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();
}
}
}
Related
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
Here is my code for fetching and loading some datas and images from mysql database in a loop,The problem is the dialog box "Loading image " is not dismissing even after the images completely loaded.
I'm new in android,Please anybody help me.
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
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.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = 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(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// 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 display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
}
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
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
}
}
}
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();
}
}
}