ОК. У меня есть новостная программа, которая получает данные через 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);
}
}