为ListView设置适配器时出现NullPointerException

时间:2013-03-29 09:03:04

标签: java android sdk

首次刷卡LayoutListView我需要帮助... 我会在ListView中显示一些文字,但它不起作用:(

MainActivity.java

package com.evolutio.blocklaunch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
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.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.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;

  private ListView mainListView ;  
  private ArrayAdapter<String> listAdapter ;  

@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

    // Find the ListView resource.   
    mainListView = (ListView) findViewById( R.id.mainListView );  

    // Create and populate a List of planet names.  
    String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",  
                                      "Jupiter", "Saturn", "Uranus", "Neptune"};    
    ArrayList<String> planetList = new ArrayList<String>();  
    planetList.addAll( Arrays.asList(planets) );  

    // Create ArrayAdapter using the planet list.  
    listAdapter = new ArrayAdapter<String>(this, R.layout.news, planetList);  

    // Add more planets. If you passed a String[] instead of a List<String>   
    // into the ArrayAdapter constructor, you must not add more items.   
    // Otherwise an exception will occur.  
    listAdapter.add( "Ceres" );  
    listAdapter.add( "Pluto" );  
    listAdapter.add( "Haumea" );  
    listAdapter.add( "Makemake" );  
    listAdapter.add( "Eris" );  

    // Set the ArrayAdapter as the ListView's adapter.  
    mainListView.setAdapter(listAdapter);

    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

@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;
}

/**
 * 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 DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        int tabLayout = 0;
        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 dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public DummySectionFragment() {
    }

     public static final String ARG_OBJECT = "object";

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

            Bundle args = getArguments();
            int position = args.getInt(ARG_OBJECT);

            int tabLayout = 0;
            switch (position) {
            case 0:
            tabLayout = R.layout.news;
            break;
            case 1:
            tabLayout = R.layout.news;
            break;
            case 2:
            tabLayout = R.layout.news;
            break;
            }

            View rootView = inflater.inflate(tabLayout, container, false);
            return rootView;
        }
}

}

XML-Files

activity_main.xml中

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/pager"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" >

    <!--
   This title strip will display the currently visible page title, as well as the page
   titles for adjacent pages.
   -->

    <android.support.v4.view.PagerTitleStrip
       android:id="@+id/pager_title_strip"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_gravity="top"
       android:background="#33b5e5"
       android:paddingBottom="4dp"
       android:paddingTop="4dp"
       android:textColor="#fff" />

</android.support.v4.view.ViewPager>

Item.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"  
android:id="@+id/rowTextView"  
android:layout_width="fill_parent"  
android:layout_height="wrap_content"  
android:padding="10dp"  
android:textSize="16sp" >  
</TextView>

News.xml

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

    <ListView android:layout_width="fill_parent"  
     android:layout_height="fill_parent"  
     android:id="@+id/mainListView">  
    </ListView>  
</LinearLayout>

错误

03-29 10:01:39.827: D/AndroidRuntime(6902): Shutting down VM
03-29 10:01:39.827: W/dalvikvm(6902): threadid=1: thread exiting with uncaught exception (group=0x2b521930)
03-29 10:01:39.827: E/AndroidRuntime(6902): FATAL EXCEPTION: main
03-29 10:01:39.827: E/AndroidRuntime(6902): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.evolutio.blocklaunch/com.evolutio.blocklaunch.MainActivity}: java.lang.NullPointerException
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2357)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.access$600(ActivityThread.java:153)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.os.Looper.loop(Looper.java:137)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.main(ActivityThread.java:5226)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at java.lang.reflect.Method.invokeNative(Native Method)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at java.lang.reflect.Method.invoke(Method.java:511)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at dalvik.system.NativeStart.main(Native Method)
03-29 10:01:39.827: E/AndroidRuntime(6902): Caused by: java.lang.NullPointerException
03-29 10:01:39.827: E/AndroidRuntime(6902):     at com.evolutio.blocklaunch.MainActivity.onCreate(MainActivity.java:74)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.Activity.performCreate(Activity.java:5104)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
03-29 10:01:39.827: E/AndroidRuntime(6902):     ... 11 more
03-29 10:01:42.327: I/Process(6902): Sending signal. PID: 6902 SIG: 9

3 个答案:

答案 0 :(得分:1)

您使用MainActivity的错误布局,因为您在ListView中添加了News.xml,但为activity_main设置了MainActivity。你应该使用News.xml布局为MainActivity初始化mainListView,其中包含mainListView ListView:

setContentView(R.layout.News);

答案 1 :(得分:0)

LogCat说问题出现在你的MainActivity的第74行,但我认为真正的问题在第53行:

mainListView = (ListView) findViewById( R.id.mainListView );

我认为mainListView为null,因为activity_main.xml中没有这个布局元素(可能是在第82行加载了吗?)

您可以尝试在第82行...

之后移动第53和74行

答案 2 :(得分:0)

试试这个:

package com.kt.listviewexample;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

   /** Here two object are created mainListView and fruits of class ListView and String respectively 
    *   fruits is contains a set of data as array type
    */
    private ListView mainListView;
    String[] fruits = {
            "Mango",
            "Pine-Apple",
            "Guava",
            "Apple",
            "Banana",
            "Grapes",
            "Orange",
            "watermilon",
            "Dates",
            "Olive", 
    };

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

        // called main UI
        setContentView(R.layout.activity_main);

        //Binding the object of ListView
        mainListView = (ListView) findViewById( R.id.mainlistview ); 

       /**
        * A fruitslist object is created of ArrayList type Which holds all element of array(Mango ,Pine-Apple...) , 
        *  in friutlist object
        */

       ArrayList<String> fruitlist = new ArrayList<String>();  
       fruitlist.addAll(Arrays.asList(fruits)); 

       /** Now all these data are bind with a ListView's object for appearance in android device or emulator
        *  with a parameter of current class , name of Xml file which contain TextView , id of that TextView
        *  and finally object of ArrayList in which we all those data
        */
        mainListView.setAdapter(new ArrayAdapter<String>(this, R.layout.list_view, R.id.rowTextView, fruitlist));

        /** Call of listener when we click on every item of ListView
         * 
         */
        mainListView.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // When clicked, show a toast with the TextView text
                if (position == 0) {
                      // do this on first item click
                }

                if (position == 1) {
                      // do this on second item click   
                } else {
                      Toast.makeText(getApplicationContext(), "You have selected " + fruits[position], Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}