Error while using ProgressDailog using in AsyncTask - android

I created Application on parsing XML data.I want to show loading progress dialog.
I created two class on ListActivity(MainClass) and other is Download(Which execute in background using Asyntask).
I using Following code.
public class ListActivity extends Activity implements AsyncResponse {
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
String url = "http://www.moneycontrol.com/rss/MCtopnews.xml";
Download download = new Download();
download.delegate = this;
download.execute(url);
}
/*
* After background task of download and parsing xml ArrayList received from
* background task and send it to arrayAdapterzz
*/
#Override
public void processFinish(ArrayList<NewsItem> listArrayList) {
ListView newsListView;
newsListView = (ListView) findViewById(R.id.listView1);
NewsListAdapter newsListAdapter = new NewsListAdapter(
ListActivity.this, 0, listArrayList);
newsListView.setAdapter(newsListAdapter);
}
}
public class Download extends AsyncTask<String, Integer, ArrayList<NewsItem>> {
public AsyncResponse delegate;
private InputStream mInStream;
private ArrayList<NewsItem> mNewsList;
ListActivity la = new ListActivity();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
la.progressDialog.setMessage("Loading");
la.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
la.progressDialog.setProgress(0);
la.progressDialog.show();
}
#Override
protected ArrayList<NewsItem> doInBackground(String... params) {
String urlstr = params[0];
mInStream = downloadFromlUrl(urlstr);
ParseXml parse = new ParseXml();
try {
mNewsList = parse.parseNewsFeed(mInStream);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mNewsList;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(ArrayList<NewsItem> newsList) {
// send back parsed data to ListActivity
delegate.processFinish(newsList);
}
private InputStream downloadFromlUrl(String urlstr) {
try {
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(10 * 1000);
connection.setRequestMethod("GET");
connection.connect();
int response = connection.getResponseCode();
Log.d("debug", "The response is: " + response);
mInStream = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mInStream;
}
}
I am getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rss/com.parse.ui.ListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException
at com.parse.net.Download.onPreExecute(Download.java:33)
at android.os.AsyncTask.execute(AsyncTask.java:391)
at com.parse.ui.ListActivity.onCreate(ListActivity.java:30)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) ... 11 more 08-05 06:08:02.113: I/Process(1852): Sending signal. PID: 1852 SIG: 9

It may not be the answer but a concept. You don't need to add ProgressDialog in ListActivity.
public ProgressDialog progressDialog;
and no need to instantiate it here.
Because you want to show the progress of the AsycTask Do it like this
public class ArticleTask extends AsyncTask<String, Void, JSONObject> {
Activity context;
ListView list_of_article;
public ProgressDialog progressDialog;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
public ArticleTask(Activity coontext, ListView listview) {
this.context = coontext;
this.list_of_article = listview;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(context,
"", "");
}
#Override
protected JSONObject doInBackground(String... params)
{
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]); //url
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", array.getJSONObject(x).getString("title"));
map.put("previewimage", array.getJSONObject(x).getString("previewimage"));
map.put("publishdate", array.getJSONObject(x).getString("publishdate"));
map.put("pagetext", array.getJSONObject(x).getString("pagetext"));
map.put("total_comments", array.getJSONObject(x).getString("total_comments"));
map.put("viewcount", array.getJSONObject(x).getString("viewcount"));
map.put("associatedthreadid", array.getJSONObject(x).getString("associatedthreadid"));
list.add(map);
}
ArticleAdapter adapter = new ArticleAdapter(context, list);
list_of_article.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
Remove ProgressDialog from ListActivity and show it on PreExecute and remove/dismiss it on PostExecute.

Try this in your preExecute() method
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(this_context, "Loading",
"Please wait for a moment...");
}

Related

How to download file from server from button click event in android

I want to create an application using PHP webservices which can download file from server.
This is my Detail class:
public class ImportExportDataDetails extends Activity {
int id;
Button btnback;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
TextView txtname,tvfile1,tvfile2,tvdetail;
ImageView imgflag;
Button btnfile1,btnfile2;
String url1,url2,filenm1,filenm2;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private ArrayList<NameValuePair> lst;
public static String[] image;
public static String[] name;
public static String[] file1;
public static String[] file2;
public static String[] fnm1;
public static String[] fnm2;
public static String[] detail;
private JSONArray users =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_import_export_data_details);
Intent i=getIntent();
id=i.getIntExtra("id", 0);
txtname=(TextView)findViewById(R.id.txtname);
tvfile1=(TextView)findViewById(R.id.tvfile1);
tvfile2=(TextView)findViewById(R.id.tvfile2);
tvdetail=(TextView)findViewById(R.id.tvdetail);
imgflag=(ImageView)findViewById(R.id.imgflag);
btnfile1=(Button)findViewById(R.id.btnfile1);
btnfile2=(Button)findViewById(R.id.btnfile2);
btnback=(Button)findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),ImportExportData.class);
startActivity(i);
}
});
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://kalalunsons.com/webservice/web-import-export-data-details.php?import_export=1");
lst=new ArrayList<NameValuePair>();
lst.add(new BasicNameValuePair("im_ex_data_id", Integer.toString(id)));
try {
httppost.setEntity(new UrlEncodedFormEntity(lst));
new details().execute();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnfile1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startDownload();
}
});
}
private void startDownload() {
String url = url1;
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.xlsx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
class details extends AsyncTask<String, integer, String>{
String jsonstring;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpResponse httpresponse=httpclient.execute(httppost);
jsonstring=EntityUtils.toString(httpresponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonstring;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject JsonObject=null;
try {
JsonObject =new JSONObject(result);
JSONObject jobj=JsonObject.getJSONObject("0");
users=jobj.getJSONArray("import_export");
name=new String[users.length()];
image=new String[users.length()];
detail=new String[users.length()];
file1=new String[users.length()];
file2=new String[users.length()];
fnm1=new String[users.length()];
fnm2=new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo=users.getJSONObject(i);
name[i]=jo.getString("name");
image[i]=jo.getString("image");
detail[i]=jo.getString("details");
file1[i]=jo.getString("file");
file2[i]=jo.getString("file2");
fnm1[i]=jo.getString("file_name");
fnm2[i]=jo.getString("file_name");
txtname.setText(name[i]);
Picasso.with(getApplicationContext()).load(image[i]+"?import_export=1").into(imgflag);
tvdetail.setText(Html.fromHtml(detail[i]));
tvfile1.setText(fnm1[i]);
tvfile2.setText(fnm2[i]);
url1=file1[i];
url2=file2[i];
filenm1=tvfile1.getText().toString();
filenm1=filenm1.toLowerCase()+".xlsx";
}
//Toast.makeText(getApplicationContext(), url1, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In that case the logcat doesn't display any error.when i run this code it start progress of downloading,when progress finished i check my sdcard folder but it not display any file.the file was downloaded successfully but it displays as binary format,what can i changes in my code.and how can i display it in the sdcard.
you can use some library for network calls:-
retrofit-
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
also background and UI threads are separate threads. In UI thread, you can update your views and UI like toast messages and load an image.
here is a great article to learn about asynctask, read this first --
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
Issue: you are showing Toast in doInBackground() which run in separate thread. Remove Toast message from doInBackground() method
If you wanna show some info,use logs instead of Toast

Progress Dialog should spin till loading of gridview completed

I am working on one android app in which i want to display progress Dialog till loading of gridview completed. But my problem is progress dialog is spin for some intial time. Then it stops spinning.
Here is my code.
public class allsites extends Activity {
private final String url_select = "http://api.stackexchange.com/2.1/sites?filter=!RGB_Y51.*-(YX";
private GridView gview;
private ListViewCustomAdapter adapter;
private ArrayList<Object> itemList = new ArrayList<Object>();
private ItemBean bean;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.allsites);
//GridView gridview = (GridView) findViewById(R.id.gvAllSites);
gview = (GridView) findViewById(R.id.gvallsites);
new task().execute();
}
private class task extends AsyncTask<Void, Void, GZIPInputStream> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(allsites.this, "Loading", "Please Wait...");
}
#Override
protected GZIPInputStream doInBackground(Void... params) {
ServerData httpclient = new ServerData();
GZIPInputStream zis = httpclient.GetServerData(url_select);
return zis;
}
#Override
protected void onPostExecute(GZIPInputStream zis) {
ParseJSON(zis);
if(progress!=null && progress.isShowing()==true)
progress.dismiss();
}
}
private void ParseJSON(GZIPInputStream zis)
{
Gson gson = new Gson();
Reader reader = new InputStreamReader(zis);
Sites response = gson.fromJson(reader, Sites.class);
List<Items> items = response.getItems();
for (Items site : items) {
//Toast.makeText(allsites.this, site.getApi_site_parameter().toString(), Toast.LENGTH_SHORT).show();
AddObjectToList(site.getIcon_url(),site.getName());
}
adapter = new ListViewCustomAdapter(this, itemList);
gview.setAdapter(adapter);
}
public void AddObjectToList(String imageURL, String title)
{
bean = new ItemBean();
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
bean.setImage(bitmap);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bean.setTitle(title);
itemList.add(bean);
}
}
Please give me suggestion how i can make progress dialog spinning till gridview get loaded.
move ParseJSON function to doInBackground event
#Override
protected Boolean doInBackground(Void... params) {
ServerData httpclient = new ServerData();
GZIPInputStream zis = httpclient.GetServerData(url_select);
ParseJSON(zis);
return true;
}
#Override
protected void onPostExecute(Boolean zis) {
progress.dismiss();
}

when process dialog is being displayed, doInBackground() is not being executed

I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}

java.lang.RuntimeException error occured while executing doInBackground()

I beginner in android development, getting error in following code. i am calling asyn method for http request.Its giving me java.lang.RuntimeException error occured while executing doInBackground()
private class PostAlert extends AsyncTask<String, Integer, JSONArray>{
private ProgressDialog progressDialog;
#Override
protected JSONArray doInBackground(String... params) {
// TODO Auto-generated method stub
JSONArray menuitemArr = null;
String url=params[0];
System.out.println("fsfsddddf"+params[0]);
ControlDashboard obj = new ControlDashboard();
try{
JSONObject aobj = obj.getJSONFromUrl(url);
JSONObject array = aobj.getJSONObject("alert_list");
menuitemArr = array.getJSONArray("array");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return menuitemArr;
}
#Override
protected void onPostExecute(JSONArray menuitemArr) {
// TODO Auto-generated method stub
super.onPostExecute(menuitemArr);
if (menuitemArr.length() == 0) {
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
//Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
}else{
name = new String[menuitemArr.length()];
alert = new String[menuitemArr.length()];
date = new String[menuitemArr.length()];
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
try {
name[i] = menuitemArr.getJSONObject(i).getString("name").toString();
alert[i] = menuitemArr.getJSONObject(i).getString("message").toString();
date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListView list = (ListView) findViewById(R.id.listView3);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] {"col1", "col2", "col3"};
int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
for(int i=0; i<name.length; i++)
{
HashMap<String,String> map = new HashMap<String, String>();
map.put("col1", name[i]);
map.put("col2", alert[i]);
map.put("col3", date[i]);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
list.setAdapter(arrayAdapter);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(Alert.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
//progressDialog.dismiss();
}
}
Error when i run my android application.
12-17 13:22:48.035: W/dalvikvm(1160): threadid=8: thread exiting with uncaught exception (group=0x4001d800)
12-17 13:22:48.045: E/AndroidRuntime(1160): FATAL EXCEPTION: AsyncTask #2
12-17 13:22:48.045: E/AndroidRuntime(1160): java.lang.RuntimeException: An error occured while executing doInBackground()
12-17 13:22:48.045: E/AndroidRuntime(1160): at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
json request class:
public class ControlDashboard extends Activity {
public static DefaultHttpClient httpClient;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
jObj = null;
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
or
ListView list = (ListView) findViewById(R.id.listView3);
here you are trying to access UI elements from Background Thread means from AsyncTask doInBackground which is not possible
solution move all ui related code in onPostExecute for updating ui after doInBackground complete
you can see here how we update UI from onPostExecute after when doInBackground execution complete
EDIT : or just use this PostAlert AsyncTask class :
private class PostAlert extends AsyncTask<String, Integer, JSONArray>{
private ProgressDialog progressDialog;
#Override
protected JSONArray doInBackground(String... params) {
// TODO Auto-generated method stub
JSONArray menuitemArr=null;
String url=params[0];
System.out.println("fsfsddddf"+url);
// System.out.println("fsfsddddfobj"+obj);
try{
JSONObject aobj = obj.getJSONFromUrl(url);
System.out.println("fsfsf"+aobj);
JSONObject array = aobj.getJSONObject("alert_list");
menuitemArr = array.getJSONArray("array");
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return menuitemArr;
}
#Override
protected void onPostExecute(JSONArray menuitemArr) {
// TODO Auto-generated method stub
if (menuitemArr.length() == 0) {
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
//Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
}else{
name = new String[menuitemArr.length()];
System.out.println("name"+name);
alert = new String[menuitemArr.length()];
date = new String[menuitemArr.length()];
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
name[i] = menuitemArr.getJSONObject(i).getString("name").toString();
alert[i] = menuitemArr.getJSONObject(i).getString("message").toString();
date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
}
ListView list = (ListView) findViewById(R.id.listView3);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] {"col1", "col2", "col3"};
int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
for(int i=0; i<name.length; i++)
{
HashMap<String,String> map = new HashMap<String, String>();
map.put("col1", name[i]);
map.put("col2", alert[i]);
map.put("col3", date[i]);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
list.setAdapter(arrayAdapter);
}
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(Alert.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
System.out.println("fsgsgsg");
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressDialog.setProgress(values[0]);
}
}
}
http://developer.android.com/reference/android/os/AsyncTask.html
You are setting ListAdapter in Background which should not be done as it is UI thread task. Change your entire code in doInBackground() to onPostExecute() except for getJsonFromUrl(url). you can return the jsonobject from doInBackground() which you can get in onPostExecute() as result parameter. Still you get that runtime error in onPostExecute() too then you just right this line listview.setAdapter() in
runOnUIThread(new Runnable(){
public void run()
{
}
});
I hope its clear and it will work for you.

ProgressDialog is not displayed

I have an Async Task getting me some data from the web. Async Task works fine and I want a Progress Dialog Spinner to be displayed while the data is being procured from the web.The Progress Dialog Spinner never shows up. Here is my code:
public class JsonHttpParsingActivity extends ListActivity{
private String jsonResult;
private ArrayList nameArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpConnection task = new HttpConnection(this);
AsyncTask<String,Void,String> taskResult = task.execute("Some URL...");
try {
jsonResult = taskResult.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
.
More Code.....
}
}
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
setActivity(activity);
}
public void setActivity(Activity activity) {
m_activity = activity;
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress((int) ((values[0] / (float) values[1]) * 100));
};
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Thanks!
Instead of write a separate method setActivity(activity) (Non UI Thread scope)
for starting ProgressDialog put the code in onPreExecute() (UI Thread) of AsyncTask, Because you are trying to show it in non UI thread.
Try this,
protected HttpConnection(Activity activity) {
m_activity = activity;
}
Override
protected void onPreExecute(String result){
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
Call progress bar from onPreExecute() function
The following code is working fine and tested:
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Try calling the AsyncTask from another method in the activity. My guess is that right now, you call it in the onCreate method of the activity. Since the activity is still building, this can give you exceptions. A thing I once tried when I had this issue, is starting the asynchronous task from the onPostCreate method of the activity.

Categories

Resources