listView.setAdapter()中的空指针异常

时间:2014-06-13 11:12:48

标签: java android listview android-listview android-arrayadapter

我在以下代码中有一个NullPointerException

package com.BriteLabs.caloriecounter.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import android.content.Intent;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

Intent intent;
TextView foodId;

CalorieDatatabaseManagement db = new CalorieDatatabaseManagement(this);

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    ArrayList<HashMap<String, String>> foodList = db.getAllFood();
    if(foodList.size() != 0){
        Log.i("MyActivity",foodList.toString());
        ListView listView = (ListView) findViewById(R.id.foodListView);

        ArrayAdapter<HashMap<String, String>> arrayAdapter = new ArrayAdapter<HashMap<String, String>>(
                this,
                android.R.layout.simple_list_item_1,
                foodList );
        listView.setAdapter(arrayAdapter);
    }
}

   public void addNewFood(View view){
    HashMap<String, String> queryValuesMap = new HashMap<String, String>();

    EditText foodName = (EditText) findViewById(R.id.foodAddEditText);
    EditText foodCalories = (EditText) findViewById(R.id.calorieAddEditText);

    queryValuesMap.put("foodName", foodName.getText().toString());
    queryValuesMap.put("foodCalories", foodCalories.getText().toString());

    db.addFood(queryValuesMap);
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        //Camera
        //Main calorie page
        //Settings
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return 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;
    }
}

}

将条目添加到数据库后,错误发生在listView.setAdapter(arrayAdapter);,我尝试在listView中显示错误。

错误如下:

Caused by: java.lang.NullPointerException
at com.BriteLabs.caloriecounter.app.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)  

foodList项目不为空,因为它包含以下数据:[{foodName=Test food, foodId=1, foodCalories=500}]

fragment_main.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.BriteLabs.caloriecounter.app.MainActivity$PlaceholderFragment">

<ProgressBar
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/titleTextView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Calories Consumed Today:"
    android:id="@+id/titleTextView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/foodListView"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/foodAddEditText"
    android:layout_alignRight="@+id/progressBar"
    android:layout_alignEnd="@+id/progressBar" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="0"
    android:id="@+id/currentCaloriestextView"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/titleTextView"
    android:layout_marginLeft="25dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/foodAddEditText"
    android:text="Food Name"
    android:layout_below="@+id/progressBar"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:paddingTop="20dp"/>

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/calorieAddEditText"
    android:layout_alignBottom="@+id/foodAddEditText"
    android:layout_toRightOf="@+id/foodAddEditText"
    android:text="Calories"
    android:layout_toLeftOf="@+id/foodAddButton" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add"
    android:id="@+id/foodAddButton"
    android:layout_alignBottom="@+id/calorieAddEditText"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignTop="@+id/calorieAddEditText"
    android:layout_toRightOf="@+id/titleTextView"
    android:onClick="addNewFood"/>

</RelativeLayout>

3 个答案:

答案 0 :(得分:1)

使用onCreateView因为您正在使用片段。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_main, container, false);

    ListView listView = (ListView) view.findViewById(R.id.foodListView);

    // Set adapter here...

    return view;
}

答案 1 :(得分:0)

就像我在评论中所说的那样,你可以在片段中使用“创建视频”,而不是在“创建活动”中进行操作。

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

    CalorieDatatabaseManagement db = new CalorieDatatabaseManagement(getActivity());
    ArrayList<HashMap<String, String>> foodList = db.getAllFood();
    if(foodList.size() != 0) {
        ListView listView = (ListView) rootView.findViewById(R.id.foodListView);

        ArrayAdapter<HashMap<String, String>> arrayAdapter = new 
            ArrayAdapter<HashMap<String, String>>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                foodList );
        listView.setAdapter(arrayAdapter);
        return rootView;
    }
}

答案 2 :(得分:0)

之前我遇到过同样的问题,但错误的是,我选择了错误的布局,只有ImageView。而我需要的布局是TextView。因为我试图将String Array填充到列表视图中。

而不是

View view=inflater.inflate(R.layout.activity_albums,container,false);

我写过

View view=inflater.inflate(R.layout.albums,container,false);

我知道这篇文章已经回答了,但是相同的错误代码有不同类型的问题。对于某人进行快速检查可能会有用。