How to pass application context to the Adapter reading Json using AsyncTask?

1
private class GetEmpresas extends AsyncTask<Void, Void, Void> {

... 

@Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        //Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                empresasJson = jsonObj.getJSONArray(TAG_EMPRESAS);

                // looping through All Contacts
                for (int i = 0; i < empresasJson.length(); i++) {

                    JSONObject c = empresasJson.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NOME);
                    String cidade = c.getString(TAG_CIDADE);
                    String endereco = c.getString(TAG_ENDERECO);

                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, id);
                    contact.put(TAG_NOME, name);
                    contact.put(TAG_CIDADE, cidade);
                    contact.put(TAG_ENDERECO, endereco);

                                                    empresas = new ArrayList<Empresas>();

                    Empresas item = new Empresas(name,endereco, R.drawable.logo);

                    empresas.add(item);

                    adapter = new AdapterEmpresas(empresas, ?????);

                    listView.setAdapter(adapter);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

     ....

}

ERROR

01-30 18:21:25.058: E/AndroidRuntime(8276): FATAL EXCEPTION: AsyncTask #1
01-30 18:21:25.058: E/AndroidRuntime(8276): java.lang.RuntimeException: An error occured while executing doInBackground()
01-30 18:21:25.058: E/AndroidRuntime(8276):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.lang.Thread.run(Thread.java:856)
01-30 18:21:25.058: E/AndroidRuntime(8276): Caused by: java.lang.NullPointerException
01-30 18:21:25.058: E/AndroidRuntime(8276):     at com.solutudo.activities.Main$GetEmpresas.doInBackground(Main.java:137)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at com.solutudo.activities.Main$GetEmpresas.doInBackground(Main.java:1)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-30 18:21:25.058: E/AndroidRuntime(8276):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-30 18:21:25.058: E/AndroidRuntime(8276):     ... 4 more

Question:

How do I pass the method context from where I am to the adapter that receives the context?

Before loading Json, I had created another class, and when I passed this as a parameter, it worked correctly. Now that other method does not work.

    
asked by anonymous 30.01.2014 / 18:48

2 answers

1

I suggest some changes. First, the reason:

Operations related to Android UI can not be done in the InBackground method, as it does not run on the Main Thread. UI operations can only be performed on the Main Thread. So, you should perform operations on the UI in the onPostExecute method as it runs on the Main Thread.

On the passage of the Context, the suggestion of lucasb.aquino is correct.

On the NullPointerException error, I believe it may be due to the inappropriate update point of the UI.

That way your code would look like this

The onCreate method

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new GetEmpresas(this).execute();
}

Your AsyncTask GetEnterprises

private class GetEmpresas extends AsyncTask<Void, Void, List<Empresas>> {

    private Context mContext;

    public GetEmpresas(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected List<Empresas> doInBackground(Void... params) {

        ...

        return empresas;
    }

    @Override
    protected void onPostExecute(List<Empresas> listEmpresas) {
        super.onPostExecute(listEmpresas);

        adapter = new AdapterEmpresas(listEmpresas, mContext);

        listView.setAdapter(adapter);

    }

}

If NullPointerException persists, make more of your code available so that you can better assess the problem.

    
31.01.2014 / 13:10
1

You can create a constructor that receives the context.

Declare within your GetEmpresas class the mContext property as below:

private Context mContext;

And then create a constructor by passing the Context.

public GetEmpresas(Context ctx){
    mContext = ctx;
}

Now in the snippet of the call you passed this, pass the mContext property.

adapter = new AdapterEmpresas(empresas, mContext);

Edit: In your Activity ...

GetEmpresas getEmpresasAsync = new GetEmpresas(this);
getEmpresasAsync.execute();
    
30.01.2014 / 18:55