0

I have this piece of code (LINE 2) that is returning :

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.projecti_popularmovies/com.example.android.projecti_popularmovies.MainActivity}: java.lang.NullPointerException

My code is :

public class MainActivity extends AppCompatActivity {

public MovieFragment mMovieFragment;
public Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    mContext = this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMovieFragment = new MovieFragment();
    if(savedInstanceState == null){
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, mMovieFragment)
                .commit();
    }
    if(mMovieFragment.getArrayImages() == null){
        Log.v(null, "Array is empty");
    }
    GridView gridView = (GridView) findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter(this, mMovieFragment.getArrayImages()));

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(MainActivity.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });
}  

I have checked the getArrayImages before this and its not null, I also tried to send the activity by getActivity() and it cannot find the method getActivity().

the word this refers to this activity context

Here is my constructor for ImageAdapter class:

public ImageAdapter(Context context, String[] images) {  

This is the code to populate the mArrayImages:

    private Void getMovieImagesFromJson(String movieJSONstr) throws JSONException {

        final String OWM_RESULTS = "results";
        final String OWM_POSTERPATH = "poster_path";

        JSONObject movieJson = new JSONObject(movieJSONstr);
        JSONArray movieArray = movieJson.getJSONArray(OWM_RESULTS);

        Log.v("SIZE MOVIE ARRAY: ", Integer.toString(movieArray.length()));

        for(int i = 0; i < movieArray.length(); i++) {
            JSONObject movieObj = movieArray.getJSONObject(i);
            mArrayImages[i] = movieObj.getString(OWM_POSTERPATH);
        }

        return null;
    }
Joao Pereira
  • 75
  • 2
  • 11

2 Answers2

0

Declare a GlobalVariable

public Context mContext;

In your OnCreate() do this :

mContext = this;

Then you can call setAdapter and your Context won't be null.

gridView.setAdapter(new ImageAdapter(mContext, mMovieFragment.getArrayImages()));

EDIT

Try to use MainActivity.this instead.

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

Instead of

MainActivity.this

use getApplicationContext()

Cody Harness
  • 1,116
  • 3
  • 18
  • 37