Call static String onCreate from other Class - java

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.

Related

storing data into array from the url in android

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;
}
}

CLOB to String conversion + java 1.8

The below program is always giving the exception
"java.sql.SQLRecoverableException: Closed Connection" in this line of " final Reader reader = clb.getCharacterStream();"
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
public class ClobStringConversion {
public static String clobStringConversion(Clob clb) throws IOException, SQLException
{
if (clb == null)
return "";
StringBuffer sb = new StringBuffer();
String strng;
try{
final Reader reader = clb.getCharacterStream();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
sb.append((char)b);
}
br.close();
}
catch (SQLException e)
{
//log.error("SQL. Could not convert CLOB to string",e);
return e.toString();
}
catch (IOException e)
{
//log.error("IO. Could not convert CLOB to string",e);
return e.toString();
}
return sb.toString();
}
}
You are probably closing the connection before calling clobStringConversion(). Try closing the connection after reading the Clob.

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

Example of POST request in Android studio

I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:
Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.
package cc.demorest;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("myserver.com");
}
//Downloadtask
public class DownloadTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data=reader.read();
while (data !=-1){
char current=(char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//After download task
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray jArray=new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(1);
//Logging data
Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
", Name: " + json_data.getString("Name") +
", Years: " + json_data.getString("Age") +
", Email address: " + json_data.getString("Email")
);
TextView textView = (TextView) findViewById(R.id.textViewName);
textView.setText("ID: "+", Name: "+ json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));
/*
String data = jsonObject.getString("Name");
Log.i("Website content", data);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards
Use HttpURLConnection, it does not use external libraries. If you're going to use an HttpURLConnection, it needs to be an AsyncTask.
Here is my code from a project I completed. Hope it helps.
First, put this in your manifest.xml file before :
<uses-permission android:name="android.permission.INTERNET" />
Calling the AsyncTask:
(Ignore the this, SinceTime, and GoesAddress. They are just variables I passed in)
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
new ReceiveData(this, SinceTime, GoesAddress).execute(url);
The Class:
package com.ryan.scrapermain;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class ReceiveData extends AsyncTask<URL, Integer, Long> {
String response = "";
String SinceTime;
String GoesAddress;
Context myContext;
ReceiveData(Context context, String since, String goes) {
this.myContext = context;
SinceTime = since;
GoesAddress = goes;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder feedback = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
feedback.append("&");
feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
feedback.append("=");
feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return feedback.toString();
}
public void getData() throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("DCPID", GoesAddress);
params.put("SINCE", SinceTime);
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
HttpURLConnection client = null;
try {
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
// You need to specify the context-type. In this case it is a
// form submission, so use "multipart/form-data"
client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
client.setDoInput(true);
client.setDoOutput(true);
OutputStream os = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = client.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
}
else {
response = "";
}
}
catch (MalformedURLException e){
e.printStackTrace();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
#Override
protected Long doInBackground(URL... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
// This counts how many bytes were downloaded
final byte[] result = response.getBytes();
Long numOfBytes = Long.valueOf(result.length);
return numOfBytes;
}
protected void onPostExecute(Long result) {
System.out.println("Downloaded " + result + " bytes");
// This is just printing it to the console for now.
System.out.println(response);
// In the following two line I pass the string elsewhere and decode it.
InputCode input = new InputCode();
input.passToDisplay(myContext, response);
}
}
Use Volley as defined here. It's far more easier.

IOException, must be caught or declared to be thrown

This code is from the below link. I tried to run it but got the following error:
Thelink
D:\Android_Dosyalar\Proje\TextToArray\app\src\main\java\chessactivetexttoarray\com\texttoarray\MainActivity.java
Error:(40, 21) error: unreported exception IOException; must be caught or declared to be thrown
Error:(41, 22) error: unreported exception IOException; must be caught or declared to be thrown
Error:(42, 21) error: unreported exception IOException; must be caught or declared to be thrown
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
What possibly is wrong. The following part is underlined in red as well.
New to android. Novice level.
Thank you all in advance.
Regards
br.close();
isr.close();
is.close();
Read and split text file into an array - Android
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager manager;
String line = null;
List<String[]> xyzList = new ArrayList<String[]>();
String[][] xyz;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
manager = getAssets();
is = manager.open("C:\\Users\\serhat\\Copy\\satranc\\Akdag_Reportaj\\dan_akdag.pgn");
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
xyzList.add(line.split(" "));
}
xyz = (String[][]) xyzList.toArray();
} catch (IOException e1) {
Toast.makeText(getBaseContext(), "Problem!", Toast.LENGTH_SHORT).show();
} finally {
br.close();
isr.close();
is.close();
}
}
}
The close methods can throw an exception. So they need to catch them.
} finally {
try {
br.close();
isr.close();
is.close();
} catch(IOException e) {
e.printStackTrace();
}
}
You also have one other issue in your code that will cause it to fail at run time. You are trying to use the AssetManager to open a file on your windows computer and not the phone. Move the file into your your projects' assets folder and then change
is = manager.open("C:\\Users\\serhat\\Copy\\satranc\\Akdag_Reportaj\\dan_akdag.pgn");
to
is = manager.open("dan_akdag.pgn");
You need to catch the IOException that the close methods may throw:
e.g.
finally {
try {
br.close();
isr.close();
is.close();
} catch (IOException e) {
// dosomething
}
}
The close method throws an IOException. You don't have a try/catch block surrounding the close methods. Your code should look like:
...
} finally {
try {
br.close();
isr.close();
is.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}

Categories

Resources