将主循环器视图从content_main移动到我的res文件中的另一个布局后,应用程序崩溃

时间:2016-08-06 08:16:55

标签: java android-studio android-recyclerview

如果回收站视图位于content_main.xml文件中,则应用程序可以正常运行

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="pv.devclub.spartans.MainActivity"
tools:showIn="@layout/app_bar_main"
android:background="#ffffff">

<android.support.v7.widget.RecyclerView
    android:id="@+id/RecyclerView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    />
</RelativeLayout>

我将recyclerview移至另一个布局并从Content_main中删除

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="pv.devclub.spartans.MainActivity"
tools:showIn="@layout/app_bar_main"
android:background="#ffffff">

<android.support.v7.widget.RecyclerView
    android:id="@+id/RecyclerView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    />
</RelativeLayout>
</RelativeLayout>

应用程序崩溃并向我提供此错误日志

08-06 00:23:46.281 13143-13143/pv.devclub.spartans E/AndroidRuntime: FATAL    EXCEPTION: main
                                                                 Process: pv.devclub.spartans, PID: 13143
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{pv.devclub.spartans/pv.devclub.spartans.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
                                                                     at android.app.ActivityThread.access$1100(ActivityThread.java:222)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                                     at pv.devclub.spartans.MainActivity.onCreate(MainActivity.java:124)
                                                                     at android.app.Activity.performCreate(Activity.java:6876)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) 
                                                                     at android.app.ActivityThread.access$1100(ActivityThread.java:222) 
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) 
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                     at android.os.Looper.loop(Looper.java:158) 
                                                                     at android.app.ActivityThread.main(ActivityThread.java:7229) 
                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

主要活动

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
public static class LoomViewHolder extends RecyclerView.ViewHolder
{
    // Main Events
    public TextView loomDay;
    public TextView loomEvent;
    public TextView loomSubeventA;
    public TextView loomSubeventB;
    public TextView loomSubeventC;
    public TextView loomSubeventD;
    public TextView loomSubeventE;
    // Id to Text Initialization
    public LoomViewHolder(View v){
        super(v);
        // Main Events
        loomDay = (TextView)itemView.findViewById(R.id.day);
        loomEvent = (TextView)itemView.findViewById(R.id.event);
        loomSubeventA = (TextView)itemView.findViewById(R.id.subeventA);
        loomSubeventB = (TextView)itemView.findViewById(R.id.subeventB);
        loomSubeventC = (TextView)itemView.findViewById(R.id.subeventC);
        loomSubeventD = (TextView)itemView.findViewById(R.id.subeventD);
        loomSubeventE = (TextView)itemView.findViewById(R.id.subeventE);
    }
}
// Setting Variables
public static final String LOOMS = "looms";
private static final String TAG = "MainActivity";
private RecyclerView mLoomRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<mainday, LoomViewHolder> mFirebaseAdapter;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Setting Main View
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Initializing Variables for the recycler view
    mLoomRecyclerView = (RecyclerView)findViewById(R.id.RecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(false);
    // Initializing main Drawer fot the main view
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    // Database Initialization
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<mainday, LoomViewHolder>(
            mainday.class,
            R.layout.first_layout,
            LoomViewHolder.class,
            mFirebaseDatabaseReference.child(LOOMS)) {
        @Override
        protected void populateViewHolder(LoomViewHolder viewHolder, mainday model, int position) {
            viewHolder.loomDay.setText(model.getday());
            viewHolder.loomEvent.setText(model.getevent());
            viewHolder.loomSubeventA.setText(model.getSubeventA());
            viewHolder.loomSubeventB.setText(model.getSubeventB());
            viewHolder.loomSubeventC.setText(model.getSubeventC());
            viewHolder.loomSubeventD.setText(model.getSubeventD());
            viewHolder.loomSubeventE.setText(model.getSubeventE());

        }
    };



    // Setting Database Adapter In/Out
    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver(){
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount){
            super.onItemRangeInserted(positionStart, itemCount);
            int roomCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            if (lastVisiblePosition == -1 || (positionStart >= (roomCount -1) && lastVisiblePosition == (positionStart -1))){
                mLoomRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    // Finalizing adapter view and Initializing the view
    mLoomRecyclerView.setLayoutManager(mLinearLayoutManager);
    mLoomRecyclerView.addItemDecoration(new VerticalSpace(0));
    mLoomRecyclerView.setAdapter(mFirebaseAdapter);
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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();

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

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    FragmentManager fragmentManager = getFragmentManager();

    if (id == R.id.nav_first_layout) {
        fragmentManager.beginTransaction()
                .replace(R.id.content_frame
                        , new FirstFragment())
                .commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pv.devclub.spartans" >

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" > </activity>

    <activity
        android:name=".splash"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>

</application>

1 个答案:

答案 0 :(得分:0)

主要活动的onCreate()方法有这一行mLoomRecyclerView = (RecyclerView)findViewById(R.id.RecyclerView);现在这个findViewbyId在setContentView(R.id.<layout_file>);

的布局集中找到了该视图

根据您的代码,您已将内容视图设置为R.layout.content_main,但那里没有RecyclerView小部件。因此,初始化RecyclerView(mLoomRecyclerView = (RecyclerView)findViewById(R.id.RecyclerView))的语句将导致NullPointerException。