从另一个Thread的JSON填充ListView

时间:2012-11-10 19:48:47

标签: android android-listview

所以, 我从REST服务器获取JSON,我想用其信息填充ListView。我所拥有的是:

public class MyReservations extends ListActivity {
....
class HTTPAssync implements Runnable {
        public void run () {
               ... //make the requestions and get a valida JSONObject (that has a JSONArray)
               try {
                    JSONObject jsonObject = new JSONObject(payload);
                    reservs = jsonObject.getJSONArray("reservs");
                    try {
                         listView.setAdapter(new JSONAdapter(MyReservations.this, reservs));
                    }

我也创建了一个JSONAdapter:

class JSONAdapter extends BaseAdapter implements ListAdapter {

private final Activity activity;
private final JSONArray jsonArray;
private LayoutInflater mInflater;

public JSONAdapter(Activity activity, JSONArray jsonArray) {
    assert activity != null;
    assert jsonArray != null;

    this.jsonArray = jsonArray;
    this.activity = activity;
}


public int getCount() {

    return jsonArray.length();
}

public JSONObject getItem(int position) {

    return jsonArray.optJSONObject(position);
}

public long getItemId(int position) {
    JSONObject jsonObject = getItem(position);

    return jsonObject.optLong("id");
}

public View getView(int position, View view, ViewGroup parent) {
    if (view == null)
        view = activity.getLayoutInflater().inflate(R.layout.reservation, null);

    JSONObject jsonObject = getItem(position);  
    view = mInflater.inflate(R.layout.reservation, null);

    ((TextView) view.findViewById(R.id.reservationCourse)).setText("MOTHAFOCKA");

    return view;
}
}

但是当我new Thread(new HTTPAssync()).start();时,我正在android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.。我试图创建一个方法并从中设置适配器,但得到了相同的错误。我该怎么办?

1 个答案:

答案 0 :(得分:1)

这不是JSON的问题。您必须使用android.os.Handler。 Handler有两个主要用途:

(1)安排消息和runnables作为未来的某个点执行;

(2)将要在不同于您自己的线程上执行的操作排入队列。

示例:

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        final Object obj = msg.obj;

        switch (msg.what) {
        case MODE_DELETE:
            this.post(new Runnable() {
                public void run() {             
                    performDelete();
                }
            }); 
            break;
        case ON_SERVICE_STATUS_CHAGED:
            ((LauncherUI)mContext).updateUI();  
            break;
        case ON_DISPLAY_TOAST:
            Toast.makeText(mContext, obj.toString(),Toast.LENGTH_SHORT).show();
            break;
        case GET_USER_INPUT:
            handleUserInputRequest();
            break;
                    // .... 
        default:
            super.handleMessage(msg);
        }
    }
};

这是一个电话示例:

mHandler.sendMessage(mHandler.obtainMessage(ON_DISPLAY_TOAST, "show toast"));