1

Hello how are you? I'm creating an android app news and is working very well, the only problem is when I'm doing the reading of the text and minimize the app to do something else and then return the app presents this error.

03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: FATAL EXCEPTION: main
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at java.util.ArrayList.get(ArrayList.java:304)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at com.brfgd.ActivityDetailStory.setAdapterToListview(ActivityDetailStory.java:179)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:171)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:119)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at android.os.AsyncTask.finish(AsyncTask.java:631)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:153)

part of the error

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ActivityDetailStory extends AppCompatActivity {

    int position;
    String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
    TextView news_title, news_date;
    WebView news_desc;
    ImageView img_news, img_fav;
    DatabaseHandler db;
    List<ItemStoryList> arrayOfRingcatItem;
    ItemStoryList objAllBean;
    final Context context = this;
    ProgressBar progressBar;
    LinearLayout content;
    private AdView mAdView;
    private InterstitialAd interstitial;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_detail_story);

        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
        }

        //show admob banner ad
        mAdView = (AdView) findViewById(R.id.adView);
        mAdView.loadAd(new AdRequest.Builder().build());
        mAdView.setAdListener(new AdListener() {

            @Override
            public void onAdClosed() {
            }

            @Override
            public void onAdFailedToLoad(int error) {
                mAdView.setVisibility(View.GONE);
            }

            @Override
            public void onAdLeftApplication() {
            }

            @Override
            public void onAdOpened() {
            }

            @Override
            public void onAdLoaded() {
                mAdView.setVisibility(View.VISIBLE);
            }
        });

        content = (LinearLayout) findViewById(R.id.content);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
        img_news = (ImageView) findViewById(R.id.image);

        news_title = (TextView) findViewById(R.id.title);
        news_date = (TextView) findViewById(R.id.subtitle);
        news_desc = (WebView) findViewById(R.id.desc);

        db = new DatabaseHandler(ActivityDetailStory.this);

        arrayOfRingcatItem = new ArrayList<ItemStoryList>();
        //imageLoader = new ImageLoader(ActivityDetailStory.this);

        if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
            new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
            MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
        }

        else {
            Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
        }

    }

    private class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            return JsonUtils.getJSONString(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            progressBar.setVisibility(View.GONE);
            content.setVisibility(View.VISIBLE);

            if (null == result || result.length() == 0) {
                Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();

            } else {

                try {
                    JSONObject mainJson = new JSONObject(result);
                    JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
                    JSONObject objJson = null;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        objJson = jsonArray.getJSONObject(i);

                        ItemStoryList objItem = new ItemStoryList();

                        objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
                        objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
                        objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
                        objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
                        objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
                        objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
                        objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
                        objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));

                        arrayOfRingcatItem.add(objItem);

                    }

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

                setAdapterToListview();
            }

        }
    }


    public void setAdapterToListview() {
        //if(arrayOfRingcatItem.size()>0) {
            objAllBean = arrayOfRingcatItem.get(0);
            str_cid = objAllBean.getCId();
            str_cat_name = objAllBean.getCategoryName();
            str_cat_image = objAllBean.getCategoryImage();
            str_cat_id = objAllBean.getCatId();
            str_title = objAllBean.getNewsHeading();
            str_desc = objAllBean.getNewsDescription();
            str_image = objAllBean.getNewsImage();
            str_date = objAllBean.getNewsDate();

            news_title.setText(str_title);
            news_date.setText(str_date);

            news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
            news_desc.setFocusableInTouchMode(false);
            news_desc.setFocusable(false);
            news_desc.getSettings().setDefaultTextEncodingName("UTF-8");

            WebSettings webSettings = news_desc.getSettings();
            Resources res = getResources();
            int fontSize = res.getInteger(R.integer.font_size);
            webSettings.setDefaultFontSize(fontSize);

            String mimeType = "text/html; charset=UTF-8";
            String encoding = "utf-8";
            String htmlText = str_desc;

            String text = "<html><head><style type=\"text/css\">@font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
                    + htmlText + "</body></html>";

            news_desc.loadData(text, mimeType, encoding);

            List<Pojo> pojolist = db.getFavRow(str_cat_id);
            if (pojolist.size() == 0) {
                img_fav.setImageResource(R.drawable.ic_bookmark_outline);
            } else {
                if (pojolist.get(0).getCatId().equals(str_cat_id))
                    ;
                {
                    img_fav.setImageResource(R.drawable.ic_bookmark_white);
                }

            }

            img_fav.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    List<Pojo> pojolist = db.getFavRow(str_cat_id);
                    if (pojolist.size() == 0) {

                        db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
                        Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
                        img_fav.setImageResource(R.drawable.ic_bookmark_white);

                        interstitial = new InterstitialAd(ActivityDetailStory.this);
                        interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
                        AdRequest adRequest = new AdRequest.Builder().build();
                        interstitial.loadAd(adRequest);
                        interstitial.setAdListener(new AdListener() {
                            public void onAdLoaded() {
                                if (interstitial.isLoaded()) {
                                    interstitial.show();
                                }
                            }
                        });
                    } else {
                        if (pojolist.get(0).getCatId().equals(str_cat_id)) {

                            db.RemoveFav(new Pojo(str_cat_id));
                            Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
                            img_fav.setImageResource(R.drawable.ic_bookmark_outline);
                        }
                    }
                }
            });

        //}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_story, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

            case R.id.menu_share:
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
                break;

            default:
                return super.onOptionsItemSelected(menuItem);
        }
        return true;
    }



    @Override
    protected void onPause() {
       // mAdView.pause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //mAdView.resume();
    }

    @Override
    protected void onDestroy() {
        //mAdView.destroy();
        super.onDestroy();
    }
}
  • Your `arrayOfRingcatItem` list is empty and yet you still try to get the first element. This cannot work – Anton Sarov Mar 21 '16 at 20:15
  • It seems like you have not initialized `arrayOfRingcatItem` and thus `arrayOfRingcatItem.get(0);` is through `IndexOutOfBounds` Exception. – user2004685 Mar 21 '16 at 20:16

2 Answers2

0

You should do this:

 public void setAdapterToListview() {
        if(arrayOfRingcatItem.size>0){
        objAllBean = arrayOfRingcatItem.get(0);
        str_cid = objAllBean.getCId();
        str_cat_name = objAllBean.getCategoryName();
        }
     }

EDIT: onResume()

@Override
protected void onResume(){
super.onResume();
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
    //imageLoader = new ImageLoader(ActivityDetailStory.this);

    if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
        new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
        MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
    }

    else {
        Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
    }
}

Or you can save the array in the Application class and use it from there, or in a singleton. The error it's because when the activity go to background Android can release some memory and delete your array.

EDIT 2: You can use SharedPreferences to save the id.
You have to put this code in onCreate:

SharedPreferences opc=getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor =opc.edit();
editor.putInt("ID_SAVED",NEWS_ITEMID); editor.commit(); 

And in the onResume:

SharedPreferences opc=getSharedPreferences("AppName", 0);
NEWS_ITEMID=opc.getInt("ID_SAVED", -1);
DonLeopardo
  • 140
  • 6
  • Now the app hasn't stopped, more all fields returned NULL – jeffersondp Mar 21 '16 at 20:39
  • That's because the list is empty, are you sure it's not? – DonLeopardo Mar 21 '16 at 21:58
  • She is NULL, was to resume where I left off. – jeffersondp Mar 21 '16 at 22:06
  • Oh, i read now, the problem is that you shuld recall the method that populate the array in the onResume() or save the array somewhere. I will update my answer. – DonLeopardo Mar 21 '16 at 22:07
  • I don't understand! where would that onResume, see my code up there and show me more or less as would be pf! never used onResume in my apps – jeffersondp Mar 21 '16 at 22:35
  • http://developer.android.com/intl/es/reference/android/app/Activity.html You can see there the graphic of an activity life cycle and exactly when each method is called. The onResume method is an activity innerith method and you should override it in your activity to put that code, and it is going to be executed when the activity come up from the background. In the onResume you should call the AsyncTask and maybe the problem will be solved. You have the onResume in your code, you should add the AsyncTask execute in there. – DonLeopardo Mar 21 '16 at 23:23
  • OK, so indicate can where I can start on my code. Thank you 'cause I don't know use pretty much the same. – jeffersondp Mar 21 '16 at 23:42
  • I edited my answer to be more clear. You should copy the code and paste it in your activity, maybe it will have some errors, but you should be ok, they should be easy little errors i guess. – DonLeopardo Mar 22 '16 at 00:00
  • didn't work no.. What do I need to save is the ID. being passed in `Constant NEWS_ITEMID` I did a test, statically and it worked. – jeffersondp Mar 22 '16 at 01:22
  • No! I did the statically test I added the ID manually and I resumed the app and it worked, the problem is how do you keep this ID 21 `new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=21"); ` This ID comes from another activity – jeffersondp Mar 22 '16 at 11:02
  • You can use the SharedPreferences, onCreate you have to put this code: `SharedPreferences opc=getSharedPreferences("AppName", 0); SharedPreferences.Editor editor =opc.edit(); editor.putInt("ID_SAVED",NEWS_ITEMID); editor.commit();` And in the onResume: `SharedPreferences opc=getSharedPreferences("AppName", 0); NEWS_ITEMID=opc.getInt("ID_SAVED", -1);` – DonLeopardo Mar 22 '16 at 11:23
  • how I would use in my code? edit your reply is confusing, Thank you for helping me! – jeffersondp Mar 22 '16 at 11:58
  • It's already updating, i post the comment and edit the answer at the same time :P – DonLeopardo Mar 22 '16 at 12:04
  • I don't know where to put this. Thank you. :( – jeffersondp Mar 22 '16 at 12:34
  • I can spend all my app for you via GIT for you run in your environment and see if it helps me – jeffersondp Mar 22 '16 at 12:37
  • I don't know how to use git, and i don't familiarise with android studio. I'm using Android Studio, but i only have on proyect at the time and never open two together... I can copy paste all your code edited if you want, but it may take a little. – DonLeopardo Mar 22 '16 at 12:43
  • give me your Skype send to folder – jeffersondp Mar 22 '16 at 12:45
0

Based on what you stated above everything is working fine except:

minimize the app to do something else and then return the app presents this error

You may need to reinitialize code in:

  @Override
    public void onResume(){
        super.onResume();
        // put your code here to repopulate arraylist...
        refreshMyData();
    }

refreshMyData could have:

  public void refreshMyData(){
        if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
            new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
            MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
        }else {
            Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
        }
}

Use this method in your oncreate as well, that way you can have the same method call when creating the activity and resuming.

Sources:

Community
  • 1
  • 1
Petro
  • 3,484
  • 3
  • 32
  • 59