How to display a ProgressDialog in an AsyncTask? - android

My Android app got one AsyncTask which gets me data from my server. When I pull a few rows from the database then it's done very fast and I don't need a loading animation while it is getting fresh data.
When I pull 2,3k rows from the database, that might slow things down so I decided to use some indicator (loading animation), so the user knows that data is collecting in the background. I got one activity Fill_in_phone where I call the asyncTask named GetOcitanja.
My code for the AsynTask is:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class GetOcitanja extends AsyncTask<Object, Void, String> {
Activity _context;
String _str_mesg;
String _str_naslov;
public ProgressDialog progress;
public GetOcitanja(Activity context, String str_naslov, String str_message){
this._context = context;
this._str_naslov = str_naslov;
this._str_mesg = str_message;
}
#Override
protected void onPreExecute() {
//super.onPreExecute();
progress = ProgressDialog.show(_context, _str_naslov,
_str_mesg, true);
progress.show();
}
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
progress.dismiss();
}
#Override
protected String doInBackground(Object... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(Config.url_get_ocitanja_async_taks);
String odg="";
try {
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
odg = EntityUtils.toString(entity, HTTP.UTF_8);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return odg;
}
As you can see, I put a 2 seconds sleep time to simulate a large dataset. I call this AsyncTask in my Fill_in_Data activity:
GetOcitanja asyncTask=new GetOcitanja(Fill_in_phone.this, "a","b");
asyncTask.execute();
String response="";
try {
response= asyncTask.get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
}
I followed a few solutions from SO and nothing helped. What did I do wrong?

response= asyncTask.get();
remove that.
You have already an asyncTask.execute().
Handle the response in onPostExecute().
I asked you before how you called your async task as i supposed you used .get(). You are calling it twice and are only showing that now.

Place your ProgressDialog in onPreExecute, sample code below:
private ProgressDialog pdia;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
https://stackoverflow.com/a/25998219/5202007

public GetOcitanja(Activity context, String str_naslov, String str_message){
this._context = context;
this._str_naslov = str_naslov;
this._str_mesg = str_message;
progressDialog = new ProgressDialog(_context);
progressDialog.setTitle("Progress");
}
can you try create progress dialog inside constructor

Related

Cannot display toast in handler (sending message to a Handler on a dead thread)

I am trying to run the background service periodically. I am using IntentService for background service along with the handler. But when I try to use Toast to confirm that service is running periodically logcat throws sending message to a Handler on a dead thread. Also when I try to use getMainLooper in handler the application doesnot run. Logcat gives "NetworkOnMainThreadException" What should I do?
package com.example.income;
import java.io.IOException;
import android.os.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.*;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.util.*;
import android.widget.Toast;
public class Background extends IntentService
{
public Background()
{
super("This is the simple background classes");
}
#Override
protected void onHandleIntent(Intent intent)
{
final Handler handler = new Handler(getMainLooper());
handler.post(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "Finally can I do it", Toast.LENGTH_SHORT).show();
Log.v("message","This is simple background services");
Db db =new Db(Background.this,"simple",null,4);
Cursor c= db.getData();
if( c.moveToFirst())
{
List<Map<String, String>> contacts = new ArrayList<Map<String, String>>();
do
{
String num,dater;
int integer;
integer=c.getInt (c.getColumnIndex(Base.Identifier));
num = c.getString(c.getColumnIndex(Base.CONTACTS));
dater =c.getString(c.getColumnIndex(Base.DATE));
Map<String, String> contact = new HashMap<String, String>();
contact.put("date", dater);
contact.put("contact", num);
contact.put("id",String.valueOf(integer));
contacts.add(contact);
}
while (c.moveToNext());
try
{
sendData(contacts);
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
}
handler.postDelayed(this, 10000);
}
});
}
public void sendData(List<Map<String, String>> contacts) throws ClientProtocolException, IOException, JSONException
{
Log.v("Let's C","Will it go here?");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.10.116/android1.php");
Log.v("p","this");
Log.d("Contacts", Integer.toString(contacts.size()));
JSONArray array= new JSONArray(contacts);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("forward",array.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response= httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
JSONObject myJsonObject = new JSONObject(result);
String idstring=myJsonObject.optString("id").toString();
JSONArray idarray = new JSONArray(idstring);
int[] intArray = new int[idarray.length()];
Db db =new Db(Background.this,"simple",null,4);
for(int i=0;i<idarray.length();i++)
{
Log.i("successfully deleting]","deleted");
intArray[i]=Integer.parseInt(idarray.getString(i));
db.deletedata(intArray[i]);
}
}
}
This is due to a bug in AsyncTask in the Android framework.
It expects this to be initialized on the main thread, but that is not guaranteed since it will be initialized on whichever thread happens to cause the class to run its static initializers. I reproduced this issue where the Handler references a worker thread.
Try this code:
public class Background extends IntentService
{
Handler mMainThreadHandler = null;
public Background() {
super("This is the simple background classes");
mMainThreadHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent)
{
mMainThreadHandler.post(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "Finally can I do it", Toast.LENGTH_SHORT).show();
Log.v("message","This is simple background services");
Db db =new Db(Background.this,"simple",null,4);
Cursor c= db.getData();
if( c.moveToFirst())
{
List<Map<String, String>> contacts = new ArrayList<Map<String, String>>();
do
{
String num,dater;
int integer;
integer=c.getInt (c.getColumnIndex(Base.Identifier));
num = c.getString(c.getColumnIndex(Base.CONTACTS));
dater =c.getString(c.getColumnIndex(Base.DATE));
Map<String, String> contact = new HashMap<String, String>();
contact.put("date", dater);
contact.put("contact", num);
contact.put("id",String.valueOf(integer));
contacts.add(contact);
}
while (c.moveToNext());
try
{
new Thread(new Runnable() {
#Override
public void run() {
try {
sendData(contacts);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
}
handler.postDelayed(this, 10000);
}
});
}
EDIT:
Your sendData() is performing network calls. This exception is thrown when an application attempts to perform a networking operation on its main thread. you need to call sendData() method in another thread.
This is due to Net-work-operation your are trying to perform on main thread
Just do one thing
public class SendContacts extends AsyncTask<Void,Void,Void>{
List<Map<String, String>> contacts;
public SendContacts(List<Map<String, String>> contacts) {
this.contacts = contacts;
}
public SendContacts() {
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... voids) {
sendData(contacts);
return null;
}
}
where you are calling sendData(contacts);
replace with this
new SendContacts(contacts).execute();

How to Show progrssbar in Android

I want to add progress bar to android project to show upload files. here is my code for upload images to server. postFile() is working fine. How to visible progress bar?
I want to add progressbar here.pleas see this code in the class
//Progrssbar Visible here
postFile();
//Progrssbar Invisible here
Here is the class
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
public String DataSendingTo="http://www.mysite.com/receiver.php/Incoming_Data_Receive";
public String txtDescription;
public static String[] FileNameStrings = new String[8];
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... strings) {
try
{
//Progrssbar Visible here
postFile();
//Progrssbar Invisible here
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
private void postFile(){
try{
// the file to be posted
for(int f=0;f <FileNameStrings.length;f++)
{
String textFile = FileNameStrings[f];
if(textFile==null)
{
break;
}
Log.v("Sending", "textFile: " + textFile);
// the URL where the file will be posted
Log.v("Sending", "postURL: " + DataSendingTo);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(DataSendingTo);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("Sending", "Response: " + responseStr);
//wait(1500);
}
}
} catch (NullPointerException e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show();
}
}
}
Add below code to your AsyncTask
class PostDataAsyncTask extends AsyncTask<String, String, String> {
private ProgressDialog mDialog = null;
public PostDataAsyncTask(Context activityContext) {
mDialog = new ProgressDialog(activityContext);
}
protected void onPreExecute() {
super.onPreExecute();
mDialog.setMessage("Wait...");
mDialog.setCancelable(false); // Depends on app behaviour
mDialog.show();
}
#Override
protected String doInBackground(String... strings) {
// Same as your implementation
}
#Override
protected void onPostExecute(String lenghtOfFile) {
if (mDialog != null)
mDialog.dismiss();
}
}
And call this as
PostDataAsyncTask postDataAsyncTask = new PostDataAsyncTask(Youractivity_name.this);
postDataAsyncTask.execute(With_your_params);
you can se ein this example just call progressdialog in onPreExecute() method.,and refer this example.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** Reference to the view which should receive the image */
private final WeakReference imageRef;public DownloadImageTask(ImageView imageView) {
imageRef = new WeakReference(imageView);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
URL url = new URL(params[0]);
// We open the connection
URLConnection conection = url.openConnection();
conection.connect();
input = new BufferedInputStream(url.openStream(), 8192);
// we convert the inputStream into bitmap
bitmap = BitmapFactory.decodeStream(input);
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
} else
Toast.makeText(DownloadImageActivity.this, "Error while downloading the image!", Toast.LENGTH_LONG).show();
}
}
}

android: hide progressdialog whe the app regain control

I've an app that opens the facebook app when you click on a button, it works fine but on slow devices (like mine) facebook takes some seconds to show up, so i want to add a simple progressdialog that says "please wait"
i can show the progress dialog and open facebook with this code:
final ProgressDialog pd = ProgressDialog.show(contatti.this, "", "Attendere...", true);
Intent facebookIntent = getOpenFacebookIntent(getApplicationContext());
startActivity(facebookIntent);
//pd.dismiss();
the first time i tried, it worked fine but when i went back from facebook to my app the dialog was still showing, and i had no way to close it.
added dismiss() to try hide it, but it was a stupid idea >.<
how can i dismiss the dialog when the app regain control?
For this situation you have to check whether the application is sent background or not in on pause if it sent to background then close the dialog.
for checking the application is in bacground or not just have a look
android:how to check if application is running in background
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.gvsu.cis.toptracks.R;
import edu.gvsu.cis.toptracks.TopTrackListActivity;
import edu.gvsu.cis.toptracks.data.Customer;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class LastWebAPITask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private TopTrackListActivity activity;
private static final String debugTag = "LastWebAPITask";
public LastWebAPITask(TopTrackListActivity activity) {
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_tracks), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
Log.d(debugTag, "Background:" + Thread.currentThread().getName());
String result = LastHelper.downloadFromServer(params);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<Customer> trackdata = new ArrayList<Customer>();
progDialog.dismiss();
if (result.length() == 0) {
this.activity.alert("Unable to find track data. Try again later.");
return;
}
try {
JSONObject respObj = new JSONObject(result);
JSONArray tracks = respObj.getJSONArray("GetStockListResult");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String Inventory_Status = track.getString("Inventory_Status");
String modify_Date = track.getString("modify_Date");
String msg = track.getString("msg");
String serial_nbr = track.getString("serial_nbr");
;
trackdata
.add(new Customer(Inventory_Status, modify_Date, msg, serial_nbr));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.activity.setTracks(trackdata);
}
}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class LastHelper {
private static final String LastUrl = "http://etosxmldev.ctdi.com/ws/wcf/UNIVERSAL-DEMO/Service.svc/GetStockList?LocationId=300779360.svc/GetStockList/1111";
private static final int HTTP_STATUS_OK = 200;
private static byte[] buff = new byte[1024];
private static final String logTag = "LastHelper";
public static class ApiException extends Exception {
private static final long serialVersionUID = 1L;
public ApiException(String msg) {
super(msg);
}
public ApiException(String msg, Throwable thr) {
super(msg, thr);
}
}
protected static synchronized String downloadFromServer(String... params)
throws ApiException {
String retval = null;
String url = LastUrl;
Log.d(logTag, "Fetching " + url);
// create an http client and a request object.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
// execute the request
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
// handle error here
throw new ApiException("Invalid response from last.fm"
+ status.toString());
}
// process the content.
HttpEntity entity = response.getEntity();
InputStream ist = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readCount = 0;
while ((readCount = ist.read(buff)) != -1) {
content.write(buff, 0, readCount);
}
retval = new String(content.toByteArray());
} catch (Exception e) {
throw new ApiException("Problem connecting to the server "
+ e.getMessage(), e);
}
return retval;
}
}
U have to use Asynctask class for doing this.Working Example for me.in your Activity class
LastWebAPITask lfmTask = new LastWebAPITask(
TopTrackListActivity.this);
lfmTask.execute(metroTxt);
thanks to another forum. looks like the fastest and simple way to do this is using onResume():
#Override
public void onResume(){
super.onResume();
if(waitdialog != null){ //check if we are resuming (not coming from another activity)
if (waitdialog.isShowing()) { //check if is showing
waitdialog.dismiss(); //dismiss
}
}
}

error posting data to webservice

I want to post data using JSON. But i am not able to achieve this.
This is my java code:
package com.bandapp;
import java.util.ArrayList;
import java.util.HashMap;
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.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 org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class UpcomingShow extends ListActivity {
public static final String TAG_SHOW_TITLE = "show_title";
public static final String TAG_SHOW_VENUE = "show_venue";
public static final String TAG_SHOW_DATE = "show_date";
public static final String TAG_SHOW_TIME = "show_time";
public static String URL = "http://example.com/example/example/mainAPI.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upcoming_show);
new AsyncData().execute();
}
class AsyncData extends AsyncTask<String, Void, Void> {
JSONParser jParser;
ArrayList<HashMap<String, String>> upcomingShows;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(UpcomingShow.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
upcomingShows = new ArrayList<HashMap<String,String>>();
params.add(new BasicNameValuePair("rquest", "={"));
params.add(new BasicNameValuePair("method","band_info"));
params.add(new BasicNameValuePair("body","[{}]}"));
String res = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
res = EntityUtils.toString(response.getEntity());
JSONTokener t = new JSONTokener(res);
JSONArray a = new JSONArray(t);
JSONObject o = a.getJSONObject(0);
String sc = o.getString(TAG_SHOW_TITLE);
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(UpcomingShow.this, upcomingShows, R.layout.upcomingshows_row, new String[] {
TAG_SHOW_TITLE, TAG_SHOW_DATE, TAG_SHOW_TIME, TAG_SHOW_VENUE }, new int[] { R.id.textTitle, R.id.textdate,
R.id.textTime, R.id.textVenue });
setListAdapter(adapter);
}
}
}
Also i am not able to Toast any of the message that i have kept in doInBackground(). Can you please help me solving this please...
You can't toast into doInBackground() because you can't update the UIview during the thread execution ! You should to use 'onProgress' and 'publishProgress'
change :
class AsyncData extends AsyncTask<String, Void, Void>
to:
class AsyncData extends AsyncTask<String, String, Void>
and override onProgress for toast:
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (values[0] != null)
Toast.makeText(UpcomingShow.this, values[0], Toast.LENGTH_SHORT).show();
}
And into doInBackground():
if(sc.equals("1"))
{
publishProgress(sc);
}
else
{
publishProgress("Fail.");
}
if(sc.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
Remove this code form doInBackground
You can not update your UI on do in background , you can get result in onPostExecute and able to pop up those toast .
I tried sending a post your request through Postman(google extension) and the URL you've provided responded with HTTP Status 200 but without a response message. Problem is, based on the code provided, is that you're expecting a message response from the said url. You should probably check with the server you are connecting with.
While doing AsyncTask<String, Void, Void> Task you can’t achieve Toast display in Main thread, user Log.d(“TAG”,”your-text”);
You can achieve Toast in onPostExecution()
}catch (Exception e)
{
e.printStackTrace();
}
return sc;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if(result.equals("1"))
{
// posted successfully
Toast.makeText(UpcomingShow.this, result, Toast.LENGTH_SHORT).show();
}
else
{
// error occurred
Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
}
}
}

Using HttpGet on Android

I can't understand, why I can't get http response without error from any url.
package de.vogella.android.asynctask;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class SimpleWebGrab extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
grabURL("http://android.com");
}
public void grabURL(String url) {
//new GrabURL().execute(url);
GrabURL grabURL = new GrabURL(); // Создаем экземпляр
grabURL.execute(url); // запускаем
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(SimpleWebGrab.this);
protected void onPreExecute() {
Dialog.setMessage("Загрузка данных..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(SimpleWebGrab.this, Error, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SimpleWebGrab.this, "Источник: " + Content, Toast.LENGTH_LONG).show();
}
}
}
}
I get error on this lines:
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
Error text is:
Connection to http://android.com refused
It doesn't matter which url I use. All the same. On this line after Step Into I get Class file editor: "source not found" message while debugging, but app doesn't crash if I press Run:
HttpGet httpget = new HttpGet(urls[0]);
Is it the reason of connection refused? If yes, how to fix it? Thanks in advance.
This is just a guess, but maybe this is because you are running the request on the main thread?
You should usually prepare a background thread that will run this code for you.
The code looks approximately like this:
Runnable r = new Runnable() {
void run()
{
// enter here httpget code
}
}
new Handler().post(r);
Did you added permission "android.permission.INTERNET" to your AndroidManifest.xml?
I found out, that this is a common problem, when there is no internet on emulator. I solved my problem by typing -http-proxy xxx.xx.111.1:3128 in Run->Run Configurations->Target->Additional Command Line Options(which is at the bottom, need to scroll). This is where I found a solution: http://www.gitshah.com/2011/02/android-fixing-no-internet-connection.html

Categories

Resources