我正在构建一个应用程序,显示您搜索过的图书的详细信息。问题是每次我更改设备的方向时,列表视图元素都会消失。我想要帮助他们如何让它们不消失。我有一种感觉,我需要使用Loader,但我不知道如何实现它。这是我的活动。
MainActivity: -
package com.example.visha.booklistingapp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BookAdapter mAdapter;
EditText searchtext;
ListView earthquakeListView;
TextView empty;
TextView authorcheck;
TextView titlecheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
earthquakeListView = (ListView) findViewById(R.id.listView);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
earthquakeListView.setAdapter(mAdapter);
searchtext = (EditText) findViewById(R.id.editText);
empty = (TextView) findViewById(R.id.textView);
earthquakeListView.setEmptyView(empty);
}
public void searchclick(View view) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
String parturl = searchtext.getText().toString();
parturl = parturl.replaceAll("\\s","");
StringBuilder urlbuilder = new StringBuilder();
urlbuilder.append(" https://www.googleapis.com/books/v1/volumes?q=");
urlbuilder.append(parturl);
urlbuilder.append("&maxResults=5");
String url = urlbuilder.toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(url); }
else{
Toast.makeText(getApplicationContext(), "You are not connected to the internet",
Toast.LENGTH_LONG).show();
}
}
private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
@Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
@Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
QueryUtils: -
package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by visha on 14-10-2016.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Book> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Book> Books = extractFeatureFromJson(jsonResponse);
return Books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Book> extractFeatureFromJson(String BookJSON) {
if (TextUtils.isEmpty(BookJSON)) {
return null;
}
List<Book> Books = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(BookJSON);
JSONArray BookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i < BookArray.length(); i++) {
JSONObject currentBook = BookArray.getJSONObject(i);
JSONObject properties = currentBook.getJSONObject("volumeInfo");
String author;
if(properties.has("authors")) {
author = properties.getString("authors");
}
else {
author = "";
}
String title = properties.getString("title");
Book Book = new Book(author, title);
Books.add(Book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
}
return Books;
}
}
答案 0 :(得分:0)
您需要覆盖Activity类的onSaveInstanceState和onRestoreInstanceState方法。
在onSaveInstanceState中,将列表数据保存到Bundle中。
在onRestoreInstanceState中,使用Bundle数据恢复列表并重新创建列表适配器。
干杯!!!
答案 1 :(得分:0)
如果您没有活动横向模式的不同布局,那么只需添加android:configChanges="orientation|screenLayout|screenSize"
即可为您完成工作。
示例:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize" />
如果横向模式的布局不同,则需要覆盖savedInstanceState
并在OnCreate