FTP file upload Android Studio - java

so I am developing an app to take in a file and upload it to an FTP server, but i keep getting android.os.NetworkOnMainThreadException. Any ideas on how to fix this?
This is my code
public void sendData() throws Exception {
FTPUploader stuff = new FTPUploader("xxx","xxx","xxx");
stuff.doInBackground();
}
FTPUploader Class:
import android.os.AsyncTask;
import org.apache.commons.net.ftp.FTPClient;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
public class FTPUploader extends AsyncTask<String, Void, Void> {
//#Override
protected Void doInBackground(String... params) {
FTPClient con = new FTPClient();
try {
con.connect(InetAddress.getByName(params[0]));
if (con.login(params[1], params[2])) {
con.enterLocalPassiveMode();
String data = params[3];
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
boolean result = con.storeFile(params[4], in);
in.close();
if (result) {
System.out.println("upload result: " + result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
con.logout();
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

You would need to call from your main activity or class instead of doInBackground ()
new FTPUploader().execute(param1,param2,param3);

Related

Wait for the server response using callback java

I am creating a Quiz app on android studio and the questions will be called from an URL containing a JSONObject, and since these API calls happen asynchronously,
i have to make sure that my app is waiting for the server to respond with a callback, below is the parsing method i created following some internet tutorials, it would be nice if you could help me understand which changes should i apply
private void jsonParse(){
final Question[] quest =new Question[10];
String url="https://opentdb.com/api.php?amount=10";
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja=response.getJSONArray("results");
for(int i=0;i<3;i++){
JSONObject temp_quest=ja.getJSONObject(i);
String question =temp_quest.getString("question");
String correctanswer=temp_quest.getString("correct_answer");
String incorrectanswer_1=(String)temp_quest.getJSONArray("incorrect_answers").getString(0);
String incorrectanswer_2=(String)temp_quest.getJSONArray("incorrect_answers").getString(1);
String incorrectanswer_3=(String)temp_quest.getJSONArray("incorrect_answers").getString(2);
String[] temp=new String[3];
temp[0]=incorrectanswer_1;
temp[1]=incorrectanswer_2;
temp[2]=incorrectanswer_3;
quest[i]=new Question(question,correctanswer,temp);
mTextViewResult.append(quest[i].getQuestion()+" \n"+ quest[i].getCorrectAnswer()+"\n "+
quest[i].getAnswer(1)+"\n "+quest[i].getAnswer(2)+"\n "+
quest[i].getAnswer(3)+"\n" +quest[i].getAnswer(4)+"\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
I consider that you are not using the correct form to call a service.
You can use a async task
package principal.concrete.concrete;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Post extends AsyncTask<String, Void, String> {
private InputStreamReader inputStreamReader;
private BufferedReader bufferedReader;
#Override
protected String doInBackground(String... params){
try {
URL obj = new URL(params[0]);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", " ");
con.connect();
inputStreamReader=new InputStreamReader(con.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader.readLine();
}catch(Exception e){
Log.d("Url doInBackground", e.toString());
return null;
} finally {
try {
closeConnection();
} catch(Exception e){
}
}
}
private void closeConnection() {
try {
if(bufferedReader!=null){
bufferedReader.close();
}
if(inputStreamReader!=null){
inputStreamReader.close();
}
}catch(IOException ex){
Log.d("Url disconnect", ex.toString());
}
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
You can use a retrofit to call a service
link the implementation
https://programacionymas.com/blog/consumir-una-api-usando-retrofit
I have a code to call service
asyn task

I am unable to get the HTML code from URL in Android Studio

package com.example.webcontentdownload;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[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 += result;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Failed Malformed";
} catch (IOException e) {
e.printStackTrace();
return "Failed IOException";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("https://www.google.com/").get();
Log.i("Contents of URL" , result);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
**This is my code, I am trying to get the html code of any URL.
I have tried the url connection method. I tried to re-install the avd also, sometimes i get
Emulator: socketTcpLoopbackClientFor: error: fd 35124 above FD_SETSIZE (32768)
Emulator: emulator: ERROR: AdbHostServer.cpp:102: Unable to connect to adb daemon on port: 5037.
This is displayed in my EVENT LOG.
I would very much like your help **
The log I am getting is here.

Unable to manage multiple clients (android devices) for a single java server

I need my server to keep track of each of it's client's connection. I've been advised to use Threads. So what I'm trying to achieve is to create a Thread for each client, which should run till the client connection exists. But what is happening is that for each message any client sends, a new client connection gets created in the doInBackground() function. So instead of having one single thread for one single client, I'm getting one thread for any client message sent to the server. Can you suggest a method in with which my server would be able to distinguish different messages sent from different clients?
Java Server Code :
package com.nss.academyassistserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class AcademyAssistServer {
public static ServerSocket serverSocket;
public static Socket clientSocket;
static final int PORT = 4444;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(PORT); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: "+PORT+" \n");
}
System.out.println("Server started. Listening to the port "+PORT);
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("New connection accepted."); // accept the client connection
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
//new thread for a client
new EchoThread(clientSocket).start();
}
}
}
class EchoThread extends Thread {
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
String fromClient;
Socket clientSocket;
public EchoThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
} catch (IOException e) {
return;
}
while (!Thread.currentThread().isInterrupted()) {
System.out.println("I am thread " + Thread.currentThread().getId());
try {
fromClient = bufferedReader.readLine();
if ((fromClient == null) || fromClient.equalsIgnoreCase("exit")) {
System.out.println("You're welcome, bye!");
return;
} else {
System.out.println(fromClient);
Thread.currentThread().interrupt();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Activity Code:
package com.nss.academyassist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
//import statements for client
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
//import statements for client
import android.os.AsyncTask;
public class MainActivity extends Activity implements OnClickListener {
EditText question;
//Client sockets
private Socket client;
private PrintWriter printwriter;
private String toTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
question = (EditText)findViewById(R.id.editText1);
Button query = (Button)findViewById(R.id.button2);
query.setOnClickListener(this);
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("Server IP Address", 4444);
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(toTag); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.button2:
toTag = question.getText().toString();
// Output the result
Toast.makeText(getApplicationContext(), toTag,
Toast.LENGTH_LONG).show();
//Invoke the execute method of AsynTask, which will run the doInBackground method of SendMessage Class
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
break;
}
}
}
You can use IP to tell the clients. Use
clientSocket.getInetAddress().getHostAddress()
You can also keep the client not closed in the android code. For example, you may open the Socket in onCreate and close it in onDestroy.
The cause for your problem is in your client code. Using new Socket(..) your client will create a new connection each time it sends a tag to the the server. So instead of that you could create a single connection that is reused:
public class MainActivity extends Activity implements OnClickListener {
/* .. your other variables .. */
private Socket client;
private PrintWriter printwriter;
#Override
protected void onCreate(Bundle savedInstanceState) {
/* .. no change here .. */
}
public void onStart()
{
if(this.client != null)
{
try {
client = new Socket("Server IP Address", 4444);
printwriter = new PrintWriter(client.getOutputStream(), true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void onClose()
{
this.printwriter.close();
this.printwriter = null;
this.client.close();
this.client = null;
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
printwriter.write(toTag); // write the message to output stream
printwriter.write("\n"); // delimiter
printwriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.button2:
toTag = question.getText().toString();
// Output the result
Toast.makeText(getApplicationContext(), toTag,
Toast.LENGTH_LONG).show();
//Invoke the execute method of AsynTask, which will run the doInBackground method of SendMessage Class
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
break;
}
}
}
In addition to that you should append some delimiter to your tag/message in order for the server to be able to distinguish the content from different messages.
Since you are using BufferedReader.readLine() which seperates lines
by any one of a line feed ('\n'), a carriage return ('\r'), or a
carriage return followed immediately by a linefeed
I added a line that appends a line feed after the tag in the example above for that purpose.

Why I am getting java.lang.NullPointerException?

I am trying to test this script, to get print some demo text to my Zebra printer using Android, but I am getting a java.lang.NullPointerException. I have read is something about an initialization, but I can't identify what is the object to initializate.
this is the error:
E/AndroidRuntime(2098):
FATAL EXCEPTION: Thread-9874
Process: com.stihn.sibmovil, PID: 2098
java.lang.NullPointerException
at com.stihn.sibmovil.sendfile.SibPrint.testSendFile(SibPrint.java:88)
at com.stihn.sibmovil.sendfile.SibPrint.access$0(SibPrint.java:86)
at com.stihn.sibmovil.sendfile.SibPrint$1.run(SibPrint.java:53)
at java.lang.Thread.run(Thread.java:841)
Thanks for your help!
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Looper;
import com.stihn.sibmovil.util.SettingsHelper;
import com.zebra.sdk.comm.BluetoothConnection;
import com.zebra.sdk.comm.Connection;
import com.zebra.sdk.comm.ConnectionException;
import com.zebra.sdk.printer.ZebraPrinter;
import com.zebra.sdk.printer.ZebraPrinterFactory;
import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import com.zebra.sdk.printer.PrinterLanguage;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
public class SibPrint extends Plugin {
ProgressDialog loadingDialog;
Activity activity;
private Context context;
String macAddress;
String filepath;
public PluginResult execute(String action, JSONArray args, String callbackId) {
try {
if (action.equals("sibPrintTicket")) {
String echo = args.getString(0);
filepath = args.getString(1);
macAddress = args.getString(2);
if (echo != null && echo.length() > 0) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
Connection connection = null;
connection = new BluetoothConnection(macAddress);
try {
System.out.println("Imprimiendo ...");
connection.open();
ZebraPrinter printer = ZebraPrinterFactory
.getInstance(connection);
testSendFile(printer);
connection.close();
} catch (ConnectionException e) {
System.out.println("Error Try 1 "
+ e.getMessage());
} catch (ZebraPrinterLanguageUnknownException e) {
System.out.println("Error Catch 1 "
+ e.getMessage());
} finally {
if (activity != null && loadingDialog != null) {
loadingDialog.dismiss();
}
}
Looper.loop();
Looper.myLooper().quit();
}
}).start();
//retornar mensaje de imprimiendo
return new PluginResult(PluginResult.Status.OK, "Imprimiendo..");
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
} else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
private void testSendFile(ZebraPrinter printer) {
try {
File filepath = context.getFileStreamPath("TEST.LBL");
createDemoFile(printer, "TEST.LBL");
printer.sendFileContents(filepath.getAbsolutePath());
this.saveBluetoothAddress(this, macAddress);
} catch (ConnectionException e1) {
System.out.println("Error sending file to printer" + e1.getMessage());
} catch (IOException e) {
System.out.println("Error creating file" + e.getMessage());
}
}
private void saveBluetoothAddress(SibPrint sibPrint,
String macAddress) {
// TODO Auto-generated method stub
}
private void createDemoFile(ZebraPrinter printer, String fileName) throws IOException {
FileOutputStream os = context.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] configLabel = null;
PrinterLanguage pl = printer.getPrinterControlLanguage();
if (pl == PrinterLanguage.ZPL) {
configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes();
} else if (pl == PrinterLanguage.CPCL) {
String cpclConfigLabel = "! 0 200 200 406 1\r\n" + "ON-FEED IGNORE\r\n" + "BOX 20 20 380 380 8\r\n" + "T 0 6 137 177 TEST\r\n" + "PRINT\r\n";
configLabel = cpclConfigLabel.getBytes();
}
os.write(configLabel);
os.flush();
os.close();
}
}
you got java.lang.NullPointerException in Context
at
File filepath = context.getFileStreamPath("TEST.LBL");
you are not initialize context in your class.
please add
public void SibPrint(Context context){
this.context=context;
}
in your class.
and create consructor in Activity like
SibPrint mSibPrint = new SibPrint(MyActivity.this);
public class SibPrint extends Plugin {
ProgressDialog loadingDialog;
Activity activity;
private Context context;
String macAddress;
String filepath;
//add this method
public void SibPrint(Context context){
this.context=context;
}
.
.
.
}
Try this..
You have not initialize context that's inside testSendFile() method
File filepath = context.getFileStreamPath("TEST.LBL");
you should initialize context before using it otherwise you will get NPE

Android read json from restful service

I am trying to get a response from a service (the response comes in json).
I made my checks if the device is connected and now I need to make the http request to the service. I found out on other questions that I have to use a background thread but I am not sure I got a working sample.
So I need to find out how I can make a connection to a given uri and read the response.
My service needs to get a content header application/json in orderto return a json, so before the request I need to set this header as well.
Thank you in advance
UPDATE
package com.example.restfulapp;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity {
private int code = 0;
private String value = "";
private ProgressDialog mDialog;
private Context mContext;
private String mUrl ="http://192.168.1.13/myservice/upfields/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isOnline())
{
displayNetworkOption ("MyApp", "Application needs network connectivity. Connect now?");
}
try {
JSONObject s = getJSON(mUrl);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class Get extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... arg) {
String linha = "";
String retorno = "";
mDialog = ProgressDialog.show(mContext, "Please wait", "Loading...", true);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(mUrl);
try {
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Ok
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((linha = rd.readLine()) != null) {
retorno += linha;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return retorno;
}
#Override
protected void onPostExecute(String result) {
mDialog.dismiss();
}
}
public JSONObject getJSON(String url) throws InterruptedException, ExecutionException {
setUrl(url);
Get g = new Get();
return createJSONObj(g.get());
}
private void displayNetworkOption(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle(title)
.setMessage(message)
.setPositiveButton("Wifi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNeutralButton("Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
return;
}
})
.show();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
This throws errors:
Gradle: cannot find symbol method setUrl(java.lang.String)
Gradle: cannot find symbol method createJSONObj(java.lang.String)
After derogatory responses from EvZ who think that he was born knowing everything, I ended up with a subclass MyTask that I call like this inside the onCreate of my Activity.
new MyTask().execute(wserviceURL);
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL myurl = null;
try {
myurl = new URL(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setConnectTimeout(R.string.TIMEOUT_CONNECTION);
connection.setReadTimeout(R.string.TIMEOUT_CONNECTION);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestProperty("Content-Type", getString(R.string.JSON_CONTENT_TYPE));
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (SocketTimeoutException ste) {
ste.printStackTrace();
}
catch (Exception e1) {
e1.printStackTrace();
}
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder answer = new StringBuilder(100000);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null) {
answer.append(inputLine);
answer.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
httpConnection.disconnect();
return answer.toString();
}
else
{
//connection is not OK
httpConnection.disconnect();
return null;
}
}
#Override
protected void onPostExecute(String result) {
String userid = null;
String username = null;
String nickname = null;
if (result!=null)
{
try {
//do read the JSON here
} catch (JSONException e) {
e.printStackTrace();
}
}
//stop loader dialog
mDialog.dismiss();
}
}
lory105's answer guided me to somewhere near the answer, thanx.
here is an example of how to process the HTTP response and convert to JSONObject:
/**
* convert the HttpResponse into a JSONArray
* #return JSONObject
* #param response
* #throws IOException
* #throws IllegalStateException
* #throws UnsupportedEncodingException
* #throws Throwable
*/
public static JSONObject processHttpResponse(HttpResponse response) throws UnsupportedEncodingException, IllegalStateException, IOException {
JSONObject top = null;
StringBuilder builder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String decoded = new String(builder.toString().getBytes(), "UTF-8");
Log.d(TAG, "decoded http response: " + decoded);
JSONTokener tokener = new JSONTokener(Uri.decode(builder.toString()));
top = new JSONObject(tokener);
} catch (JSONException t) {
Log.w(TAG, "<processHttpResponse> caught: " + t + ", handling as string...");
} catch (IOException e) {
Log.e(TAG, "caught: " + e, e);
} catch (Throwable t) {
Log.e(TAG, "caught: " + t, t);
}
return top;
}
From Android 3+, the http connections must be done within a separate thread. Android offers a Class named AsyncTask that help you do it.
Here you can find a good example of an AsyncTask that performs an http request and receives a JSON response.
Remember that in the doInBackgroud(..) method you CAN'T modify the UI such as to launch a Toast, to change activity or others. You have to use the onPreExecute() or onPostExecute() methods to do this.
ADD
For the mDialog and mContext variables, add the code below, and when you create the JSONTask write new JSONTask(YOUR_ACTIVITY)
public abstract class JSONTask extends AsyncTask<String, Void, String> {
private Context context = null;
ProgressDialog mDialog = new ProgressDialog();
public JSONTask(Context _context){ context=_context; }
..

Categories