android - 屏幕旋转时Listview不保存项目 - Android Studio
问题描述
好的,我有一个通过 JSON 获取数据的新闻程序。它有一个自定义适配器,主要包括字符串和图像。屏幕顶部有一个搜索按钮和用于搜索条件的 editText。这还没有起作用,但稍后会很容易修复。无论如何它工作正常,但是当我旋转屏幕时,数据消失了,你必须再次按下搜索按钮。但实际上它永远不会重新加载数据。我希望它是主要活动中的内容,所以我将其包含在此处。任何帮助,将不胜感激!
package com.example.android.newsreport;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class NewsReportActivity extends AppCompatActivity
implements LoaderCallbacks<List<Story>> {
private static final String LOG_TAG = NewsReportActivity.class.getName();
private String NewsApiUrl ="http://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=021abbfbc4de4c33b1644057d5f2be58";
/**
* Constant value for the Book loader ID. We can choose any integer.
* This really only comes into play if you're using multiple loaders.
*/
private static final int BOOK_LOADER_ID = 1;
private static String TAG = "MainActivity";
/** Adapter for the list of books */
private StoryAdapter mAdapter;
private StoryAdapter saveStateAdapter;
/** TextView that is displayed when the list is empty */
private TextView mEmptyStateTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_activity);
ListView newsListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
newsListView.setEmptyView(mEmptyStateTextView);
// Create a new adapter that takes an empty list of books as input
mAdapter = new StoryAdapter(this, new ArrayList<Story>());
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
newsListView.setAdapter(mAdapter);
/// End Button search
// Set an item click listener on the ListView, which sends an intent to a web browser
// to open a website with more information about the selected book.
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current book that was clicked on
Story currentstory = mAdapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri newsUri = Uri.parse(currentstory.getPreviewLink());
// Create a new intent to view the book URI
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
// Send the intent to launch a new activity
startActivity(websiteIntent);
}
});
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
}
@Override
public Loader<List<Story>> onCreateLoader(int i, Bundle bundle) {
// Create a new loader for the given URL
return new StoryLoader(this, NewsApiUrl);
}
@Override
public void onLoadFinished(Loader<List<Story>> loader, List<Story> bookworms) {
// Hide loading indicator because the data has been loaded
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
// Set empty state text to display "No books found."
mEmptyStateTextView.setText(R.string.no_stories);
// Clear the adapter of previous book data
mAdapter.clear();
// If there is a valid list of {@link Book}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (bookworms != null && !bookworms.isEmpty()) {
mAdapter.addAll(bookworms);
//mAdapter.notifyDataSetChanged();
}
}
@Override
public void onLoaderReset(Loader<List<Story>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
public void goQuery(View view){
EditText mySearchTextView = findViewById(R.id.searchEdit);
if (mySearchTextView.getText().length() < 1) return;
// ListView newsListView = (ListView) findViewById(R.id.list);
// TextView bookwormTextView = (TextView) findViewById(R.id.empty_view);
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.VISIBLE);
NewsApiUrl = "http://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=021abbfbc4de4c33b1644057d5f2be58";
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// Get a reference to the LoaderManager, in order to interact with loaders.
android.app.LoaderManager loaderManager = getLoaderManager();
loaderManager.destroyLoader(BOOK_LOADER_ID);
mAdapter.clear();
mAdapter.notifyDataSetChanged();
// If there is a network connection, fetch data
if (networkInfo != null && networkInfo.isConnected()) {
// 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 interface).
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
} else {
// Otherwise, display error
// First, hide loading indicator so error message will be visible
loadingIndicator.setVisibility(View.GONE);
// Update empty state with no connection error message
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mySearchTextView.getWindowToken(), 0);
}
}
解决方案
推荐阅读
- ios - 在用户周围显示多个驱动程序注释(使用数据库)
- r - R:按日期为 0 的完整状态
- javascript - 如何添加加号登录数字 - Bootstrap TouchSpin Spinner
- perl - CPAN_JSON 的意外行为
- azure - Azure 网络/VNet、负载均衡器、应用程序网关、流量管理器是否总是需要 VM?
- node.js - 不变性助手更新一个属性但不更新其他属性?
- react-native - React Native 的 fetch 缓存行为是什么
- r - 如何使用 Caret 为每个交叉验证绘制 ROC 曲线
- java - Espresso 测试在设备上失败,而不是在模拟器上
- javascript - 尾递归 reduce 函数返回 [..., [Curcular] ]