空对象引用setAdapter

时间:2016-07-08 03:13:09

标签: java android

这是我的代码: MainActivity:

 package com.example.apekshit.materialdesign;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        DrawerLayout dl = (DrawerLayout) findViewById(R.id.drawlayid);
        Navigationdrawer fragment = (Navigationdrawer) getSupportFragmentManager().findFragmentById(R.id.drawer);
        fragment.setUp(dl, toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

片段:

package com.example.apekshit.materialdesign;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;


public class Navigationdrawer extends android.support.v4.app.Fragment {
    private ActionBarDrawerToggle abdt;
    private DrawerLayout drawerlayout;
    RecyclerView rv;
    myAdapter a;


    public Navigationdrawer() {
        // Required empty public constructor
    }

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

    }
    public List<Info> getdata(){
        List<Info> list=new ArrayList<>();
        String[] titles={"CAT","CATERPILLAR","ELEPHANT","FROG"};
        int[] icons={R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d};
        for(int i=0;i<titles.length&&i<icons.length;i++){
            Info obj=new Info();
            obj.id=icons[i];
            obj.text=titles[i];
            list.add(obj);
        }
        return list;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_navigationdrawer, container, false);
        rv=(RecyclerView)getActivity().findViewById(R.id.recyclerlist);


        a=new myAdapter(getActivity(),getdata());
        rv.setAdapter(a);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));

        return v;
    }


    public void setUp(DrawerLayout dl, final Toolbar toolbar) {
        drawerlayout = dl;
        abdt = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar, R.string.string_open, R.string.string_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                if(slideOffset<0.6){
                    toolbar.setAlpha(1-slideOffset);
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getActivity().invalidateOptionsMenu();

            }
        };
        drawerlayout.setDrawerListener(abdt);
        drawerlayout.post(new Runnable() {
            @Override
            public void run() {
                abdt.syncState();
            }
        });
    }


}

适配器类:

package com.example.apekshit.materialdesign;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by Apekshit on 07-07-2016.
 */
public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder>{
    LayoutInflater inflater;
    List<Info> l= Collections.emptyList();
   Info info;
    public myAdapter(Context context, List<Info> Data){
        l=Data;


         inflater = LayoutInflater.from(context);

    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v=inflater.inflate(R.layout.rowlayout,viewGroup,false);
        MyViewHolder holder=new MyViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(myAdapter.MyViewHolder viewHolder, int i) {
     info=l.get(i);
        viewHolder.title.setText(info.text);
        viewHolder.icon.setImageResource(info.id);
    }

    @Override
    public int getItemCount() {
        return l.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title= (TextView) itemView.findViewById(R.id.textView);
            icon= (ImageView) itemView.findViewById(R.id.imageView);
        }
    }
}

当我启动应用程序时,它会崩溃。 logcat的:

07-08 08:40:31.919  27773-27773/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.apekshit.materialdesign, PID: 27773
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apekshit.materialdesign/com.example.apekshit.materialdesign.MainActivity}: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2330)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5273)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
     Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:767)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:508)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:418)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
            at com.example.apekshit.materialdesign.MainActivity.onCreate(MainActivity.java:15)
            at android.app.Activity.performCreate(Activity.java:6041)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5273)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
            at com.example.apekshit.materialdesign.Navigationdrawer.onCreateView(Navigationdrawer.java:55)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1061)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1264)
            at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1366)
            at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2409)
            at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
            at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:374)
            at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
            at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:737)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:508)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:418)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
            at com.example.apekshit.materialdesign.MainActivity.onCreate(MainActivity.java:15)
            at android.app.Activity.performCreate(Activity.java:6041)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5273)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

fragment_navigationdrawer.xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="240dp"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="#7C6C77"
        android:gravity="center_horizontal|center_vertical"
        android:text="Apekshit Tewathia"

        android:textColor="#FFF" />

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/recyclerlist">

</android.support.v7.widget.RecyclerView></RelativeLayout>

activity_main.xml中:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:fitsSystemWindows="true"
    xmlns:android="http://schemas.android.com/apk/res/android">
<include android:id="@+id/app_bar"
    layout="@layout/app_bar"/>

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawlayid">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
/>


    <fragment
        android:id="@+id/drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        class="com.example.apekshit.materialdesign.Navigationdrawer"
        tools:layout="@layout/fragment_navigationdrawer"
        app:layout="@layout/fragment_navigationdrawer"/>

</android.support.v4.widget.DrawerLayout>
</LinearLayout>

请帮我解释一下代码。我搜索了很多内容,我似乎找不到任何解决方案。谢谢提前:) 另外,这是我的第一个问题,请告诉我,如果我没有正确发布问题,请告诉我如何以更好的方式发布问题。谢谢 我看了一下nullpointerexplanation的不同解释,但仍然无法找到我的代码中的错误。这就是为什么我发布在这里。问题我的问题被标记为重复,因为我不能解释问题

1 个答案:

答案 0 :(得分:1)

first之前setLayoutManager需要setAdapter secondfragment_navigationdrawer布局文件rv=(RecyclerView)getActivity().findViewById(R.id.recyclerlist); 24 中存在错误。

rv=(RecyclerView)v.findViewById(R.id.recyclerlist);

应该是

onCreateView

此处,因为在创建活动之前调用此getActivity()以便event.stopPropagation()返回null。