简体   繁体   中英

ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

I want to have a listview. But I am getting below error.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.photoapp/com.example.photoapp.ViewAdmins}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

Here is my code.

 public class ViewAdmins extends AppCompatActivity {

    SyncAdminsDatabaseHelper mSyncAdminsDatabaseHelper;
    private ListView ymListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_data);

        ymListView = (ListView) findViewById(R.id.listviewadmins);
        mSyncAdminsDatabaseHelper = new SyncAdminsDatabaseHelper(this);

        //call method populateListView();
        populateListView();

    }
    private void populateListView(){

        //get the data to append in the list view
        Cursor data = mSyncAdminsDatabaseHelper.getData();

        if(data.getCount() == 0){
            toastMessage("The database is empty.");
        }else{

            //Create an Array list
            ArrayList<String> listData = new ArrayList<>();

            //Store the result in array using while loop
            while (data.moveToNext()){
                //get the value from the database in column 1
                //than add to array list
                listData.add(data.getString(0));

            }
            System.out.println(listData);
//        //create the list adapter and set the adapter
            ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listData);
           ymListView.setAdapter(adapter);


        }


    }

I want to show data from an app table to the list view. But for some reason, my list view is not rendering the data properly.

My question is how to get data from the SQLite table and display in the list view.

And also how to display multiple fields in the list view.

Activity_view_admins.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewAdmins">


    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listviewadmins">

    </ListView>
</LinearLayout>

here is what i did a couple of years back, but instead of reading from a SQL lite, im reading returned from my webservice. but it should give you an idea of how to populate a listview.

   public class MainActivity extends AppCompatActivity {
    private static final String url = "http://10.0.2.2/android_app/urltomywebservice";
    private ProgressDialog dialog;
    private List<Item> array = new ArrayList<Item>();
    private ListView listView;
    private Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list_item);
        adapter=new Adapter(this,array);
        listView.setAdapter(adapter);

        dialog=new ProgressDialog(this);
        dialog.setMessage("Loading...");
        dialog.show();

        //Creat volley request obj
        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                hideDialog();
                //parsing json
                for(int i=0;i<response.length();i++){
                    try{
                        JSONObject obj=response.getJSONObject(i);
                        Item item=new Item();
                        item.setTitle(obj.getString("Title"));
                        item.setImage(obj.getString("Image"));
                        item.setRate(obj.getInt("rating"));
                        item.setPrice(obj.getInt("Price"));



                        //add to array
                        array.add(item);
                    }catch(JSONException ex){
                        ex.printStackTrace();
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        AppController.getmInstance().addToRequesQueue(jsonArrayRequest);
    }
    public void hideDialog(){
        if(dialog !=null){
            dialog.dismiss();
            dialog=null;
        }
    }

    }

here the array im adding to the listview is a list of which my model for setting and getting the required data. you can create something similar if it suit you.

private List<Item> array = new ArrayList<Item>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM