0

This is what I essentially want to do, but can't. I want the value of urlData and size to be updated from the inner class functions. The app is crashing by giving a Null Pointer Exception at the line where I try to access these variables from the ParseJSON() function.

package edu.ahduni.seas.gyapak;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

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

import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public ArrayList<Data> urlData;
    public int size; //no. of dirs + files
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        urlData = new ArrayList<Data>();
        super.onCreate(savedInstanceState);

        try {
                parseJSON();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        setContentView(R.layout.activity_main);
    }

    public void parseJSON() throws JSONException, InterruptedException {
        ParseActivity parse = new ParseActivity();
        String url = "RDovQWNhZGVtaWMvU2FuamF5IENoYXVkaGFyeQ==";
        parse.execute(url);

        TextView text = (TextView) findViewById(R.id.text);
        text.setText(Integer.toString(size)); //cannot access new value of size

        Log.e("RETURNING JSON","RETURNING");
    }



    private class ParseActivity extends AsyncTask<String, Void, ArrayList<Data>> {
        InputStream is = null;
        JSONArray jObj = null;
        String json = "";
        ArrayList<Data> parseData;

        @Override
        public void onPostExecute(ArrayList<Data> data) {
            String print="";
            urlData.addAll(parseData);
            size = this.parseData.size();
        }

        @Override //No null is returned from this function
        protected ArrayList<Data> doInBackground(String... params) {
            final String BASE_URL = "http://111.93.66.162/json/main.php?f=" + params[0];
            HttpURLConnection urlConnection;

            // Making HTTP request
            try {

                Log.e("OPENING: ", "URL");
                URL url = new URL(BASE_URL);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                is = urlConnection.getInputStream();

                StringBuffer buffer = new StringBuffer();
                if (is == null) {
                    // Nothing to do.
                    return null;
                }

                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                String line;

                while ((line = in.readLine()) != null) {
                    buffer.append(line + "\n");
                    Log.e("JSON: ", line);
                }
                if (buffer.length() == 0) {
                    return null;
                }
                is.close();
                json = buffer.toString();

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

            try {
                return getData(json); //This is getting returned
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        public ArrayList<Data> getData(String jsonString) throws JSONException {
            // try parse the string to a JSON object
            final String EXT = "ext";
            final String PATH = "path";
            final String NAME = "name";

            try {
                jObj = new JSONArray(jsonString);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            this.parseData = new ArrayList<Data>();

            for (int i=0;i<jObj.length();i++) {
                JSONObject obj = jObj.getJSONObject(i);
                String ext = obj.getString(EXT);
                String path = obj.getString(PATH);
                String name = obj.getString(NAME);

                this.parseData.add(new Data(ext,path,name));
            }
            return this.parseData;
        }
    }
}
burglarhobbit
  • 1,860
  • 2
  • 17
  • 32
  • An `AsyncTask` is asynchronous which means that you'll have to wait for it to finish before accessing its results. – Titus Aug 29 '16 at 20:40
  • I read your question, you state that you're facing a `NullPointerException`, the post that I linked explains well what this exception means and how to fix it. – Egor Aug 29 '16 at 20:40
  • @Egore People using AsyncTask already have issues in updating member variables of parent class, I tried solutions, but it didn't work. – burglarhobbit Aug 29 '16 at 20:41
  • @Egor I'm not facing Null Pointer Exception bc of null values. It's because the member variables aren't able to receive those values that are being assigned in the AsyncTask class functions and are remaining as it is: null. – burglarhobbit Aug 29 '16 at 20:43
  • @Egor Out of all the words in my statement, `Null Pointer Exception` is the only thing that caught your eye, how about I remove it? Maybe then your perspective would change. – burglarhobbit Aug 29 '16 at 20:44
  • @Titus I waited for it to finish? That's why the actual code where the assignment done is present in the `onPostExecute()` function. – burglarhobbit Aug 29 '16 at 20:48
  • 1
    Yes but `parseJSON(...)` is executed before the task finished (before `onPostExecute()` is called). – Titus Aug 29 '16 at 20:58
  • @Titus so the part after `execute()` should be moved to the `onPostExecute()` ? – burglarhobbit Aug 29 '16 at 21:11
  • Yes, that should work since `ParseActivity` is an inner class. To access the `MainActivity`'s context, you can use `MainActivity.this` – Titus Aug 29 '16 at 21:13
  • @Titus It worked! And for `MainActivity.this` YOU JUST SAVED ME ANOTHER QUESTION. Thank you for the help. You are a nice human. – burglarhobbit Aug 29 '16 at 21:19
  • 1
    I'm glad I could help. Good luck. – Titus Aug 29 '16 at 21:25

0 Answers0