I am trying to execute asynctask from another class and update listview and also toast. But I am unable to do that. Its crashing at:
progressDialog = new ProgressDialog(context);
I really appreciate any help.
fetch.class
public class fetch extends AsyncTask<Void, Void, JSONObject> {
Context context;
Activity activity ;
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
ProgressDialog progressDialog ;
@Override
protected JSONObject doInBackground(Void... params) {
String ResponseBody = null;
try {
String user = "1";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/example.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("user",user) );
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
String result = sb.toString();
// parsing data
return new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
});
}
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (result != null) {
JSONArray arr = result.getJSONArray("Array");
for (int i = 0; i <arr.Length(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
}
list=(ListView)findViewById(R.id.ListView);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(MainActivity.this, songsList);
list.setCacheColorHint(0);
list.setScrollingCacheEnabled(false);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getBaseContext(), position+" "+id, 5).show();
}
});
} else {
// error occured
}
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.dismiss();
Toast.makeText(getBaseContext(), "done", 5).show();
}
});
}
public fetch(Context context) {
activity = (context instanceof Activity) ? (Activity) context : null;
this.context = context;
progressDialog = new ProgressDialog(context);
}
}
LazyAdapter.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(CustomizedListView.KEY_TITLE));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
}
MainActivity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
RelativeLayout rootView = (RelativeLayout)findViewById(R.id.rootLayout);
PopoverView popoverView = new PopoverView(PopoverViewActivity.this, R.layout.popover_showed_view);
popoverView.setContentSizeForViewInPopover(new Point(400, 480));
popoverView.setDelegate(PopoverViewActivity.this);
popoverView.showPopoverFromRectInViewGroup(rootView, PopoverView.getFrameForView(v), PopoverView.PopoverArrowDirectionUp, true);
songsList = new ArrayList<HashMap<String, String>>();
fetch load=new fetch(getBaseContext());
load.execute();
}
});
}
Problem with this piece of code
progressDialog = new ProgressDialog(context);
is that this needs context of currently displayed activity. And it seems you are passing it the non-displaying activity context (In your case it is null). It needs displayed activity context in order to show the progress bar.
while calling fetch you are passing it as null in main activity. you should change
fetch(null);
to
fetch(MainActivity.this);
Hope this helps.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments