Android ListView没有填充json数据

时间:2014-03-21 11:45:43

标签: android json android-listview

我想用json值填充listview。我能够获得所有json值,但是 我不知道问题是什么。

在我的logcat中,它显示NullPointerException,不幸的是我的活动停止了。

Suggesstion plz ......

我的java

  public class Certify_Absent_List extends Activity {
    private static ListView listview;
    private static List<String> list;
    private String teachername,date; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.);
        listview=(ListView) findViewById(R.id.listView1); 
        list=new ArrayList<String>();
        teachername=getIntent().getExtras().getString("teachername");
        date=getIntent().getExtras().getString("today");
        new Absent_list_bg_task().execute();
    }
    private class Absent_list_bg_task extends AsyncTask<String,Void,String>
    {

         protected String doInBackground(String... params) {  

             try{ 

                            String link="http://192.168.1.11:81/schoolapp/absent_list.php"; 
                            String data  = URLEncoder.encode("teachername", "UTF-8") 
                            + "=" + URLEncoder.encode("teacher1", "UTF-8");  
                            data += "&" + URLEncoder.encode("date", "UTF-8") 
                            + "=" + URLEncoder.encode("2013-01-01", "UTF-8");
                           /* String data  = URLEncoder.encode("teachername ", "UTF-8") 
                            + "=" + URLEncoder.encode("teacher1", "UTF-8");
                            data += "&" + URLEncoder.encode("date", "UTF-8") 
                            + "=" + URLEncoder.encode("2013-01-01", "UTF-8");*/
                            URL url = new URL(link);
                            URLConnection conn = url.openConnection(); 
                            conn.setDoOutput(true); 
                            OutputStreamWriter wr = new OutputStreamWriter
                            (conn.getOutputStream()); 
                            wr.write( data ); 
                            wr.flush(); 
                            BufferedReader reader = new BufferedReader
                            (new InputStreamReader(conn.getInputStream())); 
                            StringBuilder sb = new StringBuilder();
                            String line = null;
                            // Read Server Response
                            while((line = reader.readLine()) != null)
                            {
                               sb.append(line);
                               break;
                            }
                           return sb.toString(); 
                         }catch(Exception e){
                            return new String("Exception: " + e.getMessage());
                         }
                }
                   @Override
                protected void onPostExecute(String result)
                   {

                       ArrayAdapter<String> adapter = null;
                        JSONArray arr = null;
                        JSONObject obj = null;
                          Toast.makeText(Certify_Absent_List.this,result, Toast.LENGTH_LONG).show(); 

                       if(result.equals("wrong"))  
                       {
                          Toast.makeText(Certify_Absent_List.this,"Invalid username or password.", Toast.LENGTH_LONG).show(); 
                       }

                       else
                       {
                            Toast.makeText(Certify_Absent_List.this,result, Toast.LENGTH_LONG).show();
                            try {
                                arr=new JSONArray(result);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            for(int i=0;i<arr.length();i++)
                            {
                                try {
                                    obj=arr.getJSONObject(i);
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } 
                                try {
                                    list.add(obj.getString("ChildName"));
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                Toast.makeText(Certify_Absent_List.this,list.get(i).toString(), Toast.LENGTH_LONG).show();

                            } 


                       }
                       adapter=new ArrayAdapter<String>(Certify_Absent_List.this, android.R.layout.simple_list_item_1, list);
                       //adapter.notifyDataSetChanged();
                       listview.setAdapter(adapter);


    }
    }
    }

Json输出

[{"ChildName":""},{"ChildName":"childname1"},{"ChildName":"childname7"},{"ChildName":"childname11"},{"ChildName":"childname11"},{"ChildName":"childname11"}]

logcat的:

    03-21 07:35:29.128: E/AndroidRuntime(1443): java.lang.NullPointerException
    03-21 07:35:29.128: E/AndroidRuntime(1443):     at com.example.certify_teacher_login.Certify_Absent_List$Absent_list_bg_task.onPostExecute(Certify_Absent_List.java:121)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at com.example.certify_teacher_login.Certify_Absent_List$Absent_list_bg_task.onPostExecute(Certify_Absent_List.java:1)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at android.os.AsyncTask.finish(AsyncTask.java:632)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at android.os.Looper.loop(Looper.java:137)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at android.app.ActivityThread.main(ActivityThread.java:4998)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at java.lang.reflect.Method.invokeNative(Native Method)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at java.lang.reflect.Method.invoke(Method.java:515)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-21 07:35:29.128: E/AndroidRuntime(1443):     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:2)

修改 在你的onCreate中你需要取消注释:

//setContentView(R.layout.);

并添加要加载的布局(listView1所在的位置)。

setContentView(R.layout.your_layout_name);

之后,使用以下命令加载listView:

listview = (ListView) findViewById(R.id.your_list_view_id);

其他:永远不要private static ListView listview;这会导致应用程序内存泄漏,不要对视图保持静态引用,如果执行中有多个活动,可能会导致崩溃。

答案 1 :(得分:0)

尝试使用以下代码。

 JSONArray jarray;


            jarray= new JSONArray(result);//result is your response from webservice



                String []name= new String[jarray.length()];






                for(int f=0;f<jarray.length();f++){
                    JSONObject jobj = jarray.getJSONObject(f);
                    name[f]=    jobj.getString("Childname");


                }

                for(int a=0;a<jarray.length();a++){

                    items.add(new EntryItem(name[a]);//items is your listview and Enrty Item is your POJO class.
                }   
                adapter  = new EntryAdapter(contact.this,items);//Entry adapter is  your adapter class.
                    lv.setAdapter(adapter);

答案 2 :(得分:0)

   //setContentView(R.layout.); 

为什么该行被评论?您不会扩展ListActivity或使用片段。除非是输入错误,否则它无法正常工作!