2013-09-01 17 views
1

我正在關注android中解析json的「http://www.androidhive.info/2012/01/android-json-parsing-tutorial/」教程。程序崩潰是因爲無法在主線程上創建網絡連接。所以我加了Asynctask。現在問題是數據被解析,但是listview沒有顯示任何東西。Android:ListView爲空

繼承人我的代碼:

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

} 

回答

0

當您撥打AsyncTask.execute()時,您正在將任務推送到隊列中,不是會立即執行。還要注意,在「執行」任務後,您立即設置適配器,但適配器內部沒有任何內容,因爲任務尚未完成!

解決方案:嘗試在AsyncTaskonPostExecute()調用setListAdapter(adapter);onPostExecute()已經在UI線程上運行,所以不需要Activity.runOnUiThread(Runnable)

+0

嘗試過,但仍然沒有運氣。它的全部爲空 – Sumia

+0

嘗試編輯這個'ArrayList > contactList){'''ArrayList > _contactList){'並將'_contactList'複製到'contactList'並查看您獲得的內容。 –