storing data into array from the url in android - java

I am beginner to the android. I want to store the a the data from the web link..
I will give you the link..which have only one value.
"https://api.thingspeak.com/channels/305276/fields/1/24?api_key=KD5IR14FQW33TM4Y"
I want to assign the value coming from the link to a variable in my android program..i am trying but i didn't get..please help me..
This is the code actually i tried..
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.*;
import java.io.*;
public class urll {
public static String data(int i) {
URL oracle = null;
String a = null;
try {
oracle = new URL("https://api.thingspeak.com/channels/305276/fields/1/24?api_key=KD5IR14FQW33TM4Y");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = oracle.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null){
a=inputLine;
}
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(inputLine);
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
}

Related

how can send http request and get its information in Java?

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient2 {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("Incorrect number of args, exiting...");
System.exit(0);
}
String host_address = args[0];
String resource = args[1];
Socket socket =null;
PrintWriter out = null;
BufferedReader in = null;
int port=80;
try {
socket = new Socket(host_address,port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (UnknownHostException e) {
System.out.println("Unknown host");
System.exit(-1);
}
catch (IOException e) {
System.out.println("No I/O");
System.exit(-1);
}
try {
String request_line = "GET " + resource + " HTTP/1.1";
String host_header = "Host: " + host_address;
out.println(request_line);
out.println(host_header);
out.println(); // blank line = end of request header
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e) {
System.out.println("Error during communication");
System.exit(-1);
}try {
socket.close();
}
catch (IOException e) {
System.out.println("Cannot close the socket");
System.exit(-1);
}
}
}
hello ,i have just started learning java network programming, i tried to send a http request and i was expecting getting its information but it returns "No I/O" all the time but it connects to server . Can any one tell where do i make mistake ?

Exception in readObject of String

I'm trying to read a text file from the server string by string (line by line from the file).
It works good until readObject in the client side has nothing to read and than I get exception and going to "client error".
I have tried to close streams and sockets, ask questions and also I have tried to use scanner but none of the options above helped me.
Can u help me?
client side:
package hit.model;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class MMUClient {
private ArrayList<String> userDetails;
private String fileFromServer =null;
private ObjectOutputStream outToServer;
private ObjectInputStream inFromServer;
private String fileName;
private boolean ERROR = true;
private String messageError = "No Errors";
private PrintWriter printerWriter;
public MMUClient(ArrayList<String> userParameters){
userDetails = userParameters;
};
public MMUClient(String filePath){
fileName = filePath;
};
public ArrayList<String> getUserDetails() {
return userDetails;
}
public void setUserDetails(ArrayList<String> userDetails) {
this.userDetails = userDetails;
clientAuthenticate();
}
public void clientAuthenticate(){
try{
Socket myServer = null;
try {
//1. creating a socket to connect to the server
myServer = new Socket("localhost", 12345);
System.out.println("Connected to localhost in port 12345");
//2. get Input and Output streams
outToServer = new ObjectOutputStream(myServer.getOutputStream());
inFromServer=new ObjectInputStream(myServer.getInputStream());
//3: Communicating with the server
outToServer.writeObject(userDetails);
//4. get server answer
fileFromServer = (String) inFromServer.readObject();
printerWriter = new PrintWriter("logClient.txt");
if(fileFromServer.contains("Error")){
messageError = "Error";
ERROR = true;
}
else{
if (fileFromServer.contains("Wrong")){
messageError = "Wrong";
ERROR = true;
}
else
while(fileFromServer != null){
// messageError = "No Errors";
// ERROR = false;
System.out.println(fileFromServer);
printerWriter.println(fileFromServer);
// writeData(fileFromServer);
fileFromServer = (String) inFromServer.readObject();
}
printerWriter.close();
}
} catch (IOException e) {
System.out.println("Client error");
}finally{
inFromServer.close();
outToServer.close();
myServer.close();
}
}catch (Exception e) {
System.out.println("Client error Details");
}
}
//**********************write into text file from server***************************
/* private void writeData(String lineToWrite) {
FileWriter fileWriter = null;
String filetowrite = "logClient.txt";
try {
PrintWriter printerWriter = new PrintWriter(filetowrite);
printerWriter.println(lineToWrite);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
//************************if there is any error with the client******************************
public boolean getError(){
return ERROR;
}
public String getMessageError() {
return messageError;
}
public void setMessageError(String messageError) {
this.messageError = messageError;
}
}
server side:
package hit.applicationservice;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import hit.login.AuthenticationManager;
public class MMULogFileApplicationService implements Runnable {
//MMULogService logService;
AuthenticationManager authenticateDetails;
MMULogFileBrowsing browsing;
ArrayList<String> userDetails;
private Socket someClient = null;
private ObjectOutputStream outToClient;
private ObjectInputStream inFromClient;
String filePath = "/Users/oferg/Desktop/lastVirsion/MMUProject/log.txt";
public MMULogFileApplicationService (Socket socket ){
someClient = socket;
};
#Override
public void run() {
//3. get Input and Output streams
try{
outToClient = new ObjectOutputStream(someClient.getOutputStream());
inFromClient = new ObjectInputStream(someClient.getInputStream());
userDetails = (ArrayList<String>) inFromClient.readObject();
System.out.println("Connection successful ");
}catch(IOException | ClassNotFoundException ioException){
ioException.printStackTrace();
}
boolean userFound = false;
try {
authenticateDetails = new AuthenticationManager();
userFound = authenticateDetails.authenticate(userDetails.get(0), userDetails.get(1));
if(userFound)
{
browsing = new MMULogFileBrowsing(someClient, userDetails.get(2), filePath);
if(!browsing.searchIfFileExist()){
//write object to Socket
String sendMessage = "Wrong FileName the file isn't found";
outToClient.writeObject(sendMessage);
}
else{
getFileToClient();
}
}
else
{
//write object to Socket
String sendMessage = "Error - the user isn't exist";
outToClient.writeObject(sendMessage);
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inFromClient.close();
outToClient.close();
someClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void getFileToClient() throws IOException {
FileReader fileReader = null;
String currentLine = null;
try {
fileReader = new FileReader(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((currentLine = bufferedReader.readLine())!= null){
if (currentLine.isEmpty() == false ){
outToClient.writeObject(currentLine);
outToClient.flush();
}
}
outToClient.close();
bufferedReader.close();
fileReader.close();
}
}
tnx everybody for their answers.
i think i found the way to pass al the text file by the next simple loop code:
String currentLine = "";
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((tempLine = bufferedReader.readLine())!= null){
if (tempLine.isEmpty() == false ){
currentLine = currentLine+tempLine+"\n";
}
}
in that way i'm copying the text file line by line and send it to the client by 1 string and than i can do whatever i want.
tnx every1.
peace

Call static String onCreate from other Class

How can I call "getContent" inside "onCreate"?
I am getting errors like
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity: android.os.NetworkOnMainThreadException
Caused by: android.os.NetworkOnMainThreadException
main.java
protected void onCreate(Bundle savedInstanceState) {
Log.d("URL", HttpUtils.getContents("http://google.com"));
}
HttpUtils.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtils {
public static String getContents(String url) {
String contents ="";
try {
URLConnection conn = new URL(url).openConnection();
InputStream in = conn.getInputStream();
contents = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.v("MALFORMED URL EXCEPTION");
} catch (IOException e) {
Log.e(e.getMessage(), e);
}
return contents;
}
private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
In android you cann't perform any networking task on UI thread. so you will have perform Networking task on a Different thread. For this you can use normal java Threads but this is not a good approach in android. you should use Async Task.
You can follow any good tutorial on google.

Reading text file into String array, then converting to ArrayList

How can I read a file into a array of String[] and then convert it into ArrayList?
I can't use an ArrayList right away because my type of list is not applicable for the arguments (String).
So my prof told me to put it into an array of String, then convert it.
I am stumped and cannot figure it out for the life of me as I am still very new to java.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tsenyurt on 06/04/15.
*/
public class ReadFile
{
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Users/tsenyurt/Development/Projects/java/test/pom.xml"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
strings.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
there is a code that reads a file and create a ArrayList from it
http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Well there are many ways to do that,
you can use this code if you want have a List of each word exist in your file
public static void main(String[] args) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(
"Your file path"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
String[] words = sb.toString().split("\\s");
list = Arrays.asList(words);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String string : list) {
System.out.println(string);
}
}

I failed to get facebook recource page using this java code:

for a test i want to try get facebook recource page using that java code:
it is work for any other site but facebook\ twitter, any solutions?
public class ReadWebPage {
public static void main(String[] args) {
String urltext = "http://www.facebook.com";
BufferedReader in = null;
try {
URL url = new URL(urltext);
in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
What errors are returned? I suspect it has something to do with "http://www.facebook.com/" redirecting to "https://www.facebook.com". I suggest trying the https address and seeing if that corrects the problem.

Categories

Resources