How to use Async task - android

I am trying to use a thread to do some work in the background which takes a few seconds.
I was trying to display a progress dialog but its not displaying at all.
I thought it would be better to use an Async task but whenever I try I cannot get it to work, mostly because I cannot access the variables I need to modify within the Async task.
Here is my thread which is called when a button is clicked:
Thread thread = new Thread()
{
#Override
public void run() {
try {
for (String s : dLinks) {
String pathToFile = s.substring(1));
dURLs.add(dFs.fetchLink(pathToFile, false).toString());
}
} catch (DbxException e) {
dURL = null;
e.printStackTrace();
}
}
};
thread.start();
try {
thread.join(); // I added this as the next part of my code was executing before the thread was finished
} catch (InterruptedException e) {
e.printStackTrace();
}
Could I move this to an Async task, update a progress bar or at least show a spinner AND pass back the array dURLs to the Main thread?

Here we called AsyncTask with activity's context this which will feed to AsyncTask to show ProgressDialog in these Activity while AsyncTask runs in background.
public void onCreate(Bundle savedInstanceState)
{
SpinnerDataTask spinnerDataTask = new SpinnerDataTask(this);
spinnerDataTask.execute(null);
}
AsyncTask has method which uses to do background work in doInBackground() and post the result in onPostExecute(). To show view whenever AsyncTask start working, onPreExecute() is perfect to show that something is working in background.
private class SpinnerDataTask extends AsyncTask<Void Void, Void>
{
Context context;
public SpinnerDataTask(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
for (String s : dLinks) {
String pathToFile = s.substring(1));
dURLs.add(dFs.fetchLink(pathToFile, false).toString());
}
} catch (DbxException e) {
dURL = null;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
{
pDialog.dismiss();
}
}
}

you can use like this:
public class web_api_get_thread extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(context);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.show();
progressDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
//do your work
return builder.toString();
} // protected Void doInBackground(String... params)
protected void onPostExecute(String string) {
this.progressDialog.dismiss();
// see your result here
}
}

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 de.vogella.android.asyntask.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReadWebpageAsyncTask extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.TextView01);
}
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) {
textView.setText(result);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
}
}
Create the following layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/readWebpage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Load Webpage" >
</Button>
<TextView
android:id="#+id/TextView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Placeholder" >
</TextView>
</LinearLayout>
refer to :http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

Related

How to display a ProgressDialog in an AsyncTask?

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

JSON Parsing showing NullPointerException in android

Hi I have a JSON Data and I'm getting it through url by using get method,I need to show the sender,receiver,message in Textview,I have created a JsonParser class also but after running the app its showing Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference.How to fix this issue.
Here is what I have tried
private static String url = "http://130.211.99.188/api/messages";
JSONArray _items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView1);
t2 = (TextView)findViewById(R.id.textView2);
t2 = (TextView)findViewById(R.id.textView3);
if (Utils.isNetConnected(this))
{
new Parser().execute();
}
else
Utils.showDialog(this);
}
class Parser extends AsyncTask < String, String, String > {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONData(url);
try{
_items = json.getJSONArray("_updated");
for(int i=0;i<_items.length();i++){
JSONObject object = _items.getJSONObject(i);
sender = object.getString("sender");
receiver = object.getString("receiver");
message = object.getString("message");
}
}catch(JSONException e){
e.printStackTrace();
}
return message;
}//Ending doInBackground
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
t1.setText(sender);
t2.setText(receiver);
t3.setText(message);
}
}
}
This is my JSON Data
{"_items": [{"_updated": "Thu, 01 Jan 1970 00:00:00 GMT", "sender": "556a1233aca33b3c8158de0a", "timestamp": 1433018976, "receiver": "5569c6c5aca33b3c8158de07", "_links": {"self": {"href": "messages/556a2260aca33b3c8158de11", "title": "messages"}}, "message_created": "Sat, 30 May 2015 20:49:36 GMT", "seen": false, "message": "hii", "_id": "556a2260aca33b3c8158de11", "_etag": "afa4fe57efec9abf7c5bc817a7e045a5b4467384", "_created": "Thu, 01 Jan 1970 00:00:00 GMT"},
This is the complete code, have a look at the data printed
import java.io.IOException;
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.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends Activity {
ProgressDialog pdialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new postServer().execute();
}
public String postData() throws JSONException {
// Create a new HttpClient and Post Header
String downloadedString = null;
HttpClient httpclient = new DefaultHttpClient();
// for registerhttps://te
// HttpPost httppost = new HttpPost("http://130.211.99.188/api/messages");
HttpClient myClient = new DefaultHttpClient();
// HttpPost myConnection = new HttpGet("http://130.211.99.188/api/messages");
try {
// HttpResponse response = myClient.execute(myConnection);
HttpResponse httpResponse = httpclient.execute(new HttpGet("http://130.211.99.188/api/messages"));
downloadedString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("downloadedString:in login:::"
+ downloadedString);
return downloadedString;
}
public class postServer extends AsyncTask<Void, Void, Void> {
String jsonstring = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setCancelable(false);
pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pdialog.setMessage("Loading..");
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
jsonstring = postData();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
if(pdialog!=null){
pdialog.dismiss();
}
JSONObject mainObject = new JSONObject(jsonstring);
JSONArray array=mainObject.getJSONArray("_items");
for(int i=0;i<array.length();i++){
System.out.println(array.getJSONObject(i).getString("sender"));
System.out.println(array.getJSONObject(i).getString("receiver"));
System.out.println(array.getJSONObject(i).getString("message"));
}
} catch (Exception e) {
// TODO: handle exception
if (pdialog != null) {
pdialog.dismiss();
}
System.out.println(e.getMessage());
}
}
}
}
Thanks
Have you tried just declaring the JSONArray variable without assigning it a null value? JSONArray _items;
_items = json.getJSONArray("_updated");
Change to
_items = json.getJSONArray("_items");
And
class Parser extends AsyncTask < String, String, String > {
to
class Parser extends AsyncTask < void, void, void > {
Try this code:
class Parser extends AsyncTask < String, String, String > {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONData(url);
try{
_items = json.getJSONArray("_items");
for(int i=0; i<_items.length(); i++){
JSONObject object = _items.getJSONObject(i);
sender = object.optString("sender");
receiver = object.optString("receiver");
message = object.optString("message");
}
}
catch(JSONException e){
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
t1.setText(sender);
t2.setText(receiver);
t3.setText(message);
}
}
Try to use optString() instead of getString() because the former returns null if doesn't exist and it doesn't throw an exception
Are you sure getJSONData(url) in JSONObject json = jParser.getJSONData(url); is not returning null?
Your question indicates that you are calling getJSONArray() on a null object. Which means the JSON object you queried from the parser is null

How to set progress dialog in AsyncTask

Hi I have one problem with ProgressDailog. I'm not able to set it properly in my code. In my code I'm getting URLs of images through JSON Array and downloading that images after that showing them into GridView and on click displaying selected image on next activity..This all work perfectly but the problem is As I'm using AsyncTask in my code it goes in background and fetch JSON, download images. I want to show ProgressBar till background process is completed and initialize the GridView after all images get downloaded ...
Following is my code..
public class AndroidGridLayoutActivity extends Activity {
public static ImageAdapter img;
public static String[] imageurls;
public static GridView gridView;
public static Bitmap bm[]=new Bitmap[4];
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// Showing progress dialog
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
new GetImageUrls().execute();
Thread thread = new Thread()
{
#Override
public void run() {
int count=0;
while(count<3) {
try {
sleep(1000);
count++;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
if(pDialog != null && pDialog.isShowing()){
pDialog.dismiss();
}
new GetImageUrls().execute();
}
};
thread.start();
gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
img = new ImageAdapter(AndroidGridLayoutActivity.this,bm);
gridView.setAdapter(img);
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
Log.d("DownloadImage: ", url.toString());
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
Log.d("DownloadImage response: ", Integer.toString(response));
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("DownloadImage: ", in.toString());
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
Log.d("DownloadImage Bitmap: ", bitmap.toString());
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
}
As I run this code the images get downloaded but not display on grid view and as I click on any Grid the image displays on next activity,,
ImageAdapter Class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public static Bitmap adapterbm[]=new Bitmap[4];
ImageView imageView;
public static String[] imageurls;
// Constructor
public ImageAdapter(Context c, Bitmap[] bm){
mContext = c;
adapterbm = bm;
}
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return adapterbm.length;
}
#Override
public Object getItem(int position) {
return adapterbm[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imageView = new ImageView(mContext);
imageView.setImageBitmap(adapterbm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
You should Override onPreExecute() method before doInBackground method.
ProgressDialog myPd_bar;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(AndroidGridLayoutActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(title);
myPd_bar.show();
super.onPreExecute();
}
Then you should Override onPostExecute() method after doInBackground method.
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
myPd_bar.dismiss();
}
You can find more information from this link
Place your ProgressDialog in onPreExecute, hope this code helps you out :)
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();
}
There are two more method in Async class i.e onPostExecute and onPreExecute method. in onPreExecute method you can write the following code
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
And onPostExecute method use pDialog.dismiss().
Use preExcecute to display progress dialog.
ProgressDialog pDialog;
public class GetImageUrls extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg)
{....
}
#Override
protected postExcecute()
{
pDialog.dismiss();
....//display UI
...
}
There is no need of writing Thread to show ProgressDialog.
Just simply you need to implement onPreExecute to show the dialog and onPostExecute to dismiss the dialog.
Just change your GetImageUrls method as below:
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
Start dialog in
onPreExecute()
and dismiss it
onPostExecute()
The easiest way to show progress while doing background process!
private class GetImageUrls extends AsyncTask<String, String , String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(this,null, "Loading ...", true);
progressDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... arg0) {
//background process
}
protected void onProgressUpdate(String... str) {
}
protected void onPostExecute(String result) {
progressDialog.dismiss(); // once process complete it will dismiss.
}
}
Use beelow code:
ProgressDialog mProgressDialog;
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgressDialog = ProgressDialog.show(AndroidGridLayoutActivity.this,
"", "Loading...");
mProgressDialog.setCancelable(false);
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
Log.d("DownloadImage: ", url.toString());
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
Log.d("DownloadImage response: ", Integer.toString(response));
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("DownloadImage: ", in.toString());
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
Log.d("DownloadImage Bitmap: ", bitmap.toString());
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
#Override
protected void onPostExecute(){
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
}
Try this
Activity class
package com.example.imagelist;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ItemsAdapter adapter;
ListView list;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://........................";
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion > android.os.Build.VERSION_CODES.FROYO) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
}
/*
int images[] = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
*/
list = (ListView) findViewById(R.id.listView1);
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
//build hash set for list view
public void ListDrwaer(){
List<String> listImg = new ArrayList<String>();
try{
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
listImg.add(img_url);
// Log.d("URL", img_url);
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(), listImg);
list.setAdapter(adapter);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(),"Connection Error...", Toast.LENGTH_LONG).show();
}
}
}
Adapter class
package com.example.imagelist;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class ItemsAdapter extends ArrayAdapter<Integer> {
private final Context context;
ImageView imageView;
List<String> listImg;
ItemsAdapter(Context context, List<String> listImg) {
super(context, R.layout.items_list_item);
this.context = context;
this.listImg = listImg;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listImg.size();
}
#Override
public Integer getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final String text = listImg.get(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
if (null == convertView)
rowView = inflater.inflate(R.layout.items_list_item, parent, false);
imageView = (ImageView) rowView.findViewById(R.id.list_item_image);
Bitmap bitmap;
URL imageURL = null;
try {
imageURL = new URL(text);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return rowView ;
}
}
activity_main.xml
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
list_item.xml
<ImageView
android:id="#+id/list_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
you can use gridView instead of listview.
Use onPreExecute and onPostExecute method

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 Eclipse AsyncTask - but result is empty - can someone have a look

sorry to be a pain, but I've been on this one too long and I am sure it's a easy one but I am tired and can't see it. All works fine but the 'String result' is empty
package com.example.me;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnLoginButton;
TextView tmpError, tmpUsername, tmpPassword;
ArrayList<NameValuePair> postParameters;
String response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tmpError = (TextView) findViewById(R.id.lblMessage);
tmpUsername = (TextView) findViewById(R.id.txtUsername);
tmpPassword = (TextView) findViewById(R.id.txtPassword);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
btnLoginButton = (Button) findViewById(R.id.btnLogin);
btnLoginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg) {
try{
triggerClick();
}
catch (Exception e) {
tmpError.setText("[]" + e.toString());
}
}
});
}
private void triggerClick() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", tmpUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", tmpPassword.getText().toString()));
final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
publishProgress(true);
try {
response = CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
publishProgress(false);
result = result.replaceAll("\\s+","");
if(result.equals("1")) {
tmpError.setText("Correct");
}
else {
tmpError.setText("Sorry!!("+result+")");
}
}
}
new HttpTask().execute();
}
}
come back time and time again with an empty "result" string :-(
because in the doInBackground() you return empty string, you should do:
protected String doInBackground(String... params) {
publishProgress(true);
try {
return CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
The string result is empty because you're returning an empty string from doInBackground().
return "";
Please Declare String response; as a global variable.
protected String doInBackground(String... params)
{
publishProgress(true);
try
{
response=CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
}
catch (Exception e)
{
e.printStackTrace();
}
}

Categories

Resources