1

我正在关注“ http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ”中关于在 android 中解析 json 的教程。程序崩溃,因为无法在主线程上创建网络连接。所以我添加了异步任务。现在的问题是数据被解析但列表视图没有显示任何内容。

这是我的代码:

AndroidJSONParsingActivity.java

public class AndroidJSONParsingActivity extends ListActivity {

ArrayList<HashMap<String, String>> contactList;
ListAdapter adapter;

// url to make request
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names
static final String TAG_CONTACTS = "contacts";
static final String TAG_ID = "id";
static final String TAG_NAME = "name";
static final String TAG_EMAIL = "email";
static final String TAG_ADDRESS = "address";
static final String TAG_GENDER = "gender";
static final String TAG_PHONE = "phone";
static final String TAG_PHONE_MOBILE = "mobile";
static final String TAG_PHONE_HOME = "home";
static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item);



    new AsyncTask<String, Void, ArrayList<HashMap<String, String>>>() {

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                String... params) {

            // Hashmap for ListView
            contactList = new ArrayList<HashMap<String, String>>();

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            final String url1 = params[0];



            JSONObject jObj = jParser.getJSONFromUrl(url1);

            try {
                contacts = jObj.getJSONArray(TAG_CONTACTS);

                for (int i = 0; i < contacts.length(); ++i) {
                    JSONObject contactObj = contacts.getJSONObject(i);

                    // Storing each json item in variable
                    String id = contactObj.getString(TAG_ID);
                    String name = contactObj.getString(TAG_NAME);
                    String email = contactObj.getString(TAG_EMAIL);
                    String address = contactObj.getString(TAG_ADDRESS);
                    String gender = contactObj.getString(TAG_GENDER);

                    // Phone number is agin JSON Object
                    JSONObject phone = contactObj.getJSONObject(TAG_PHONE);
                    String mobile = phone.getString(TAG_PHONE_MOBILE);
                    String home = phone.getString(TAG_PHONE_HOME);
                    String office = phone.getString(TAG_PHONE_OFFICE);

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

                    contactList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return contactList;
        }

        @Override
        protected void onPostExecute(
            ArrayList<HashMap<String, String>> contactList) {

            /**
             * Updating parsed JSON data into ListView
             * */

            for(int i=0;i<contactList.size();i++) {
                HashMap<String, String> map = contactList.get(i);
                Toast.makeText(getApplicationContext(), map.get(TAG_NAME), Toast.LENGTH_LONG).show();
            }

            Toast.makeText(AndroidJSONParsingActivity.this, "hi", Toast.LENGTH_LONG).show();
             adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, contactList,
                    R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
                            TAG_PHONE_MOBILE }, new int[] { R.id.name,
                            R.id.email, R.id.mobile });




        }

    }.execute(url);

    setListAdapter(adapter);
    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting new intent
            Intent intent = new Intent(getApplicationContext(),
                    SingleMenuItemActivity.class);
            intent.putExtra(TAG_NAME, name);
            intent.putExtra(TAG_EMAIL, cost);
            intent.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(intent);
        }
    });
}

}

JSONParser.java

public class JSONParser {

static InputStream inputStream = null;
static JSONObject jObj = null;
static String jsonStr = "";

public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        inputStream = entity.getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while((line=reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        inputStream.close();
        jsonStr = sb.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        jObj = new JSONObject(jsonStr);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jObj;
}
}

SingleMenuItemActivity.java

public class SingleMenuItemActivity extends Activity {

TextView tvName, tvEmail, tvMobile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item);

    tvName = (TextView) findViewById(R.id.name);
    tvEmail = (TextView) findViewById(R.id.email);
    tvMobile = (TextView) findViewById(R.id.mobile);


    Bundle bundle = getIntent().getExtras();
    tvName.setText(bundle.getString(AndroidJSONParsingActivity.TAG_NAME));
    tvEmail.setText(bundle.getString(AndroidJSONParsingActivity.TAG_EMAIL));
    tvMobile.setText(bundle.getString(AndroidJSONParsingActivity.TAG_PHONE_MOBILE));
}

}
4

1 回答 1

0

当您调用时,AsyncTask.execute()您正在将任务推送到队列中,它不会立即执行。另请注意,在您“执行”任务之后,您设置了适配器,但适配器内部没有任何内容,因为任务尚未完成!

解决方案尝试调用setListAdapter(adapter);. 已经在 UI 线程上运行,因此不需要onPostExecute()AsyncTaskonPostExecute()Activity.runOnUiThread(Runnable)

于 2013-09-01T10:04:27.850 回答