-1

I would like to save some data to SharedPreferences inside of an AsyncTask, I have google it and followed some of the other answer on here but I can't seem to get it to work correctly.

 public class NtmLoadingTask extends AsyncTask<Void, Void, Void> {


    ArrayList<String> arr_dataNtmTitles = new ArrayList<String>();
    ArrayList<String> arr_dataNtmDates = new ArrayList<String>();
    ArrayList<String> arr_dataNtmContents = new ArrayList<String>();

 public NtmLoadingTask(Context applicationContext) {
}

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

    }

    @Override
    protected Void doInBackground(Void... params) {

        Document docNTM;
        try {
            Connection.Response response = Jsoup.connect("http://omitted")
                    .timeout(10000)
                    .ignoreHttpErrors(true)
                    .execute();

            int statusCode = response.statusCode();
            if (statusCode == 200) {

                docNTM = Jsoup.connect("http://omitted").timeout(10000).get();

                Elements tableRows;
                tableRows = docNTM.select("table[title= TABLE]");

                //Get the Notices to Mariners Amount
                Element ntmNumber = tableRows.select("td:eq(0)").last();
                String ntmAmt = ntmNumber.text();

                //In-case Data does not exist...
                if (tableRows != null) {//Exists...

                    //Convert Ntm Number to int for Gathering the Ntm List
                    int ntmInt = Integer.parseInt(ntmAmt);
                    for (int i = 0; i < ntmInt; i++) {

                        //Get Ntm Titles
                        Elements titles = tableRows.select("td:eq(1)");
                        String ntmTitle = titles.get(i).text() + "\n";
                        arr_dataNtmTitles.add(ntmTitle);


                        //Get Ntm Dates
                        Elements dates = tableRows.select("td:eq(2)");
                        String ntmDates = dates.get(i).text() + "\n";
                        arr_dataNtmDates.add(ntmDates);

                        //Get Ntm Content
                        Elements contents = tableRows.select("td:eq(3)");
                        String ntmContent = contents.get(i).text() + "\n";
                        arr_dataNtmContents.add(ntmContent);


*****THIS IS WHERE I WOULD LIKE TO SAVE THE DATA SO AS ONCE THIS TASK HAS COMPLETED 
             I CAN USE IT IN ANOTHER ACTIVITY**********************


                     };

                } else {
                    System.out.println("No Data : " + statusCode );
                }
            } else {
                System.out.println("Received error code " + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Received timeout error code);
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void params){

    System.out.println("NTM Content Captured and Saved");

       }
 }

I use Sharedpreferences in another activity when the app is loading and I understand how to use it in a normal activity but a whole load of errors or null pointers are thrown when trying to save anything here.

So should I be accessing the shared preferences file already created in the loading activity where this asyncTask is called from or do I create a new shared preference file inside of the doinbackground?

Thank you

Also the shared preferences I created in the loading activity:

//Created
public static final String APP_DATA = "AppData";
SharedPreferences DATA;
SharedPreferences.Editor Editor;

//Usage
DATA = getSharedPreferences(APP_DATA, MODE_PRIVATE);
Editor = DATA.edit();

Editor.clear();
            Editor.putString("HomePort", selectedItem);//save name
            Editor.apply();
            Editor.commit();
J4C3N-14
  • 686
  • 1
  • 13
  • 32
  • I would suggest you to save final data in `onPostExecute" of AsyncTask – deadfish Aug 22 '14 at 23:08
  • Why are you calling both `apply()` and `commit()` on the shared preferences object? Clearly that is not the correct usage... just use `apply()`. – Alex Lockwood Aug 22 '14 at 23:09
  • Save or read some values on postExecute method, is executed on UI main thread, and can block UI, the work with SharedPreference most executed on background. – Jose Rodriguez Aug 22 '14 at 23:25
  • you can access your sharedpreferences from any activity:refer to http://stackoverflow.com/questions/6186123/android-how-do-i-get-sharedpreferences-from-another-activity – user3487063 Aug 22 '14 at 23:26
  • Hi, thanks for the input. @deadfish yes I have seen that on other examples but how would I implement that? as that is what I am asking, which brings me to "user3487063" comment as because this is not a normal activity how do I access it? thanks – J4C3N-14 Aug 22 '14 at 23:45
  • @AlexLockwood Yes you are correct I think it changed from one to the other at some point clearly from your comment from commit to apply? thanks – J4C3N-14 Aug 22 '14 at 23:47
  • @user3487063 yes I am aware that you can use sharedpreferences in any activity but what I am stumbling on is how to use it in an AsyncTask? – J4C3N-14 Aug 22 '14 at 23:48

1 Answers1

0

I believe I wasn't passing the Context correctly the correct method for me was as following:

public class NtmLoadingTask extends AsyncTask<Void, Void, Void> {

public static final String APP_DATA = "AppData";
SharedPreferences DATA;
SharedPreferences.Editor Editor;

ArrayList<String> arr_dataNtmTitles = new ArrayList<String>();
ArrayList<String> arr_dataNtmDates = new ArrayList<String>();
ArrayList<String> arr_dataNtmContents = new ArrayList<String>();

public NtmLoadingTask(Context context) {

Here was were I was going wrong I wasn't passing the context correctly

    DATA = context.getSharedPreferences(APP_DATA, Context.MODE_PRIVATE);
    Editor = DATA.edit();

}

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

}

@Override
protected Void doInBackground(Void... params) {

I am now also saving the data in onPostExecute

J4C3N-14
  • 686
  • 1
  • 13
  • 32