AsyncTask that updates a progress bar - java

I have an AsyncTask that currently shows a spinner dialog on login but it doesn't work very well from a user perspective it goes and gets everything then kind of spins into the second intent when it's done - it looks fine when you have a good signal but it works rubbish when the signal is bad or when it jumps from 3G to wifi mid sentence
so. what I want is a login page that works by showing a progressbar dialog on submit click and only once it's DONE jump to the 2nd intent
Here is what I have so far
package com.pprem.include;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Include_CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
then it is called by this in the actual activity
status="passed";
final class GetUserHttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
publishProgress(true);
try {
getUserPhpResponse = Include_CustomHttpClient.executeHttpPost(settings.getServer() + "getUser.php", postParameters);
return getUserPhpResponse;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String getUserPhpResponse) {
publishProgress(false);
//result = result.replaceAll("\\s+","");
settings.setFullname(getUserPhpResponse);
JSONObject jObject;
try {
jObject = new JSONObject(getUserPhpResponse);
settings.setFullname(jObject.getString("fullname"));
settings.setAdministrator(jObject.getString("administrator"));
if (status=="passed"){
//start the second Activity
gotofrmListSchema.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
gotofrmListSchema.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(gotofrmListSchema);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
new GetUserHttpTask().execute();

I think you need something like this
private class RemoteTask extends AsyncTask<Object, Void, String > {
private ProgressDialog dialog;
private Context context;
private RemoteTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage(getResources().getString(R.string.loading));
dialog.show();
}
#Override
protected String doInBackground(Object... objects) {
return client.executeGet(objects[0]);
}
#Override
protected void onPostExecute(String result) {
if (dialog.isShowing())
dialog.dismiss();
...
//start new activity here
}
}

Related

How to upgrade from HTTPClient to volley

In this class I am sending request to server asynchronously by extending AsyncTask using HttpClient, I have created two custom classes one for Uploading and Downloading of Images from the server, and other for sending JSON Object and array. Beside this I'm also able to differentiate the requests using RequestTag
Can we also do the same using volley?
How can I upgrade to Volley from the HttpClient having same approach like in below class?
package com.creative.projectmanager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import org.apache.commons.logging.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* server manager class. performs all server requests asynchronously
*/
public class ServerManager {
final private String SERVER_ADDRESS = "http://192.168.200.10/";
public void login(String email, String password, int requestTag) {
String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
HashMap<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
params.put("authenticate", "false");
android.util.Log.w("My App", email + " " + password + " " + requestTag);
AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
requestSender.execute();
}
public void downloadImage(String imageUrl, int imageSize, int requestTag) {
ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
imageDownloadTask.execute();
}
private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
private String url = "";
private HashMap<String, String> postParams = null;
private int requestTag;
private String errorMessage = "";
public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
this.url = url;
postParams = params;
this.requestTag = tag;
}
#Override
protected String doInBackground(Void... params) {
byte[] result;
String resultString = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
for (String key:postParams.keySet()
) {
nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
}
android.util.Log.w("My App",nameValuePairs.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
errorMessage = "ok";
result = EntityUtils.toByteArray(response.getEntity());
resultString = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
errorMessage = "Encoding is not supported";
}
catch (Exception e) {
errorMessage = "An error occurred";
}
return resultString;
}
#Override
protected void onPostExecute(String s) {
if (errorMessage.equals("ok")) {
sourceActivity.requestFinished(s, requestTag);
}
else
sourceActivity.requestFailed(errorMessage, requestTag);
}
}
private class ImageDownloadTask extends AsyncTask<String, String, String> {
private String imageUrl;
private int imageSize;
private int requestTag;
Bitmap image;
public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
this.imageUrl = imageUrl;
this.imageSize = imageSize;
this.requestTag = requestTag;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(imageUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
image = createScaledBitmapFromStream(inputStream, imageSize);
}
catch (Exception e){
//do nothing
}
return null;
}
#Override
protected void onPostExecute(String s) {
sourceActivity.imageDownloaded(image, requestTag);
}
protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
try {
BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
if (minimumDesiredBitmapSize > 0) {
BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
decodeBoundsOptions.inJustDecodeBounds = true;
bufferedInputStream.mark(32 * 1024);
BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
bufferedInputStream.reset();
int originalWidth = decodeBoundsOptions.outWidth;
int originalHeight = decodeBoundsOptions.outHeight;
decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
}
return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
}
catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
bufferedInputStream.close();
} catch (IOException ignored) {}
}
}
}
}
There are a lot of examples of how to make requests with Volley, so "upgrading" will mean rewriting your code in different way.
Volley, in my opinion is not the best library for HTTP calls, I would recommend you to try
http://square.github.io/retrofit/
for loading images use http://square.github.io/picasso/ or glide. These libraries will help you make you code cleaner whit out boilerplate stuff.

how to send string from Android to php

i was trying to create an online apps. I would like to send a string from my apps to my PHP script, but it ended up with the php doesn't receive any string from my apps, which means the PhP will echo back NULL. I have been doing research online and searching for solution, but none of them worked.
Below is my MainActivity.java code:
package my.com.tutionathome.calvinlau.testserver;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b;
EditText et;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
et= (EditText)findViewById(R.id.EditText01);
tv= (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
Thread thread = new Thread()
{
#Override
public void run() {
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $"username" = $_POST['username'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
tv.setText("Response from PHP : " + response);
}
});
}catch(Exception e){
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
}
});
System.out.println("Exception : " + e.getMessage());
}
}
};
thread.start();
}
});
}
}
And my php code:
<?php
// put your code here
$hostname_localhost ="localhost";
$database_localhost ="android";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select Email, Username from tblmember where Username = '".$username."' AND Email = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($username == NULL){
echo "NULL";
}else{
echo $username;
}
?>
This is my Android Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.com.tutionathome.calvinlau.testserver">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
There are a bunch of libraries to facilitate this, saving many lines of code, i particularly suggest retrofit.
Try this Code.
AysncyTask
private class AysncyTask extends AsyncTask<Void,Void,Void>
{
private ProgressDialog regDialog=null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
regDialog=new ProgressDialog(this);
regDialog.setTitle(getResources().getString(R.string.app_name));
regDialog.setMessage(getResources().getString(R.string.app_pleasewait));
regDialog.setIndeterminate(true);
regDialog.setCancelable(true);
regDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
et.getText().toString().trim()));
postParameters.add(new BasicNameValuePair("password",
etpass.getText().toString().trim()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php",
postParameters);
res = response.toString();
return res;
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(3000);
// error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
}
} catch (Exception e) {
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(regDialog!=null)
{
regDialog.dismiss();
//do you code here you want
}
// do what u do
}
SimpleHttpClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpatch(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

android-asyncTask keeps looping

Im kinda new in android development, Im trying to do a login process for app, i have successfully complete the process with http post method on a php script on my local host, however to make my login process nicer i decided use progressdialog to show when the authentication process runs but the progress keeps looping. Below is my code:
LoginActivity.java - login button:
opt = new HttpRequest();
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private boolean authResult = false;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
if(opt.loginAuth(txtUsername.getText().toString(), txtPassword.getText().toString())){
Log.i(Data.tagInfo,"Redirecting to mainpage");
opt.showToast(LoginActivity.this,"Login Successful");
startActivity(new Intent("com.example.MainActivity"));
}
else{
opt.showToast(LoginActivity.this,"Login Fail");
Log.i(Data.tagError,"Login Fail");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
btnLogin.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
});
HttpRequest.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.util.Log;
public class HttpRequest extends Operations {
public boolean loginAuth(String user , String pass){
//Log.i("Info",user+"|"+pass);
String folder = "mobileapp",
script = "/loginAuth_m-script.php",
fullpath = folder+script,
parameter = "username="+user+"&password="+pass,
result = "";
try {
JSONArray jArray = convertJSON(new SendRequest().execute(fullpath,parameter).get());
result = getSpecificJSONdata(jArray,"result");
Log.i(Data.tagInfo,"Login result:"+result);
if(result.equals(Data.success)){
Log.i(Data.tagInfo,"loginAuth() return true");
return true;
}
else{
Log.i(Data.tagInfo,"loginAuth() return false");
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i(Data.tagError,"Error:"+e.toString());
return false;
}
}
private class SendRequest extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg) {
// TODO Auto-generated method stub
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
try
{
url = new URL("http://"+Data.host+"/"+arg[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(arg[1]);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Log.i("Info","Server Response:"+response);
isr.close();
reader.close();
return response;
}
catch(IOException e)
{
Log.i("InfoError",e.toString());
return "";
// Error
}
}
}
}
Thanks alot in advance^^

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

Why this doesn't work for ICS [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange NetworkOnMainThreadException in Android app?
Trying To Upload To Dropbox: NetworkOnMainThreadException?
I have used the below code for reading HTML contents from a url. This works perfectly for 2.3.3 but when I try to run the same code it doesn't work for ICS.
I am trying to append these html contents on to a edittext. But it always remains empty when I run the code on ICS. What may be the problem?
public class Quiz1Activity extends Activity {
private static BufferedReader reader = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText ed = (EditText) findViewById(R.id.editText1);
try {
ed.append(getStringFromUrl("http://www.google.com"));
//getInputStreamFromUrl("").close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}
public static String getStringFromUrl(String url) throws IOException{
reader = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
}
Like #Vipul Shah said you have to move getInputStreamFromUrl() into another thread use Async Task, this is work on ICS:
package com.home.anas;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.EditText;
public class WebPageContentActivity extends Activity {
private EditText ed;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText) findViewById(R.id.editText1);
readWebpage();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
ed.setText(result);
}
}
public void readWebpage() {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.google.com" });
}
}
But it always remains empty when I run the code on ICS. What may be the problem?
Issue is ICS don't allow you do asynchronous task on main thread so move your asynchronous into new thread.
You should move following code in seperate thread.
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}

Categories