2016-10-15 4 views
0

검색 한 책의 세부 정보를 표시하는 앱을 제작 중입니다. 문제는 장치의 방향을 변경할 때마다 목록보기 요소가 사라집니다. 나는 그들을 사라지지 않게 만드는 방법에 도움을 원합니다. 로더를 사용해야한다는 생각이 들지만 구현 방법은 모른다. 여기에 내 활동이있다.장치의 방향을 변경할 때 목록 뷰 요소가 사라지지 않도록하려면 어떻게해야합니까?

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 : -

당신은 onSaveInstanceState 및 활동 클래스의 onRestoreInstanceState 메소드를 오버라이드 (override) 할 필요가
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

OnCreate에 따라 목록을 복원 할 필요가 참조 가로 모드에 대한 다른 레이아웃이있는 경우 http://stackoverflow.com/questions/12176179/android-listview- 화면 회전 후 사라짐 – sasikumar

답변

0

.

onSaveInstanceState에서 목록 데이터를 번들에 저장하십시오.

onRestoreInstanceState에서 번들 데이터로 목록을 복원하고 목록 어댑터를 다시 만듭니다.

건배 !!!

0

활동 가로 모드와 다른 레이아웃이 없다면 단순히 android:configChanges="orientation|screenLayout|screenSize"을 입력하면됩니다.

예 :

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

당신은 당신이 savedInstanceState을 무시하고 저장하고

관련 문제