Home » Android » android – Cannot resolve method getApplicationContext()

android – Cannot resolve method getApplicationContext()

Posted by: admin June 15, 2020 Leave a comment

Questions:

This is the code I got from internet which I need it for my own application. I am trying to make an app using the example. The difference is that I made one separate class for this named JSONTask. I am getting error with getApplicationContex() function. Please help me with this.

import android.os.AsyncTask;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import navdrawerexample1.models.MovieModel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class JSONTask extends AsyncTask<String,String,List<MovieModel>>
{
private ListView lvMovies;
@Override
protected List<MovieModel> doInBackground(String... params) {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
        URL url= new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();


        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer buffer = new StringBuffer();
        String line ="";
        while ((line = reader.readLine())!=null){
            buffer.append(line);
        }
        String finalJason = buffer.toString();

        JSONObject parentObject = new JSONObject(finalJason);
        JSONArray parentArray = parentObject.getJSONArray("movies");

        List<MovieModel> movieModelList = new ArrayList<>();
        //StringBuffer finalBufferData = new StringBuffer();
        for (int i=0; i<parentArray.length();i++) {
            JSONObject finalObject = parentArray.getJSONObject(i);
            MovieModel movieModel = new MovieModel();
            movieModel.setMovie(finalObject.getString("movie"));
            movieModel.setYear(finalObject.getInt("year"));
            movieModel.setRating((float) finalObject.getDouble("rating"));
            movieModel.setDuration(finalObject.getString("duration"));
            movieModel.setDirector(finalObject.getString("director"));
            movieModel.setTagline(finalObject.getString("tagline"));
            movieModel.setImage(finalObject.getString("image"));
            movieModel.setStory(finalObject.getString("story"));

            List<MovieModel.cast> castList = new ArrayList<>();
            for (int j=0; j<finalObject.getJSONArray("cast").length();j++){
                MovieModel.cast cast = new MovieModel.cast();
                cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
                castList.add(cast);
            }
            movieModel.setCastList(castList);
            //adding the final object in the list
            movieModelList.add(movieModel);
        }
        return  movieModelList;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPostExecute(List<MovieModel> result) {
    super.onPostExecute(result);
    //This is where I get the error
    MovieAdapter adapter = new MovieAdapter(getApplicationContext(),R.layout.row,result);
    lvMovies.setAdapter(adapter);
    //TODO need to set data to the list
}

}

How to&Answers:

The trouble is that you are calling getApplicationContext() inside a Class that does not extend Context or its subclasses (Activity, etc). You should pass Context or its subclass to the JSONTask constructor. Furthermore, I don’t see where you are initializing lvMovies – and you are likely to get NullPointerException at lvMovies.setAdapter(adapter); – my suggestion is that you should pass this as well to your JSONTask constructor:

private Context mContext;
private ListView lvMovies;
public JSONTask (Context context, ListView  lstView){
   this.lvMovies = lstView;
   this.mContext = context;
} 

so that in the onPostExecute you can do something like:

MovieAdapter adapter = new MovieAdapter(mContext,R.layout.row,result);
lvMovies.setAdapter(adapter);

I hope this helps.

Answer:

First declare context,

Activity context;

then

MovieAdapter adapter = new MovieAdapter(context.getApplicationContext(),R.layout.row,result);
        lvMovies.setAdapter(adapter);

I hope this is helpfull to you……

Answer:

You cannot access getApplicationContext() from asynTask because getApplicationContext() doesn’t exist in AsyncTask.
Make a constructor and pass Context to this class. Use it in your JSONTask class.

I would recommend you to use Volley library instead of AsyncTask.

Answer:

create a constructor and pass it a Context variable like

public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{
public Context mContext;

public JSONTask(Context context){
    this.mContext = context;
}
.
.
.

now create JsonTask object from your activity/service as

JSONTask task = new JSONTask(getApplicationContext());

and now you can use mContext where you need to pass a context.