我使用android listview和lazyadapter在列表中显示图像和textview。
当用户滚动到底部时我使用AsyncTask添加更多内容但是当我执行AsyncTask时它会终止进程。
这是我的代码。 的 mainactivity
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.Element;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AndroidJSONParsingActivity extends Activity {
// url to make request
// JSON Node names
static final String TAG_CONTACTS = "comics";
static final String TAG_ID = "id";
static final String TAG_NAME = "title";
static final String TAG_EMAIL = "id";
static final String TAG_PHONE_MOBILE = "image";
// contacts JSONArray
JSONArray contacts = null;
ListView list;
LazyAdapter adapter;
static int counter = 0;
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
// call the function
LoadData();
}
public void LoadData(){
String url = "http://myurl?start=" + counter;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String mobile = "http://www.funnydash.com/uploads/s/" + c.getString(TAG_PHONE_MOBILE);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
}
public class BackgroundLoadMore extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
}
protected Void doInBackground(Void... unused) {
LoadData();
return (null);
}
protected void onPostExecute(Void unused) {
// On completing background task
// closing progress dialog etc,.
list.setOnScrollListener(new EndlessScrollListener());
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
counter +=12;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new BackgroundLoadMore().execute();
loading = true;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
}
Lazyadapter.java
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
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(AndroidJSONParsingActivity.TAG_NAME));
artist.setText(song.get(AndroidJSONParsingActivity.TAG_ID));
imageLoader.DisplayImage(song.get(AndroidJSONParsingActivity.TAG_PHONE_MOBILE), thumb_image);
return vi;
}
}
和this是我在logcat中得到的
答案 0 :(得分:3)
问题是因为您尝试从UI线程外部在列表上设置适配器。 Android中的视图可以在后台线程中修改不,在这种情况下,这意味着您无法通过doInBackground
的{{1}}方法修改用户界面。因此,您的方法AsyncTask
无法调用以下内容:
LoadData()
您需要从adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
方法返回一些数据(可能是contactList
),然后将有问题的代码移到doInBackground()
方法, 在UI线程上运行。
堆栈跟踪中提到的关键问题是:
onPostExecute()
答案 1 :(得分:0)
您正在尝试从主线程类创建一个视图。
如上所述
07-26 22:26:36.933:E / AndroidRuntime(16353):引起: android.view.ViewRootImpl $ CalledFromWrongThreadException:只有 创建视图层次结构的原始线程可以触及其视图。
您的主要问题在于您的asyncTask。您无法创建不在原始线程中的视图项。你可以做什么。是将这些行放在post方法上,而不是在do background方法或asynctask class之外。
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
答案 2 :(得分:0)
1。始终保持 UI线程在UI线程上工作,非UI工作在非UI线程上,这成为法律Honey Comb版Android的到来。
2。从上面的logcat中,它只指向一件事,你是试图从UI线程上的非UI线程做一些事情(主要的专用UI线程) )。强>
这是....你在doInBackground()上调用它,这是一个非UI线程。
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
第3。修改适配器表单UI线程,您可以在 onPostExecute()