gpt4 book ai didi

android - 用列表保存 RecyclerView 状态

转载 作者:行者123 更新时间:2023-11-29 01:04:04 25 4
gpt4 key购买 nike

我正在尝试保存 RecyclerView 的状态,以便即使在旋转时也能显示数据。我实际上是通过保存 LayoutManager 的状态来解决这个问题的。我在旋转时遇到的错误是:

Process: com.example.android.guardiannewsapp, PID: 25829
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.support.v7.widget.RecyclerView$LayoutManager.onSaveInstanceState()' on a null object reference
at com.example.android.guardiannewsapp.MainActivity.onSaveInstanceState(MainActivity.java:80)

我想我了解问题所在,但不确定如何解决。错误指向这个方法:

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListState = mLayoutManager.onSaveInstanceState();
outState.putParcelable(STATE_LIST, mListState);
}

还有这一行

mListState = mLayoutManager.onSaveInstanceState();

这是我的 MainActivity 代码:

包 com.example.android.guardiannewsapp;

import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<News>> {

//Constant value for the news loader ID. We can choose any integer. We do this if we
//are using multiple loaders. We aren't in this app but good practice.
private static final int EARTHQUAKE_LAODER_ID = 1;

RecyclerView recyclerView;
private TextView emptyView;
private ProgressBar progressBar;
private ConnectivityManager cm;
private TextView internetConnectionEmptyView;
private List<News> mNews;
private LoaderManager loaderManager;
private static final String STATE_LIST = "State Adapter Data";
RecyclerView.LayoutManager mLayoutManager;
private Parcelable mListState;

//Adapter for the list of news articles
private NewsAdapter mAdapter;

//User search term
private String userSearch = "";

//URL to query the Guardian dataset for search query
private String GUARDIAN_REQUEST_URL = "";


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

//Find a reference to the RecyclerView in the layout
recyclerView = findViewById(R.id.recyclerView);

//Find a reference to the empty view
emptyView = findViewById(R.id.empty_view);

//Find a reference to the progress bar and keep it hidden
progressBar = findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);

//Find a reference to the no internet connection message.
internetConnectionEmptyView = findViewById(R.id.no_internet_connection);

recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext()));

}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListState = mLayoutManager.onSaveInstanceState();
outState.putParcelable(STATE_LIST, mListState);
}

@Override
public void onRestoreInstanceState(Bundle outState) {
super.onRestoreInstanceState(outState);

if (outState != null) {
mListState = outState.getParcelable(STATE_LIST);
}

}

@Override
protected void onResume() {
super.onResume();
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Associate searchable configuration with the SearchView
final SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
userSearch = query;

cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

//Initialize the loader. Pass in the int ID constant defined above and pass in null
//for the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
//because this activity implements the LoaderCallbacks interace).
if (activeNetwork != null && activeNetwork.isConnected()) {
// Get a reference to the LoaderManager, in order to interact with loaders.
loaderManager = getLoaderManager();

//Initialize the loader. Pass in the int ID constant defined above and pass in null
//for the bundle. Pass in the activity for the LoaderCallbacks parameter (which is valid
//because this activity implements the LoaderCallbacks interface.)
loaderManager.initLoader(EARTHQUAKE_LAODER_ID, null, MainActivity.this);

loaderManager.restartLoader(EARTHQUAKE_LAODER_ID, null, MainActivity.this);
} else {
//If there is no network connection, hide the loading indicator and show the
//no internet connection message.
internetConnectionEmptyView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
}

searchView.clearFocus();
return true;
}

@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});{
}

return true;
}

//When the LoaderManager determines that the loader with our specified ID isn't running to
//create a new one.
@Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
GUARDIAN_REQUEST_URL = "http://content.guardianapis.com/search?show-fields=thumbnail&q="+userSearch+
"&api-key=23a6ee65-f55d-452f-a073-0bc71e36bb8b";

return new NewsLoader(this, GUARDIAN_REQUEST_URL);
}

@Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {

mNews = news;
//If the list is empty, the app will show the emptyView message
if (news.isEmpty()){
emptyView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.INVISIBLE);
} else {

//Once the view populates, hide the progress bar.
progressBar.setVisibility(View.INVISIBLE);

//Create a new adapter that takes an empty list of news articles as input
mAdapter = new NewsAdapter(this, news);

//Create a new adapter that takes an empty list of news articles as input
mAdapter = new NewsAdapter(this, news);

//Set the adapter on the RecyclerView so the list can be populated in the user interface.
mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}

}

@Override
public void onLoaderReset(Loader<List<News>> loader) {

}

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;

public DividerItemDecoration(Context context){
mDivider = context.getResources().getDrawable(R.drawable.horizontal_line);
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
int dividerLeft = parent.getPaddingLeft();
int dividerRight = parent.getWidth() - parent.getPaddingRight();

int childCount = parent.getChildCount();
for (int i = 0; i < childCount - 1; i++) {
View child = parent.getChildAt(i);

RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

int dividerTop = child.getBottom() + params.bottomMargin;
int dividerBottom = dividerTop + mDivider.getIntrinsicHeight();

mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom);
mDivider.draw(c);
}
}
}

}

最佳答案

看起来mLayoutManager还没有设置。由于是在onLoadFinished()中设置的,要么onLoadFinished()没有运行,要么news.isEmpty()为true,所以mLayoutManager 仍然不会被设置。

应该没问题,在onCreate()中设置mLayoutManager即可。那应该可以解决问题。您也可以在 onSaveInstanceState() 中使用它之前检查 mLayoutManager 是否为 null。

关于android - 用列表保存 RecyclerView 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48869012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com