2013-02-14 45 views
0

JSON數據我已經做了一個簡單的應用程序在Android中的JSON解析,我試圖從JSON Web服務的URL解析JSON數據,並希望看到它在ListView得到,但我不知道爲什麼它不工作,我已經嘗試了下面的代碼。我沒有在分析從網絡

Main.java

package com.example.newjsondemo; 

import java.util.ArrayList; 
import java.util.HashMap; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.R.string; 
import android.os.Bundle; 
import android.app.Activity; 
import android.app.ListActivity; 
import android.content.Intent; 
import android.view.Menu; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

public class MainActivity extends ListActivity { 
private static String url= "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo"; 

private static final String TAG_POSTALCODES = "postalcode"; 
private static final String TAG_ADMINNAME1 = "adminName1"; 
private static final String TAG_ADMINNAME2 = "adminName2"; 
private static final String TAG_ADMINNAME3 = "adminName3"; 
private static final String TAG_ADMINCODE1 = "adminCode1"; 
private static final String TAG_ADMINCODE2 = "adminCode2"; 
private static final String TAG_ADMINCODE3 = "adminCode3"; 
private static final String TAG_PLACENAME = "placeName"; 
private static final String TAG_POSTALCODE = "postalcode"; 
private static final String TAG_LNG = "lng"; 
private static final String TAG_LAT = "lat"; 
private static final String TAG_COUNTRY_CODE = "countryCode"; 

JSONArray postalcodes = null; 


@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // Hashmap for ListView 
       ArrayList<HashMap<String, String>> postalList = new ArrayList<HashMap<String, String>>(); 
       Jsonparser jParser = new Jsonparser(); 
       JSONObject json = jParser.getJSONFromUrl(url); 

       try{ 
        postalcodes = json.getJSONArray(TAG_POSTALCODES); 

         for(int i=0;i<postalcodes.length();i++) 
         { 
         JSONObject p = postalcodes.getJSONObject(i); 
         // Storing each json item in variable 
         String adminname1 = p.getString(TAG_ADMINNAME1); 
         String adminname2 = p.getString(TAG_ADMINNAME2); 
         String adminname3 = p.getString(TAG_ADMINNAME3); 
         String admincode1 = p.getString(TAG_ADMINCODE1); 
         String admincode2 = p.getString(TAG_ADMINCODE2); 
         String admincode3 = p.getString(TAG_ADMINCODE3); 
         String postalcode = p.getString(TAG_POSTALCODE); 
         String countrycode = p.getString(TAG_COUNTRY_CODE); 
         String placename = p.getString(TAG_PLACENAME); 
         String lng = p.getString(TAG_LNG); 
         String lat = p.getString(TAG_LAT); 

         // creating new HashMap 
         HashMap<String, String> map = new HashMap<String, String>(); 
         map.put(TAG_ADMINNAME1,adminname1); 
         map.put(TAG_COUNTRY_CODE, countrycode); 
         map.put(TAG_PLACENAME, placename); 
         postalList.add(map); 
        } 
       }catch (JSONException e) { 
        e.printStackTrace(); 
       } 


       /** 
       * Updating parsed JSON data into ListView 
       * */ 
       ListAdapter adapter = new SimpleAdapter(this, postalList, R.layout.activity_list_item, 
         new String[] { TAG_ADMINNAME1, TAG_COUNTRY_CODE, TAG_PLACENAME}, new int[] { 
         R.id.adminname1, R.id.countrycode, R.id.placename}); 
       setListAdapter(adapter); 

       // selecting single ListView item 
       ListView lv = getListView(); 
       lv.setOnItemClickListener(new OnItemClickListener() { 

        @Override 
        public void onItemClick(AdapterView<?> arg0, View view, 
          int position, long id) { 
         // TODO Auto-generated method stub 
         // getting values from selected ListItem 
        // String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
         String adminname1 = ((TextView)view.findViewById(R.id.adminname1)).getText().toString(); 
         String countrycode= ((TextView)view.findViewById(R.id.countrycode)).getText().toString(); 
         String placename= ((TextView)view.findViewById(R.id.placename)).getText().toString(); 
         // Starting new intent 
         Intent in = new Intent(getApplicationContext(), SIngleListItem.class); 
         in.putExtra(TAG_ADMINNAME1, adminname1); 
         in.putExtra(TAG_COUNTRY_CODE, countrycode); 
         in.putExtra(TAG_PLACENAME, placename); 
         //in.putExtra(TAG_ADDRESS, address); 
         //in.putExtra(TAG_GENDER, gender); 
         startActivity(in); 
        } 

       }); 

} 


} 

JsonParser.java

package com.example.newjsondemo; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

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; 

    } 

} 

logcat的

02-14 17:07:04.411: E/Buffer Error(1932): Error converting result java.lang.NullPointerException 
02-14 17:07:04.411: E/JSON Parser(1932): Error parsing data org.json.JSONException: End of input at character 0 of 
02-14 17:07:04.421: D/AndroidRuntime(1932): Shutting down VM 
02-14 17:07:04.421: W/dalvikvm(1932): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 
02-14 17:07:04.431: E/AndroidRuntime(1932): FATAL EXCEPTION: main 
02-14 17:07:04.431: E/AndroidRuntime(1932): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonmydemo/com.example.jsonmydemo.MainActivity}: java.lang.NullPointerException 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.ActivityThread.access$2300(ActivityThread.java:125) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.os.Handler.dispatchMessage(Handler.java:99) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.os.Looper.loop(Looper.java:123) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.ActivityThread.main(ActivityThread.java:4627) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at java.lang.reflect.Method.invokeNative(Native Method) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at java.lang.reflect.Method.invoke(Method.java:521) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at dalvik.system.NativeStart.main(Native Method) 
02-14 17:07:04.431: E/AndroidRuntime(1932): Caused by: java.lang.NullPointerException 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at com.example.jsonmydemo.MainActivity.onCreate(MainActivity.java:51) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 
02-14 17:07:04.431: E/AndroidRuntime(1932):  ... 11 more 
+1

發佈您的logcat錯誤。 – rajeshwaran 2013-02-14 11:33:19

+0

我已經加入logcat的錯誤.. – 2013-02-14 11:39:14

+0

請參閱本http://stackoverflow.com/questions/8202048/org-json-json-exception-end-of-input-at-character-0 – rajeshwaran 2013-02-14 11:47:06

回答

-1
HttpClient httpClient = new DefaultHttpClient(); 
       HttpGet httpGet = new HttpGet(registerUrl); 
       StringBuffer jsonString = new StringBuffer(); 
       try{ 
        HttpResponse httpResponse = httpClient.execute(httpGet); 
        InputStream in = httpResponse.getEntity().getContent(); 
        int ch = 0; 
        while ((ch = in.read()) != -1) { 
         jsonString.append((char) ch); 
        } 
        in.close(); 
        JSONObject jsonObject = new JSONObject(jsonString.toString()); 
        JSONArray jArray = jsonObject.getJSONArray("results"); 
        int arraysize = jArray.length(); 
         for (int i = 0; i < arraysize; i++){ 
          JSONObject one = jArray.getJSONObject(i); 
          LogMsg.i("Confirm "+one.getString("ConfirmationMessage")+ " UserId "+one.getString("UserID")+ " userName "+one.getString("UserName")+" Email "+one.getString("Email")); 
          if (one.getString("ConfirmationMessage").equals("Account Created")){ 
           isUserRegister = true; 
          } 
         } 
        }catch (Exception e) {} 
+0

-1碼只能回答沒有任何解釋(和壞的格式化,太) – WarrenFaith 2013-02-14 11:37:15

0

您還沒有想過下載JSON數據的延遲。您只需撥打JSONObject json = jparser.getJSONFromURL(url);,希望數據在下一行出現(postalcodes = json.getJSONArray(TAG_POSTALCODES);)。它不這樣工作。

首先,您需要加載JSON數據並等待它完成。您應該熟悉AsyncTask才能正確執行此操作。然後在你的類裏調用一個回調函數,把檢索到的數據返回給它。然後你應該使用這些數據並構建你的適配器。

+0

全部是好的...但janitha可以ü請給我的代碼線索或代碼...? – 2013-02-15 02:31:30

+0

https://gist.github.com/JanithaR/ff97f074c18b3eea0e0b – JanithaR 2013-02-15 05:46:21

+0

親愛的你能不能請通過我的代碼??? – 2013-02-15 09:28:48