1

I was following this tutorial.

I've modified it to my app's needs, such as no CRUD functionality and no main menu - I just want to list all the items during the main activity that gets executed when the app is launched.

Code seems to have no errors, but running it gives me: Unfortunately, MyFirstApp has stopped in the VM.

LogCat gives me this:

E/AndroidRuntime(910): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstproject/com.example.myfirstproject.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

What do? I've checked my .xml layouts and made the changes, but the app still crashes.

MainActivity.java

package com.example.myfirstproject;

//imports

public class MainActivity extends ListActivity implements OnItemClickListener {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> carsList;

    // url to get all products list
    private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CARS = "cars";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray cars = null;

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

        // Hashmap for ListView
        carsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllcars().execute();

        // Get listview
        ListView lv = getListView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllcars extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading cars. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All cars: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    cars = json.getJSONArray(TAG_CARS);

                    // looping through All Products
                    for (int i = 0; i < cars.length(); i++) {
                        JSONObject c = cars.getJSONObject(i);

                        // Storing each json item in variable
                        String title = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        carsList.add(map);
                    }
                } else {
                    // no products found
                    pDialog = new ProgressDialog(MainActivity.this);
                    pDialog.setMessage("No cars found");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(false);
                    pDialog.show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this, carsList,
                            android.R.id.list, new String[] {TAG_NAME},
                            new int[] { R.id.title });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
    }
}

activity_main.xml (layout for the mainactivity with listview):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </ListView>   
</LinearLayout>

list_item.xml (layout for individual list items):

<?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" >

    <!-- Name Label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17dip"
        android:textStyle="bold" />

</LinearLayout>
user1701467
  • 285
  • 2
  • 7
  • 20

5 Answers5

6

Take a look at how they define the layout in the ListActivity documentation here

Your ListView Id is android:id="@+id/list" and it needs to be android:id="@android:id/list"

additionally, your ListAdapter is going to crash

ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this, carsList,
                            android.R.id.list, new String[] {TAG_NAME},
                            new int[] { R.id.title });

You are telling the adapter to use the android ListView as the Item view.. You should be passing in your list_item.xml ID for this and using the proper TextView ID (name)

ex:

ListAdapter adapter = new SimpleAdapter(
                                MainActivity.this, carsList,
                                R.layout.list_item, new String[] {TAG_NAME},
                                new int[] { R.id.name});
dymmeh
  • 22,247
  • 5
  • 53
  • 60
  • Seems to get to the "Loading cars...Please wait" dialog, but after some time it crashes again. LogCat gives the following: `E/Buffer Error(999): Error converting result java.lang.NullPointerException E/JSON Parser(999): Error parsing data org.json.JSONException: End of input at character 0 of E/AndroidRuntime(999): FATAL EXCEPTION: AsyncTask #1 E/AndroidRuntime(999): java.lang.RuntimeException: An error occured while executing doInBackground()`. Sorry, I'm very new to this and the error doesn't seem to tell me much like the previous did besides that there's some NullPointerException somewhere – user1701467 Nov 02 '12 at 21:23
  • It looks like somewhere in your JSON parsing you are getting a null pointer. In the stack trace it should point to the line in your code where its crashing – dymmeh Nov 02 '12 at 21:28
  • Looks like it's this line: `JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);`, therefore it implies that it doesn't get the list of cars from my PHP webservice(running on wamp)? Why wouldn't it work? If I go straight to the `url_all_cars` path in any web browser I get the JSON list generated properly. – user1701467 Nov 02 '12 at 21:32
  • Do you have the internet permission set in your apps manifest? http://stackoverflow.com/questions/2378607/what-permission-do-i-need-to-access-internet-from-an-android-application – dymmeh Nov 02 '12 at 21:35
  • Just did. Same problem on the same line. But I'm using a localhost(MySQL, WAMP on my computer) so do I need that permission? – user1701467 Nov 02 '12 at 21:55
  • Also, this line sets the error off: `Log.d("All Cars: ", json.toString());` – user1701467 Nov 02 '12 at 22:24
  • please don't use the comments to ask additional questions; new questions should be created as a new question... – slinden77 Jul 21 '16 at 06:17
2

In your activity_main.xml use android:id="@android:id/list" and not android:id="@+id/list" and it should work.

For now the ID of your ListView is yourapplicationpackage.R.id.list.

Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
2

use android:id="@android:id/list" while assigning the id in xml.

Imran Ali
  • 539
  • 4
  • 17
1

Note that the id of the ListView must be @android:id/list to reference the required android.R.id.list per the ListActivity documentation.

In contrast, your id of @+id/list creates a new id com.example.myfirstproject.R.id.list.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
0

It is old post but for others who faced same problem here is my solution:

If you are make sure, the ID of the List View or any other object you created is existed in layout - To make sure go head to gen sources, check the name of the id in R.java file. If it is not there, then you didn't create any item. - Then, In Java Code make sure android.R is not in the import list. If so rid off. Then manually add your package R.java import com.yourpackagename.R; Now you are able to add our item into Java Code: exp: ListView lvitems = (ListView) findViewById(R.id.nameofit);

I don't recommend that Project>Clean in these situations, you could easily lose your generated R.java file.

cyberlyn06
  • 31
  • 5