0

I am building an app that displays details of a book you have searched. The problem is that every time I change the orientation of my device the list view elements disappear. I want help in how to make them not disappear. I have a feeling that I need to use a Loader but I have no idea in how to implement it. Here are my activities.

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;
    }
}

2 Answers2

0

You need to override onSaveInstanceState and onRestoreInstanceState methods of Activity Class.

In onSaveInstanceState, save the list data into the Bundle.

In onRestoreInstanceState, restore the list with the Bundle data and re-create the list adapter.

Cheers!!!

Amit Goyal
  • 56
  • 2
0

if you do not have a different layout for the activity landscape mode then simply putting android:configChanges="orientation|screenLayout|screenSize" will do the job for you.

Example:

 <activity
        android:name=".MainActivity"
        android:configChanges="orientation|screenLayout|screenSize" />

and if you do have different layout for landscape mode the you need to override the savedInstanceState and save and restore the list accordingly in OnCreate

Atiq
  • 14,435
  • 6
  • 54
  • 69