João Menighin
João Menighin

Reputation: 3225

Populate ListView from JSON from another Thread

So, Im getting a JSON from a REST server and I want to fill a ListView with its info. What I have is:

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));
                    }

I have created a JSONAdapter as well:

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;
}
}

But when I make new Thread(new HTTPAssync()).start(); Im getting android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.. I tried to create a method and set the adapter from it, but got the same error. How can I do it?

Upvotes: 0

Views: 226

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

It's not the problem of JSON. You must use android.os.Handler. There are two main uses for a Handler:

(1) to schedule messages and runnables to be executed as some point in the future;

(2) to enqueue an action to be performed on a different thread than your own.

Example:

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);
        }
    }
};

And here is a call example:

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

Upvotes: 1

Related Questions