2015-02-10 53 views
-1

我想从在线数据库中获取一些dat到android中的listview,即使尝试获取空指针异常来自localhost数据库的数据,我猜他们是jsonArray的一些问题。在android中尝试从在线服务器使用json解析检索数据时出现空指针异常

public class MainActivity extends Activity { 
private String jsonResult; 
private String url = "http://cpriyankara.coolpage.biz/employee_details.php"; 
private ListView listView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    listView = (ListView) findViewById(R.id.listView1); 
    accessWebService(); 
} 



// Async Task to access the web 
private class JsonReadTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... params) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(params[0]); 
     try { 
      HttpResponse response = httpclient.execute(httppost); 
      jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString(); 
     } 

     catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    private StringBuilder inputStreamToString(InputStream is) { 
     String rLine = ""; 
     StringBuilder answer = new StringBuilder(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

     try { 
      while ((rLine = rd.readLine()) != null) { 
       answer.append(rLine); 
      } 
     } 

     catch (IOException e) { 
      // e.printStackTrace(); 
      Toast.makeText(getApplicationContext(), 
        "Error..." + e.toString(), Toast.LENGTH_LONG).show(); 
     } 
     return answer; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     ListDrwaer(); 
    } 
}// end async task 

public void accessWebService() { 
    JsonReadTask task = new JsonReadTask(); 
    // passes values for the urls string array 
    task.execute(new String[] { url }); 
} 

// build hash set for list view 
public void ListDrwaer() { 
    List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>(); 

    try { 
     JSONObject jsonResponse = new JSONObject(jsonResult); 
     JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info"); 

     for (int i = 0; i < jsonMainNode.length(); i++) { 
      JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
      String name = jsonChildNode.optString("employee name"); 
      String number = jsonChildNode.optString("employee no"); 
      String outPut = name + "-" + number; 
      employeeList.add(createEmployee("employees", outPut)); 
     } 
    } catch (JSONException e) { 
     Toast.makeText(getApplicationContext(), "Error" + e.toString(), 
       Toast.LENGTH_SHORT).show(); 
    } 

    SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, 
      android.R.layout.simple_list_item_1, 
      new String[] { "employees" }, new int[] { android.R.id.text1 }); 
    listView.setAdapter(simpleAdapter); 
} 

private HashMap<String, String> createEmployee(String name, String number) { 
    HashMap<String, String> employeeNameNo = new HashMap<String, String>(); 
    employeeNameNo.put(name, number); 
    return employeeNameNo; 
} 

,我的记录是:

11 01:48:33.290 1328-1328/com.example.gautam.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main 
Process: com.example.gautam.mysqlapp, PID: 1328 
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference 
     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) 
     at org.json.JSONTokener.nextValue(JSONTokener.java:94) 
     at org.json.JSONObject.<init>(JSONObject.java:156) 
     at org.json.JSONObject.<init>(JSONObject.java:173) 
     at com.example.gautam.mysqlapp.MainActivity.ListDrwaer(MainActivity.java:100) 
     at com.example.gautam.mysqlapp.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:85) 
     at com.example.gautam.mysqlapp.MainActivity$JsonReadTask.onPostExecute(MainActivity.java:45) 
     at android.os.AsyncTask.finish(AsyncTask.java:632) 
     at android.os.AsyncTask.access$600(AsyncTask.java:177) 
     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5221) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
+0

“MainActivity”的第100行是什么? – iRuth 2015-02-10 20:54:47

+0

请在LIstDrwer中检查** jsonMainNode **的值 – vinitius 2015-02-10 20:57:22

+0

我试过了你的代码,它完美地工作! – kelvincer 2015-02-10 21:06:55

回答

0

你有一个IOException或建立结果字符串jsonResultClientProtocolException;记录,但否则忽略它;继续;返回null;然后尝试用空字符串构造一个JSONObject,这导致NPE在构造函数中向下几层。

道德:不要写这样的代码。你的代码不应该超出例外。至少在尝试使用它之前,您应该先检查jsonResult为null。

+0

所以如何摆脱它..?如果相同的代码工作正常的其他人,这意味着问题是与我的连接似乎...? – aniroid 2015-02-10 21:23:24

+0

我已经告诉过你如何以两种不同的方式摆脱它。再看一遍。 – EJP 2015-02-10 21:37:00

相关问题