简体   繁体   中英

RecyclerView Activity getting killed after Returning

I have put an recyclerview which shows some cards which contains text and image. The cards are clickable and direct the user to another activity to see the card contents. But when the user goes back to search activity, the recyclerview removes the items. It shows No item found, since I have put the text No item found if Async task return result is invalid.

Thanks in advance.

I have included the code below:

 @Override
public void onRestart() {
    super.onRestart();
    if(!cd.isConnectingToInternet()){
        alert.showAlertDialog(pgrentertabsearch.this,
                "No Internet Connection",
                "Please connect to Internet", false);
        // stop executing code by return
        return;

    }
    else {

        search(areavalue, pricevalue, numberofbedsvalue);
    }


}












private void search(final String searcharea, final String searchprice, final String searchnumberofbeds) {


    class PGAsync extends AsyncTask<String, Void, String> {

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            spinner.setVisibility(View.VISIBLE);
            loading.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            String searcharea = params[0];
            String searchprice = params[1];
            String searchnumberofbeds = params[2];

            InputStream is = null;
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("searcharea", searcharea));
            nameValuePairs.add(new BasicNameValuePair("searchprice", searchprice));
            nameValuePairs.add(new BasicNameValuePair("searchnumberofbeds", searchnumberofbeds));
            String result = null;

            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(
                        "http://xxx.php");
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpClient.execute(httpPost);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            String s = jsonresult.trim();
    spinner.setVisibility(View.GONE);
                loading.setVisibility(View.GONE);
            if (!s.equalsIgnoreCase("invalid")) {
                found.setVisibility(View.VISIBLE);
                myJSON = result;
                showList();


            } else {
                pgnotfound.setVisibility(View.VISIBLE);
                pgnotfound1.setVisibility(View.VISIBLE);
                pgnotfoundimage.setVisibility(View.VISIBLE);


            }

        }
    }

    PGAsync g = new PGAsync();
    g.execute(searcharea, searchprice, searchnumberofbeds);


}


protected void showList() {


    try {
        JSONObject jsonObj = new JSONObject(myJSON);

        pgarray = jsonObj.getJSONArray(TAG_RESULTS);
        for(int i=0;i<pgarray.length();i++){
            JSONObject c = pgarray.getJSONObject(i);
            PGCardItemReturn pgcarditemreturn = new PGCardItemReturn();
            pgcarditemreturn.setId(c.getString(TAG_ID));



            pgcarditemreturn.setFurnishing(c.getString(TAG_FURNISHING));


            pgcarditemreturn.setArea(c.getString(TAG_AREA));

            pgcarditemreturn.setPrice(c.getString(TAG_PRICE));

            pgcarditemreturn.setNumberofbeds(c.getString(TAG_NUMBEROFBEDS));


            pgcarditemreturn.setImageUrl(c.getString(TAG_IMAGE_URL));


            listPG.add(pgcarditemreturn);



        }


    } catch (JSONException e) {
        e.printStackTrace();

    }
    adapter = new PGSearchCardAdapter(listPG, this);

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);


}

In oncreate method:

if(!cd.isConnectingToInternet()){
        alert.showAlertDialog(pgrentertabsearch.this,
                "No Internet Connection",
                "Please connect to Internet", false);
        // stop executing code by return
        return;

    }
    else {

        search(areavalue, pricevalue, numberofbedsvalue);
    }

Her's the logcat:

11-28 15:56:06.377 1894-2620/eya.eya D/skia: --- SkImageDecoder::Factory returned null
11-28 15:56:07.552 1894-2619/eya.eya D/skia: --- SkImageDecoder::Factory returned null
11-28 15:56:07.843 1894-2620/eya.eya D/skia: --- SkImageDecoder::Factory returned null
11-28 15:56:08.858 1894-1936/eya.eya W/EGL_emulation: eglSurfaceAttrib not implemented
11-28 15:56:08.858 1894-1936/eya.eya W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa3bb8020, error=EGL_SUCCESS
11-28 15:56:08.886 1894-1894/eya.eya E/RecyclerView: No adapter attached; skipping layout
11-28 15:56:08.898 1894-1894/eya.eya E/RecyclerView: No adapter attached; skipping layout
11-28 15:56:09.023 1894-1936/eya.eya D/OpenGLRenderer: endAllStagingAnimators on 0xa4349f00 (RippleDrawable) with handle 0xa3bffb50
11-28 15:56:09.233 1894-1894/eya.eya E/RecyclerView: No adapter attached; skipping layout
11-28 15:57:57.915 1894-1901/eya.eya W/art: Suspending all threads took: 5.356ms
11-28 16:02:08.480 1894-1901/eya.eya W/art: Suspending all threads took: 5.204ms
11-28 16:02:38.129 1894-1901/eya.eya W/art: Suspending all threads took: 5.316ms

if my undestanding is correct, there is two Activities :

Activity A -> RecyclerView displaying search results

Activity B -> Detail for each recyclerview items


When you back to Activity A, from Activity B, your activity B has been destroyed.

So, you need to override onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) in the Activity A, with the aim of retrieving your list of data.

Exemple :

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(outState);
savedInstanceState.putParcelable("key", myObject);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Object myObject = savedInstanceState.getParcelable("key"); 
}

Be Careful, your object class must to implement Parcelable.

You can see the documentation : http://developer.android.com/reference/android/os/Parcelable.html

There is a typical implementation of Parcelable, when you clic on "Class Overview".

And there is a tool for auto implementing Parcelable :

http://dallasgutauckis.com/2012/01/20/parcelabler-for-implementing-androids-parcelable-interface/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM