-2

I have a fragment called PopularFragment.java in that i am fetching images from server and then displaying them into recyclerview. Usually it works great but sometimes the app crashes with a NullPointerException.

PopularFragment:

package com.apphics.minimalwallpapers;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.adapter.AdapterImage;
import com.example.item.ItemPhotos;
import com.example.util.Constant;
import com.example.util.DBHelper;
import com.example.util.EndlessRecyclerViewScrollListener;
import com.example.util.JsonUtils;
import com.pnikosis.materialishprogress.ProgressWheel;

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

import java.lang.ref.WeakReference;
import java.util.ArrayList;


public class PopularFragment extends Fragment {

    DBHelper dbHelper;
    GridLayoutManager lLayout;
    RecyclerView recyclerView;
    AdapterImage adapterImage;
    ArrayList<ItemPhotos> arrayOfLatestImage;
    SwipeRefreshLayout mSwipeRefreshLayout;
    ProgressWheel pbar;
    TextView txt_no;
    int spaceInPixels = 10;
    Boolean isOver = false;

    public PopularFragment newInstance() {
        PopularFragment fragment = new PopularFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
        pbar=(ProgressWheel) rootView.findViewById(R.id.progressBar1);

        mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);

        dbHelper = new DBHelper(getActivity().getApplicationContext());

        arrayOfLatestImage=new ArrayList<ItemPhotos>();

        lLayout = new GridLayoutManager(getActivity(), 2);
        lLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapterImage.isHeader(position) ? lLayout.getSpanCount() : 1;
            }
        });


        recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_latest);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(lLayout);





        recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(lLayout) {
            @Override
            public void onLoadMore(int p, int totalItemsCount) {
                arrayOfLatestImage.add(null);
                adapterImage.notifyItemInserted(arrayOfLatestImage.size() - 1);
                arrayOfLatestImage.remove(arrayOfLatestImage.size() - 1);
                adapterImage.notifyItemRemoved(arrayOfLatestImage.size());
                if(!isOver) {
                    //                    list_url.clear();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            new MyTask(getActivity().getApplicationContext()).execute(Constant.POPULAR_URL);
                        }
                    }, 2000);
                } else {
                    adapterImage.hideHeader();
                    //Toast.makeText(getActivity(), "No more data", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshContent();
            }
        });


        if (JsonUtils.isNetworkAvailable(getActivity())) {
            new MyTask(getActivity().getApplicationContext()).execute(Constant.POPULAR_URL);
        } else {
            arrayOfLatestImage = dbHelper.getAllDataPopular("popular");
            if(arrayOfLatestImage.size()==0) {
                Toast.makeText(getActivity(), "Please connect to internet to load Images ", Toast.LENGTH_SHORT).show();
                pbar.setVisibility(View.GONE);
            } else {
                adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
                recyclerView.setAdapter(adapterImage);
                pbar.setVisibility(View.GONE);
            }
        }
        return rootView;
    }

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

        private final WeakReference<Context> contextReference;

        public MyTask(Context context) {

            this.contextReference = new WeakReference<Context>(context);
        }

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

            Context context = this.contextReference.get();
            if(context != null) {

                if (arrayOfLatestImage.size() == 0) {
                    pbar.setVisibility(View.VISIBLE);
                }
            }
        }

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

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

            Context context = this.contextReference.get();
            if(context != null) {

                if (arrayOfLatestImage.size() == 0) {
                    pbar.setVisibility(View.INVISIBLE);
                }

                if (null == result || result.length() == 0) {
                    Toast.makeText(getActivity(), "Something Went Wrong! Please check your internet and reload", Toast.LENGTH_SHORT).show();

                } else {

                    try {
                        JSONObject mainJson = new JSONObject(result);
                        JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);

                        if (jsonArray.length() <= arrayOfLatestImage.size() + 40) {
                            isOver = true;
                        }

                        int a = arrayOfLatestImage.size();
                        int b;
                        b = 40;

                        JSONObject objJson = null;
                        for (int i = a; i < a + b; i++) {
                            objJson = jsonArray.getJSONObject(i);

                            String id = objJson.getString(Constant.TAG_WALL_ID);
                            String cid = objJson.getString(Constant.TAG_CAT_ID);
                            String img = objJson.getString(Constant.TAG_WALL_IMAGE);
                            String img_thumb = objJson.getString(Constant.TAG_WALL_IMAGE_THUMB);
                            String cat_name = objJson.getString(Constant.TAG_CAT_NAME);
                            String views = objJson.getString(Constant.TAG_WALL_VIEWS);

                            ItemPhotos objItem = new ItemPhotos(id, cid, img, img_thumb, cat_name, views);

                            dbHelper.addtoFavorite(objItem, "popular");
                            arrayOfLatestImage.add(objItem);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        isOver = true;
                    }
                    setAdapterToListview();
                }
            }

        }
    }

    public void setAdapterToListview() {
        if(arrayOfLatestImage.size()<41) {
            adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
            recyclerView.setAdapter(adapterImage);
        } else {
            adapterImage.notifyDataSetChanged();
        }

        //setExmptTextView();
    }

    /*private void setExmptTextView() {
        if(adapterImage.getItemCount()==0) {
            txt_no.setVisibility(View.VISIBLE);
        } else{
            txt_no.setVisibility(View.INVISIBLE);
        }
    }*/

    public void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onResume() {
        //if(adapterImage!=null && adapterImage.getItemCount() > 0) {
        // adapterImage.notifyDataSetChanged();
        //setExmptTextView();
        // }
        super.onResume();
    }

    private void refreshContent() {
        // TODO implement a refresh

        recyclerView.getRecycledViewPool().clear();
        adapterImage.notifyDataSetChanged();

        arrayOfLatestImage.clear();
        try{
            if (JsonUtils.isNetworkAvailable(getActivity())) {
                new MyTask(getActivity()).execute(Constant.POPULAR_URL);

            } else {
                arrayOfLatestImage = dbHelper.getAllDataPopular("popular");
                if(arrayOfLatestImage.size()==0) {
                    Toast.makeText(getActivity(), "First Time Load Application from Internet ", Toast.LENGTH_SHORT).show();
                } else {
                    adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
                    recyclerView.setAdapter(adapterImage);
                }
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }



        mSwipeRefreshLayout.setRefreshing(false); // Disables the refresh icon
    }
}

DBHelper.java:

package com.example.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.item.ItemAbout;
import com.example.item.ItemCategory;
import com.example.item.ItemGIF;
import com.example.item.ItemPhotos;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class DBHelper extends SQLiteOpenHelper {

    private static String DB_NAME = "wallpaper.db";
    private SQLiteDatabase db;
    private final Context context;
    private String DB_PATH;
    String outFileName = "";
    SharedPreferences.Editor spEdit;

    public DBHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
        DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
    }


    public void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();
        //------------------------------------------------------------
        PackageInfo pinfo = null;
        if (!dbExist) {
            getReadableDatabase();
            copyDataBase();
        }

    }

    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    private void copyDataBase() throws IOException {

        InputStream myInput = context.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public Cursor getData(String Query) {
        String myPath = DB_PATH + DB_NAME;
        Cursor c = null;

        try {
            File file = new File(myPath);
            if (file.exists() && !file.isDirectory())
                db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
                c = db.rawQuery(Query, null);

        } catch (Exception e) {
            Log.e("Err", e.toString());
        }

        return c;
    }

    //UPDATE temp_dquot SET age='20',name1='--',rdt='11/08/2014',basic_sa='100000',plno='814',pterm='20',mterm='20',mat_date='11/08/2034',mode='YLY',dab_sa='100000',tr_sa='0',cir_sa='',bonus_rate='42',prem='5276',basic_prem='5118',dab_prem='100.0',step_rate='for Life',loyal_rate='0',bonus_rate='42',act_mat='1,88,000',mly_b_pr='448',qly_b_pr='1345',hly_b_pr='2664',yly_b_pr='5276'  WHERE uniqid=1
    public void dml(String Query) {
        String myPath = DB_PATH + DB_NAME;
        File file = new File(myPath);
        if (file.exists() && !file.isDirectory())
        if (db == null)
            db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        try {
            db.execSQL(Query);
        } catch (Exception e) {
            Log.e("Error", e.toString());
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }

    public ArrayList<ItemPhotos> getAllData(String table){
        ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();

        Cursor cursor = getData("select * from '"+table+"'");
        if(cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String pid = cursor.getString(cursor.getColumnIndex("pid"));
                String cid = cursor.getString(cursor.getColumnIndex("cid"));
                String cname = cursor.getString(cursor.getColumnIndex("cname"));
                String img = cursor.getString(cursor.getColumnIndex("img"));
                String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
                arrayList.add(itemPhotos);

                cursor.moveToNext();
            }
            cursor.close();
        }

        return arrayList;
    }

    public ArrayList<ItemPhotos> getAllDataPopular(String table){
        ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();

        Cursor cursor = getData("select * from '"+table+"'");
        if(cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String pid = cursor.getString(cursor.getColumnIndex("pid"));
                String cid = cursor.getString(cursor.getColumnIndex("cid"));
                String cname = cursor.getString(cursor.getColumnIndex("cname"));
                String img = cursor.getString(cursor.getColumnIndex("img"));
                String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
                arrayList.add(itemPhotos);

                cursor.moveToNext();
            }
            cursor.close();
        }

        return arrayList;
    }

    public ArrayList<ItemPhotos> getAllDataShuffl(String table){
        ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();

        Cursor cursor = getData("select * from '"+table+"'");
        if(cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String pid = cursor.getString(cursor.getColumnIndex("pid"));
                String cid = cursor.getString(cursor.getColumnIndex("cid"));
                String cname = cursor.getString(cursor.getColumnIndex("cname"));
                String img = cursor.getString(cursor.getColumnIndex("img"));
                String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
                arrayList.add(itemPhotos);

                cursor.moveToNext();
            }
            cursor.close();
        }

        return arrayList;
    }


    public ArrayList<ItemGIF> getAllDataGIF(){
        ArrayList<ItemGIF> arrayList = new ArrayList<ItemGIF>();

        Cursor cursor = getData("select * from gif");
        if(cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String gid = cursor.getString(cursor.getColumnIndex("gid"));
                String img = cursor.getString(cursor.getColumnIndex("image"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemGIF itemGIF = new ItemGIF(gid,img,views);
                arrayList.add(itemGIF);

                cursor.moveToNext();
            }
            cursor.close();
        }

        return arrayList;
    }

    public ArrayList<ItemCategory> getAllDataCat(String table){
        ArrayList<ItemCategory> arrayList = new ArrayList<ItemCategory>();

        Cursor cursor = getData("select * from '"+table+"'");
        if(cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String cid = cursor.getString(cursor.getColumnIndex("cid"));
                String cname = cursor.getString(cursor.getColumnIndex("cname"));
                String img = cursor.getString(cursor.getColumnIndex("img"));
                String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
                String tot_wall = cursor.getString(cursor.getColumnIndex("tot_wall"));

                ItemCategory itemCategory = new ItemCategory(cid,cname,img,img_thumb,tot_wall);
                arrayList.add(itemCategory);

                cursor.moveToNext();
            }
            cursor.close();
        }

        return arrayList;
    }

    public ArrayList<ItemPhotos> getFavRow(String id, String table)
    {
        ArrayList<ItemPhotos> dataList = new ArrayList<ItemPhotos>();
        // Select All Query
        String selectQuery = "SELECT  * FROM '"+table+"' WHERE pid="+"'"+id+"'";

        Cursor cursor = getData(selectQuery);

        if (cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String pid = cursor.getString(cursor.getColumnIndex("pid"));
                String cid = cursor.getString(cursor.getColumnIndex("cid"));
                String cname = cursor.getString(cursor.getColumnIndex("cname"));
                String img = cursor.getString(cursor.getColumnIndex("img"));
                String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
                dataList.add(itemPhotos);

                cursor.moveToNext();
            }
            cursor.close();
        }

        // return contact list
        return dataList;
    }

    public ArrayList<ItemGIF> getFavRowGIF(String id)
    {
        ArrayList<ItemGIF> dataList = new ArrayList<ItemGIF>();
        // Select All Query
        String selectQuery = "SELECT * FROM gif WHERE gid="+"'"+id+"'";

        Cursor cursor = getData(selectQuery);

        if (cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String gid = cursor.getString(cursor.getColumnIndex("gid"));
                String img = cursor.getString(cursor.getColumnIndex("image"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemGIF itemGIF = new ItemGIF(gid,img,views);
                dataList.add(itemGIF);

                cursor.moveToNext();
            }
            cursor.close();
        }

        // return contact list
        return dataList;
    }

    public ArrayList<ItemPhotos> getCatList(String id, String table)
    {
        ArrayList<ItemPhotos> dataList = new ArrayList<ItemPhotos>();
        // Select All Query
        String selectQuery = "SELECT  * FROM '"+table+"' WHERE cid="+"'"+id+"'";

        Cursor cursor = getData(selectQuery);

        if (cursor != null && cursor.getCount()>0) {
            cursor.moveToFirst();
            for (int i=0; i<cursor.getCount(); i++) {
                String pid = cursor.getString(cursor.getColumnIndex("pid"));
                String cid = cursor.getString(cursor.getColumnIndex("cid"));
                String cname = cursor.getString(cursor.getColumnIndex("cname"));
                String img = cursor.getString(cursor.getColumnIndex("img"));
                String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
                String views = cursor.getString(cursor.getColumnIndex("views"));

                ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
                dataList.add(itemPhotos);

                cursor.moveToNext();
            }
            cursor.close();
        }

        // return contact list
        return dataList;
    }

    public void addtoFavorite(ItemPhotos itemPhotos, String table) {
        dml("insert into '"+table+"' (pid,cid,cname,img,img_thumb,views) values ('"+itemPhotos.getId()+"','"+itemPhotos.getCatId()+"','"+itemPhotos.getCName()+"','"+itemPhotos.getImage()+"','"+itemPhotos.getImageThumb()+"','"+itemPhotos.getTotalViews()+"')");
    }

    public void addtoFavoriteGIF(ItemGIF itemGIF) {
        dml("insert into gif (gid,image,views) values ('"+itemGIF.getId()+"','"+itemGIF.getImage()+"','"+itemGIF.getTotalViews()+"')");
    }

    public void addtoCatList(ItemCategory itemCategory, String table) {
        dml("insert into '"+table+"' (cid,cname,img,img_thumb,tot_wall) values ('"+itemCategory.getId()+"','"+itemCategory.getName()+"','"+itemCategory.getImage()+"','"+itemCategory.getImageThumb()+"','"+itemCategory.getTotalWallpaper()+"')");
    }

    public void removeFav(String id) {
        dml("delete from fav where pid = '"+id+"'");
    }

    public void removeFavGIF(String id) {
        dml("delete from gif where gid = '"+id+"'");
    }

    public void updateView(String id, String totview) {
        int views = Integer.parseInt(totview) + 1;
        dml("update catlist set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
        dml("update fav set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
        dml("update latest set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
        dml("update shuffl set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
    }

    public void updateViewGIF(String id, String totview) {
        int views = Integer.parseInt(totview) + 1;
        dml("update gif set views = '"+String.valueOf(views)+"' where gid = '"+id+"'");
    }

    public void addtoAbout() {
        dml("delete from about");
        dml("insert into about (name,logo,version,author,contact,email,website,desc,developed,privacy) values (" +
            "'"+ Constant.itemAbout.getAppName()+"','"+ Constant.itemAbout.getAppLogo()+"','"+ Constant.itemAbout.getAppVersion()+"'" +
            ",'"+ Constant.itemAbout.getAuthor()+"','"+ Constant.itemAbout.getContact()+"','"+ Constant.itemAbout.getEmail()+"'" +
            ",'"+ Constant.itemAbout.getWebsite()+"','"+ Constant.itemAbout.getAppDesc()+"','"+ Constant.itemAbout.getDevelopedby()+"'" +
            ",'"+ Constant.itemAbout.getPrivacy()+"')");
    }

    public Boolean getAbout() {
        String selectQuery = "SELECT * FROM about";

        Cursor c = getData(selectQuery);

        if (c != null && c.getCount()>0) {
            c.moveToFirst();
            for (int i=0; i<c.getCount(); i++) {
                String appname = c.getString(c.getColumnIndex("name"));
                String applogo = c.getString(c.getColumnIndex("logo"));
                String desc = c.getString(c.getColumnIndex("desc"));
                String appversion = c.getString(c.getColumnIndex("version"));
                String appauthor = c.getString(c.getColumnIndex("author"));
                String appcontact = c.getString(c.getColumnIndex("contact"));
                String email = c.getString(c.getColumnIndex("email"));
                String website = c.getString(c.getColumnIndex("website"));
                String privacy = c.getString(c.getColumnIndex("privacy"));
                String developedby = c.getString(c.getColumnIndex("developed"));

                Constant.itemAbout = new ItemAbout(appname,applogo,desc,appversion,appauthor,appcontact,email,website,privacy,developedby);
            }
            c.close();
            return true;
        } else {
            return false;
        }
    }
}  

This is the logcat:

java.lang.NullPointerException: 
  at com.example.util.DBHelper.<init>(DBHelper.java:35)
  at com.example.adapter.AdapterImage.<init>(AdapterImage.java:69)
  at com.apphics.minimalwallpapers.PopularFragment.setAdapterToListview(PopularFragment.java:226)
  at com.apphics.minimalwallpapers.PopularFragment$MyTask.onPostExecute(PopularFragment.java:217)
  at com.apphics.minimalwallpapers.PopularFragment$MyTask.onPostExecute(PopularFragment.java:141)
  at android.os.AsyncTask.finish(AsyncTask.java:651)
  at android.os.AsyncTask.access$500(AsyncTask.java:180)
  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5438)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • An Activity is a Context, stopping using `getActivity().getApplicationContext()` and just use `getActivity()` – OneCricketeer May 27 '17 at 16:25
  • The problem here is that `getActivity()` returns null before the framework calls `onActivityCreated()`. The method `onCreateView` is called before that. So you need to move the initialization of DBHelper dbHelper = new DBHelper(getActivity().getApplicationContext()); to `onActivityCreated()`. – Henry May 27 '17 at 16:27
  • 1
    @Rotwang I think this is one of the rare NPEs that are not a duplicate. – Henry May 27 '17 at 16:28
  • Yeah. I agree with @Henry – Bertram Gilfoyle May 27 '17 at 16:30
  • Thanx all for the solution. Though i rarely get this exception so i can't test it. but i am doing everything that @henry and cricket_007 said. Hoping to get no more exceptions. :) – Nikhil Singh May 27 '17 at 20:00
  • @henry i don'nt have onActivityCreated() part in my fragment. should i add it there with the dbhelper initialization?? – Nikhil Singh May 27 '17 at 20:14
  • yes, or you could use any other life cycle method that is called later. – Henry May 28 '17 at 05:02
  • @henry. tried your solution but still getting force closes with same logcat :( – Nikhil Singh May 30 '17 at 10:02
  • Your `WeakReference contextReference` will only be useful if you make your `MyTask` class static. And when does the crash occur? When you minimize the app? – Sufian Jun 04 '17 at 07:27
  • @Sufian app crashes randomly at loading time or at app startup. These crashes does not occur all the time but its stil ocurring. Please help me resolve this..:/ – Nikhil Singh Jun 04 '17 at 14:07
  • 1. you should move `dbHelper = new DBHelper(getActivity().getApplicationContext());` into `onActivityCreated()` method of the Fragment (override one if you haven't yet). 2. and it seems that you're doing `new DBHelper()` in the constructor of your `AdapterImage`. Don't do that, instead pass `dbHelper` from your Fragment. – Sufian Jun 05 '17 at 03:58

1 Answers1

0

The exception is thrown when arrayOfLatestImage.size() is greater than or equal to 41. Initialize adapterImage in the else block in the setAdapterToListview() function. Hope it helps.

Bertram Gilfoyle
  • 9,899
  • 6
  • 42
  • 67
  • hey @Ahamad Anees, Should i just initialize the adapterimage in else part or should i also add recyclerView.setAdapter(adapterImage); after that?? – Nikhil Singh May 27 '17 at 20:02
  • You should keep setAdapter(). Or simply move the initialisation to the line before the if block before the if block – Bertram Gilfoyle May 27 '17 at 20:07
  • Thanx a lot. I have added : adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage); recyclerView.setAdapter(adapterImage); adapterImage.notifyDataSetChanged(); to my else part. hope it helps to resolve this exception..:) – Nikhil Singh May 27 '17 at 20:10
  • i tried adding this code but everytime no of images exceed 41 instead of just adding more images it refreshes the whole recyclerview..i am adding more images on recycler view scrolling so this will not work for me..any other solution? – Nikhil Singh May 27 '17 at 20:40