Question

I've recently began working through Android tutorials and, though not a tutorial in itself, I've started working from this page in an attempt to implement a simple ListView.

I've started with a New Android Application Project in a version of the Android SDK that I downloaded just last week, and have modified two files in a way that I believe to be in line with the above material, and this page.

However, upon starting my application up on my HTC One, it immediately fails with the message "Unfortunately, [my app] has stopped." I've found a single line of code that I can comment out to make it not crash, but in doing so I'm avoiding initialising the ListView and so the result is an empty view.

As mentioned, I've only changed the contents of two files from the default for a New Android Application Project, but here they are in full:

fragment_main.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testproj.MainActivity$PlaceholderFragment">

    <ListView
        android:id="@+id/main_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.example.recipeorganiserforandroid;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] myArray = new String[] {"Tomato", "Potato", "Carrot", "Mushroom", "Beef", "Cheese", "Lettuce", "Bread", "Milk", "Spinach", "Chicken", "Rice"};

        setContentView(R.layout.activity_main);

        ListView myList = (ListView) findViewById(R.id.main_list);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myArray);

        myList.setAdapter(adapter);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

}

I note that the second example page I linked to above used a different constructor for ArrayAdapter but trying that doesn't give me more success. If I comment out the line myList.setAdapter(adapter); then my application runs successfully but, obviously, doesn't provide any content within my ListView view.

I've had a look for other examples online but all I've found have been considerably more complicated and I don't think throwing more ideas into the mix is going to make this any clearer in my mind. Can anyone suggest what I might be doing wrong here?

Was it helpful?

Solution

As you are using a Fragment, you should be initializing the data and setting the adapter in the Frament class. For that reason your app is crashing, when you call myList.setAdapter(adapter) from the Activity, myList is probably Null because you are trying to retrieve it from the Activity, and the ListView is in the Fragment.

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        String[] myArray =
                new String[] {
                        "Tomato", "Potato", "Carrot", "Mushroom", "Beef", "Cheese", "Lettuce",
                        "Bread", "Milk", "Spinach", "Chicken", "Rice"
                };

        ListView myList = (ListView) rootView.findViewById(R.id.list_main);

        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,
                                         myArray);

        myList.setAdapter(adapter);

        return rootView;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top