NullPointerException onCreateView方法期间出错

时间:2016-08-13 19:07:54

标签: android android-fragments fragment android-arrayadapter

ModAdapterFragment Class

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

/**
 * Created by Deep Depinder Singh on 8/10/2016.
 */
public class ModeAdapterFragment extends android.support.v4.app.Fragment {


    public ListView listView;

    /**
     * Called when the fragment's activity has been created and this
     * fragment's view hierarchy instantiated.  It can be used to do final
     * initialization once these pieces are in place, such as retrieving
     * views or restoring state.  It is also useful for fragments that use
     * {@link #setRetainInstance(boolean)} to retain their instance,
     * as this callback tells the fragment when it is fully associated with
     * the new activity instance.  This is called after {@link #onCreateView}
     * and before {@link #onViewStateRestored(Bundle)}.
     *
     * @param savedInstanceState If the fragment is being re-created from
     *                           a previous saved state, this is the state.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_setting, container, false);

        final ArrayList<DummyData> words = new ArrayList<DummyData>();
        //words.add("One");
        words.add(new DummyData(R.drawable.family_son, "One", "Lutti"));
        words.add(new DummyData(R.drawable.family_son, "two", "Lutti"));
        words.add(new DummyData(R.drawable.family_son, "Three", "Lutti"));
        words.add(new DummyData(R.drawable.family_son, "Four", "Lutti"));

        DummyDataAdapter itemsAdapter = new DummyDataAdapter(getActivity(), words);
        listView = (ListView) v.findViewById(R.id.list);
        listView.setAdapter(itemsAdapter);
        return v;
    }





  /*  @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }
*/

}

DummyDataAdapter类

package com.example.deepdepindersingh.activevoice;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Deep Depinder Singh on 8/13/2016.
 */
public class DummyDataAdapter extends ArrayAdapter<DummyData> {

    public DummyDataAdapter(Context context, ArrayList<DummyData> dummyData){
        super(context, 0, dummyData);
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item_record, parent, false);
        }


        // Get the {@link AndroidFlavor} object located at this position in the list
        DummyData currentAndroidFlavor = getItem(position);



        // Find the TextView in the list_item.xml layout with the ID version_name
        TextView nameTextView = (TextView) listItemView.findViewById(R.id.caller_text_view);
        // Get the version name from the current AndroidFlavor object and
        // set this text on the name TextView
        nameTextView.setText(currentAndroidFlavor.getCallerName());

        // Find the TextView in the list_item.xml layout with the ID version_number
        TextView numberTextView = (TextView) listItemView.findViewById(R.id.date_text_view);
        // Get the version number from the current AndroidFlavor object and
        // set this text on the number TextView
        numberTextView.setText(currentAndroidFlavor.getCallerDate());

        ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);


        imageView.setImageResource(currentAndroidFlavor.getCallerImageResource());


        return listItemView;
    }
}

DummyData类

package com.example.deepdepindersingh.activevoice;

/**
 * Created by Deep Depinder Singh on 8/13/2016.
 */
public class DummyData {

    private String mCallerName;
    private String mCallerDate;
    private int mCallerImageResource;


    public DummyData(int callerImageResource, String callerName, String callerDate ){
        mCallerImageResource = callerImageResource;
        mCallerName = callerName;
        mCallerDate = callerDate;
    }


    public String getCallerName(){
        return mCallerName;
    }

    public String getCallerDate(){
        return mCallerDate;

    }

    public int getCallerImageResource(){
        return mCallerImageResource;
    }
}

布局文件FragmentMode.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

layot文件List_item_record.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="@dimen/list_item_height"
    android:background="@color/colorAccent">
    <ImageView
        android:id="@+id/image"
        android:layout_width="@dimen/list_item_height"
        android:layout_height="@dimen/list_item_height"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/text_container"
        android:orientation="vertical"
        android:paddingLeft="16dp"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:gravity="bottom"
            android:id="@+id/caller_text_view"
            tools:text="lutti"
            android:textAppearance="?android:textAppearanceMedium"
            android:textColor="@android:color/white"
            android:textStyle="bold"
            android:layout_weight="1"

            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/date_text_view"
            tools:text="one"
            android:textAppearance="?android:textAppearanceMedium"
            android:textColor="@android:color/white"
            android:layout_weight="1"
            android:gravity="top"
            />
    </LinearLayout>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/call_button"
        >

    </RelativeLayout>
</LinearLayout>

mainActivity Class

package com.example.deepdepindersingh.activevoice;

import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TableLayout;

public class MainActivity extends AppCompatActivity {

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


        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(adapter);


        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);

    }
}
  

由于我是Android编程的新手,而且我从早上开始对此代码感到厌烦,因此无法找到解决方案   这个代码我想在3个片段中显示数据。请帮我改一下。感谢名单....

Logcat捕获此错误消息

08-14 00:47:46.382 2730-2730/com.example.deepdepindersingh.activevoice W/System: ClassLoader referenced unknown path: /data/app/com.example.deepdepindersingh.activevoice-2/lib/x86_64
08-14 00:47:50.900 2730-2730/com.example.deepdepindersingh.activevoice W/System: ClassLoader referenced unknown path: /data/app/com.example.deepdepindersingh.activevoice-2/lib/x86_64
08-14 00:47:51.003 2730-2740/com.example.deepdepindersingh.activevoice W/art: Suspending all threads took: 16.395ms
08-14 00:47:51.535 2730-2736/com.example.deepdepindersingh.activevoice W/art: Suspending all threads took: 120.484ms
08-14 00:47:51.583 2730-2730/com.example.deepdepindersingh.activevoice W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-14 00:47:51.919 2730-2736/com.example.deepdepindersingh.activevoice W/art: Suspending all threads took: 9.823ms
08-14 00:47:52.192 2730-2846/com.example.deepdepindersingh.activevoice D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                                                                                         [ 08-14 00:47:52.214  2730: 2730 D/         ]
                                                                                         HostConnection::get() New Host Connection established 0x7f85e5913940, tid 2730
08-14 00:47:52.273 2730-2730/com.example.deepdepindersingh.activevoice D/AndroidRuntime: Shutting down VM
08-14 00:47:52.518 2730-2736/com.example.deepdepindersingh.activevoice W/art: Suspending all threads took: 76.800ms

                                                                              --------- beginning of crash
08-14 00:47:52.520 2730-2730/com.example.deepdepindersingh.activevoice E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                         Process: com.example.deepdepindersingh.activevoice, PID: 2730
                                                                                         java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                                             at com.example.deepdepindersingh.activevoice.ModeAdapterFragment.onCreateView(ModeAdapterFragment.java:49)
                                                                                             at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
                                                                                             at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
                                                                                             at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
                                                                                             at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
                                                                                             at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1632)
                                                                                             at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:637)
                                                                                             at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                                                             at android.support.v4.view.ViewPager.populate(ViewPager.java:1237)
                                                                                             at android.support.v4.view.ViewPager.populate(ViewPager.java:1085)
                                                                                             at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1611)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                             at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                                             at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                                             at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                             at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                             at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                             at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                             at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                             at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                                             at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                                             at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                                             at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                                             at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
                                                                                             at android.view.View.measure(View.java:18788)
                                                                                             at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
                                                                                             at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
                                                                                             at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
                                                                                             at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                                             at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                                             at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                                             at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                                             at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                                             at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                                             at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

3 个答案:

答案 0 :(得分:0)

在您的ModAdapterFragment中,您正在充气R.layout.fragment_setting并尝试查找ID为ListView的{​​{1}}元素。但是,该列表视图(R.id.list)存在于文件R.id.list中。我认为您需要在ModAdapterFragment类的FragmentMode.xml中夸大此文件而不是R.layout.fragment_setting

答案 1 :(得分:0)

ListView v未在onCreateView

中初始化

使用v = (ListView) v.findViewById(R.id.YOURLISTVIEWID);

之类的内容

答案 2 :(得分:0)

您必须为同一个xml文件充气:

 View v = inflater.inflate(R.layout.fragment_setting, container, false);

必须替换为:

 View v = inflater.inflate(R.layout.FragmentMode, container, false);