2013-02-06 49 views
2

我正在尋找一個很好的教程來解析JSON到Android的Listview中。JSON Android和Listview

問題是我的JSON文件是這樣的

[{"location_id":"823","company_id":"41","name":"Milj\u00f8station","address":"Aldersro \/ Aldersro 8","place":"","postal":"5700","city":"Svendborg","monday":"","tuesday":"","wednesday":"","thursday":"","friday":"","saturday":"","sunday":"","type":"2","lat":"55.061426149085","lng":"10.5927246809006","nocar":"0","distance":"0.00023254303859579"}] 

開始JSON數組大多數教程,以及後來的數據。我知道有很多例子,但我找不到符合我的問題的一些例子。

我加了代碼,但還是不行,這裏是我的3個班。

SingleMenuItemActivity

public class SingleMenuItemActivity extends Activity { 

// JSON node keys 
private static final String TAG_NAME = "name"; 
private static final String TAG_EMAIL = "email"; 
private static final String TAG_PHONE_MOBILE = "mobile"; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.single_list_item); 

    // getting intent data 
    Intent in = getIntent(); 

    // Get JSON values from previous intent 
    String name = in.getStringExtra(TAG_NAME); 
    String cost = in.getStringExtra(TAG_EMAIL); 
    String description = in.getStringExtra(TAG_PHONE_MOBILE); 

    // Displaying all values on the screen 
    TextView lblName = (TextView) findViewById(R.id.name_label); 
    TextView lblCost = (TextView) findViewById(R.id.email_label); 
    TextView lblDesc = (TextView) findViewById(R.id.mobile_label); 

    lblName.setText(name); 
    lblCost.setText(cost); 
    lblDesc.setText(description); 
} } 

JSONParser

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent();   

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 
} } 

AndroidJSONParserActvity

public class AndroidJSONParsingActivity extends ListActivity { 

// url to make request 
private static String url = "http://webservice.xxx.com/webservice/getLocationList.php?lat=55.061424255371094&lng=10.592724800109863"; 

// JSON Node names 
private static final String TAG_Location = "location_id"; 
private static final String TAG_Company = "company_id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_ADDRESS = "address"; 
private static final String TAG_PLACE = "place"; 
private static final String TAG_POSTAL = "postal"; 
private static final String TAG_CITY = "city"; 
private static final String TAG_MONDAY = "monday"; 
private static final String TAG_TUESDAY = "tuesday"; 
private static final String TAG_WEDNESDAY = "wednesday"; 
private static final String TAG_THURSDAY = "thursday"; 
private static final String TAG_FRIDAY = "friday"; 
private static final String TAG_SATURDAY = "saturday"; 
private static final String TAG_SUNDAY = "sunday"; 
private static final String TAG_TYPE = "type"; 
private static final String TAG_LAT = "lat"; 
private static final String TAG_LNG = "lng"; 
private static final String TAG_NOCAR = "nocar"; 



// contacts JSONArray 
JSONArray contacts = null; 

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

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

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

    // getting JSON string from URL 
    JSONObject json = jParser.getJSONFromUrl(url); 

    try { 

     // looping through All Contacts 
     for(int i = 0; i < contacts.length(); i++){ 
      JSONObject c = contacts.getJSONObject(i); 

      // Storing each json item in variable 
      String location_id = c.getString(TAG_Location); 
      String company_id = c.getString(TAG_Company); 
      String name = c.getString(TAG_NAME); 
      String address = c.getString(TAG_ADDRESS); 
      String place = c.getString(TAG_PLACE); 
      String postal = c.getString(TAG_POSTAL); 
      String city = c.getString(TAG_CITY); 
      String monday = c.getString(TAG_MONDAY); 
      String tuesday = c.getString(TAG_TUESDAY); 
      String wednesday = c.getString(TAG_WEDNESDAY); 
      String thursday = c.getString(TAG_THURSDAY); 
      String friday = c.getString(TAG_FRIDAY); 
      String saturday = c.getString(TAG_SATURDAY); 
      String sunday = c.getString(TAG_SUNDAY); 
      String type = c.getString(TAG_TYPE); 
      String lat = c.getString(TAG_LAT); 
      String lng = c.getString(TAG_LNG); 
      String nocar = c.getString(TAG_NOCAR); 


     // creating new HashMap 
      HashMap<String, String> map = new HashMap<String, String>(); 

      // adding each child node to HashMap key => value 
      map.put(TAG_Location, location_id); 
      map.put(TAG_Company, company_id); 
      map.put(TAG_NAME, name); 
      map.put(TAG_ADDRESS, address); 
      map.put(TAG_PLACE, place); 
      map.put(TAG_POSTAL, postal); 
      map.put(TAG_CITY, city); 
      map.put(TAG_MONDAY, monday); 
      map.put(TAG_TUESDAY, tuesday); 
      map.put(TAG_WEDNESDAY, wednesday); 
      map.put(TAG_THURSDAY, thursday); 
      map.put(TAG_FRIDAY, friday); 
      map.put(TAG_SATURDAY, saturday); 
      map.put(TAG_SUNDAY, sunday); 
      map.put(TAG_TYPE, type); 
      map.put(TAG_LAT, lat); 
      map.put(TAG_LNG, lng); 
      map.put(TAG_NOCAR, nocar); 

       // adding HashList to ArrayList 
      contactList.add(map); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 


    /** 
    * Updating parsed JSON data into ListView 
    * */ 
    ListAdapter adapter = new SimpleAdapter(this, contactList, 
      R.layout.list_item, 
      new String[] { TAG_NAME, TAG_LAT, TAG_Company }, new int[] { 
        R.id.name, R.id.email, R.id.mobile }); 

    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 in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); 
      in.putExtra(TAG_NAME, name); 
      in.putExtra(TAG_Location, cost); 
      in.putExtra(TAG_Company, description); 
      startActivity(in); 

     } 
    }); 
} } 

錯誤日誌貓

 02-06 10:06:19.025: D/AbsListView(9115): Get MotionRecognitionManager 02-06 10:06:19.705: D/dalvikvm(9115): GC_CONCURRENT freed 206K, 6% free 12315K/12999K, paused 13ms+14ms, total 40ms 02-06 10:06:19.725: E/JSON Parser(9115): Error parsing data org.json.JSONException: Value [{"nocar":"0","company_id":"41","postal":"5700","thursday":"","monday":"","lng":"10.5927246809006","type":"2","city":"Svendborg","location_id":"823","distance":"0.00023254303859579","wednesday":"","address":"Aldersro \/ Aldersro 8","sunday":"","name":"Miljøstation","saturday":"","friday":"","tuesday":"","place":"","lat":"55.061426149085"}, 
02-06 10:06:19.730: D/AndroidRuntime(9115): Shutting down VM 
02-06 10:06:19.730: W/dalvikvm(9115): threadid=1: thread exiting with uncaught exception (group=0x4100f2a0) 
02-06 10:06:19.740: E/AndroidRuntime(9115): FATAL EXCEPTION: main 
02-06 10:06:19.740: E/AndroidRuntime(9115): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.jsonparsing/com.androidhive.jsonparsing.AndroidJSONParsingActivity}: java.lang.NullPointerException 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.ActivityThread.access$600(ActivityThread.java:140) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.os.Handler.dispatchMessage(Handler.java:99) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.os.Looper.loop(Looper.java:137) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.ActivityThread.main(ActivityThread.java:4898) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at java.lang.reflect.Method.invokeNative(Native Method) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at java.lang.reflect.Method.invoke(Method.java:511) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at dalvik.system.NativeStart.main(Native Method) 
02-06 10:06:19.740: E/AndroidRuntime(9115): Caused by: java.lang.NullPointerException 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at com.androidhive.jsonparsing.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:69) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.Activity.performCreate(Activity.java:5206) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064) 
02-06 10:06:19.740: E/AndroidRuntime(9115):  ... 11 more 
+1

把整個堆棧跟蹤,只有與您的問題相關的代碼。我們也有我們的工作要做。 – m0skit0

+0

我剛加了 – Tirolel

+0

男人,你覺得你的英文不好嗎?如果是這樣,嘗試使用正確的語法,使用上**我**爲**我**,而不是更低**我**。向我們展示你的一些努力。 – 2013-02-06 09:31:41

回答

3

,因爲你的web服務返回一個JSONArray而不是JSONObject但您嘗試將其轉換爲JSONObject的。改變你的getJSONFromUrl方法的返回類型爲JSONArray而不是JSONObject爲:

public JSONArray getJSONFromUrl(String url) { 
JSONArray jsonarr=null; 
    // Making HTTP request 

    // try parse the string to a JSONArray 
    try { 
     jsonarr = new JSONArray(json); 
    } catch (JSONException e) { 

    } 

    // return JSON String 
    return jsonarr; //<<<< return JSONArray instead of JSONObject 
} 

,並呼籲getJSONFromUrl從活動的onCreate:

JSONArray json = jParser.getJSONFromUrl(url); 

try { 

    // looping through All Contacts 
    for(int i = 0; i < json.length(); i++){ 
     JSONObject c = json.getJSONObject(i); 

     // put your parsing code here 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+1

確切的想法。 –

+0

只是測試它,它再次失敗:( – Tirolel

+0

@LeythHisham:發佈你的最新代碼。我認爲你正在使用聯繫人jsonArray而不是json從數組中獲取值 –

0
try{ 
     // String t; 
     Boolean found=false; 

      JSONArray jArray = new JSONArray(result); 
     int jArrayLength = jArray.length(); 
     ArrayList<String> listContents = new ArrayList<String>(jArrayLength); 

      for(int i=0;i<jArray.length();i++){ 
        JSONObject json_data = jArray.getJSONObject(i); 
       // t[i]=json_data.getString("hotelname"); 


      listContents.add(json_data.getString("hotelname")); 







      } 






      arr = new String[listContents.size()]; 
      for(int i=0;i<listContents.size();i++) 
       arr[i]= listContents.get(i); 
      setListAdapter(new ArrayAdapter<String>(this, 
        android.R.layout.simple_list_item_1,arr)); 




    } 
    catch(JSONException e){ 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
    } 




} 

公共無效onListItemClick( ListView的父,視圖V, int position,long id) { Intent myIntent = new Intent(getBaseContext(),Hotelinfo.class); myIntent.putExtra(「hotelname」,arr [position]);

 startActivity(myIntent); 
     } 

} 
+0

你在回答中建議什麼?我的意思是用戶在代碼中犯的錯誤是什麼。 –

+0

我認爲他在最新版本的android上運行應用程序,他正在主線程上做Http服務器請求,這就是爲什麼他面臨問題。他應該使用異步任務這個 –

+1

這是你應該包括在你的答案得到upvote的東西: )否則,簡單的代碼並不是完美的答案。 –

1

我用同一個教程一次,我解決了問題,通過替換您的try-catch塊中的JSONParser類中的代碼。這是類是反正沒用了,你可以在的onCreate(鍵入此),或在您的AndroidJSONParserActivity類編寫方法:

HttpClient httpclient = new DefaultHttpClient(); 
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
HttpGet request = new HttpGet(url); 
HttpResponse response = httpclient.execute(request); 
HttpEntity resEntity = response.getEntity(); 
String _response=EntityUtils.toString(resEntity); // content will be consume only once 
Log.i(".......",_response); 
JSONObject json = new JSONObject(_response); 
JSONArray jarray = json.getJSONArray("array_name"); 
for(int i=0;i<jarray.length();i++) 
{ 
    JSONObject jb = (JSONObject) jarray.get(i); 
    String name = jb.getString("name"); 
} 

無論如何,你應該做在單獨的線程,而不是UI解析,與AsyncTask