0

It runs fine if i don't use AsyncTask. Iam doing this because its data fetching operation from server and writing in sqlite database. Iam calling this on first fragment of tab layout.

this is the first fragment

public class TabFragment7 extends Fragment {
 @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        registerInBackground1();  // this method 
    } 

}

registerInBackground1(); method

 private void registerInBackground1() {

        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";




                TabFragment0 tab1= new TabFragment0();
                try {
                    tab1.getRSSfeedstoSqLite();  //this methods fetches data 
                                 from server and writes it in sqlite database
                } catch (RSSReaderException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {

                runOnUiThread(new Runnable() {
                    public void run() {


                    }

                });




            }
        }.execute(null, null, null);
    }

getRSSfeedstoSqLite() In this method create a sqlite data base and store it. if you guys know better way to do this please suggest me.

 public void getRSSfeedstoSqLite() throws RSSReaderException, IOException {

              SQLiteDatabase mydatabase = getActivity().openOrCreateDatabase("aappen", getActivity().MODE_PRIVATE, null);

                  Log.d(SHETTY, "getRSSfeedstoSqLite: 1  " + mydatabase);


              RSSMasterInfo.RssInfoPhp rssInfophp = new RSSMasterInfo.RssInfoPhp();
            RSSMasterList = rssInfophp.getData();
            rssItems = new ArrayList<RSSItem>();
            //  RssLinkForOnTouch = new ArrayList<RSSMasterInfo.RssfeedSubCategoryLink>();

         for (int j = 0; j < RSSMasterList.size(); j++) {
                RSSReader reader = new RSSReader();
                String uri = RSSMasterList.get(j).getLink();
                RSSFeed feed = reader.load(uri);

             Names = RSSMasterList.get(j).getNames();
             Urls = RSSMasterList.get(j).getUrls();
             Imagelinks = RSSMasterList.get(j).getImageinks();

                rssItems = feed.getItems();
                for (RSSItem rssItem : rssItems) {
                    int count = 0;
                    Log.i("RSS Reader ", rssItem.getTitle());
                    Uri v = rssItem.getLink();
                    String Header = rssItem.getTitle().replace("'", "`");
                    String Details = rssItem.getDescription().replace("'", "`");
                    String Link = rssItem.getLink().toString();

                    String PubDatestr = Formats.TIMESTAMP.formatValue(rssItem.getPubDate());


                    System.out.println("DATE@@@@@@@@@ "+PubDatestr+"    "+"   URI  "+uri+"   "+rssItems);

                    /*
                    Instance to create the current time values
                     */
                  Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+05:30"));
                    Date currentLocalTime = cal.getTime();
                    DateFormat date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
                    // you can get seconds by adding  "...:ss" to it
                    date.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
                    String localTime = date.format(currentLocalTime);

                    String Randomid = UUID.randomUUID().toString();
                    String RssSource = rssItem.getLink().toString();

                    /*
                    Code to split the rss link got to show the Source as: www.deccanherald.com
                     */

                    String res2 = RssSource.substring(7, RssSource.length());
                    String finalSplitRssSource = res2.substring(0, res2.indexOf("/"));
                    String ActualRssSource = finalSplitRssSource.toString();


                        mydatabase.execSQL("CREATE TABLE IF NOT EXISTS rssdata(ID VARCHAR,header VARCHAR(1000) , detail VARCHAR(8000) , link VARCHAR(2000) , pubdate VARCHAR(100) , rsssource VARCHAR(100) , datetime VARCHAR(50)  );");


                    mydatabase.execSQL("DELETE FROM rssdata WHERE link= '" + Link + "' ");

                    mydatabase.execSQL("UPDATE rssdata SET datetime= '" + localTime + "' ");

                    mydatabase.execSQL("INSERT INTO rssdata VALUES('" + Randomid + "' , '" + Header + "' , '" + Details + "'  , '" + Link + "' , '" + PubDatestr + "' , '" + ActualRssSource + "' , '" + localTime + "' ) ");

                    Cursor res1 = mydatabase.rawQuery("select * from rssdata where link= '" + Link + "' ", null);

                    String RssFeedResults = null;
                    res1.moveToFirst();
                    if (res1.getCount() == 1) {
                        RssFeedResults = res1.getString(0);
                    }

                     System.out.println(RssFeedResults);

                }
            }
        }

logcat

09-15 12:32:18.489 16186-17460/aappen.com.buddiesnew E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
                                                                       java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                           at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                           at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                                                                           at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                                                                           at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                                                                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                                                                           at java.lang.Thread.run(Thread.java:864)
                                                                        Caused by: java.lang.NullPointerException
                                                                           at aappen.com.buddiesnew.TabFragment0.getRSSfeedstoSqLite(TabFragment0.java:935)
                                                                           at aappen.com.buddiesnew.TabFragment7$1.doInBackground(TabFragment7.java:81)
                                                                           at aappen.com.buddiesnew.TabFragment7$1.doInBackground(TabFragment7.java:71)
                                                                           at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                           at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
                                                                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
                                                                           at java.lang.Thread.run(Thread.java:864) 

its pointing below line

SQLiteDatabase mydatabase = getActivity().openOrCreateDatabase("aappen", getActivity().MODE_PRIVATE, null);

i caught that null pointer exception with try/catch block just to check will it proceed but again null pointer exception at this point. so guys please suggest me how to crack this.

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS rssdata(ID VARCHAR,header VARCHAR(1000) , detail VARCHAR(8000) , link VARCHAR(2000) , pubdate VARCHAR(100) , rsssource VARCHAR(100) , datetime VARCHAR(50)  );"); 
Chethan Shetty
  • 179
  • 1
  • 10

1 Answers1

2

As we found out, getActivity() returns null. It means in that moment fragment is not attached to some Activity. May be your call happens before attaching or after detaching - I think after detach because synchronous code doesn't throw exception.

Anyway there is Fragment lifecycle error. If this information is not enough I need more code of your fragment class.

Oops

Didn't see it at first time :)

TabFragment0 tab1= new TabFragment0();
tab1.getRSSfeedstoSqLite();

You are not attaching fragment at all. So there would not be any value in getActivity() call. Use FragmentManager to add fragment into some activity.

Later added solution

  1. Just repeat solution with adding fragment to FragmentManager. I don't know how you will get a reference, because getFragmentManager() is Activity's method. So if you already have activity refrence just use it. Simpliest way is to create constructor in your Fragment class that get acivity as parameter.

  2. openOrCreateDatabase is Context's method. So there is no need to call it from activity. And context you can get as static field of your custom application class.

  3. May be it would be better to just get reference to your fragment created before. You can get it by its id or tag from FragmentManager (again).

Ircover
  • 2,406
  • 2
  • 22
  • 42
  • Ya it was not attached at that point. but it gets attached when i tap on 3rd tab. so i called this method getRSSfeedstoSqLite(); in onResume of 4th fragment that's nothing but TabFragment0 only [ i re-arranged the fragments so numbers are like that]. I did like that because View-pager always loads up next fragment by default. still i am getting the same error. is there any other way to achieve it. i cant load up all the fragments at launch time because it will take lot of time to load. – Chethan Shetty Sep 15 '17 at 08:53
  • Added solutions to my answer. – Ircover Sep 15 '17 at 09:14