java.lang.NullPointerException:尝试调用虚方法' void android.widget.ListView.setAdapter

时间:2016-02-03 16:41:42

标签: java android

我想创建一个从db中获取Mysql数据的android应用程序,并将其显示在列表中。我得到的问题是当应用程序运行时它显示不幸它停止。 Logcat显示问题出在这一行

 list.setAdapter(adapter);

无论在哪里,我都尽力搜索,但它不起作用。由于我是Android开发的初学者,请帮助我

Logcat:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at com.example.abdul.zx.MainActivity.showList(MainActivity.java:81)
        at com.example.abdul.zx.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:129)
        at com.example.abdul.zx.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:90)
        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)

主要Activity.java

public class MainActivity extends ActionBarActivity {

String myJSON;

private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD ="address";

JSONArray peoples = null;

ArrayList <HashMap <String, String> > personList;

ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String,String>>();
    getData();
}


protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADD);

            HashMap<String,String> persons = new HashMap<String,String>();

            persons.put(TAG_ID,id);
            persons.put(TAG_NAME,name);
            persons.put(TAG_ADD,address);

            personList.add(persons);
        }

        ListAdapter adapter = new SimpleAdapter
                (
                MainActivity.this, personList, R.layout.list_item,
                new String[]{TAG_ID,TAG_NAME,TAG_ADD},
                new int[]{R.id.id, R.id.name, R.id.address}
        );

        list.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

public void getData(){
    class GetDataJSON extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://10.0.2.2/in.php");

            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            InputStream inputStream = null;
            String result = null;
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (Exception e) {
                // Oops
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result){
            myJSON=result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >


<TextView
    android:id="@+id/id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:paddingTop="6dip"
    android:textStyle="bold" />


<TextView
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:textStyle="bold"/>


<TextView
    android:id="@+id/address"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:textStyle="bold" />

list_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView" />
</LinearLayout>

0 个答案:

没有答案