1

So here's the code I'm working on:

public class MainActivity extends ListActivity {

// url to make request
private static String url = "http://alyssayango.x10.mx/";

private static final String TAG_TYPE = "movie_type";
private static final String TAG_NAME = "movie_name";
private static final String TAG_LENGTH = "movie_length";
private static final String TAG_SCHEDULES = "movie_schedules";
private static final String TAG_CINEMA = "movie_cinema_number";
private static final String TAG_URL = "movie_image_url";

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

     MyTask task = new MyTask(MainActivity.this);
     task.execute(url);

}

public String readMovieSchedules(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(MainActivity.class.toString(), "Failed to download file");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();

  }

private class MyTask extends AsyncTask<String, Void, String>{

    private ProgressDialog pd;
    public MainActivity activity;

    public MyTask(MainActivity a)
    {
        activity = a;
    }

    @Override
    protected String doInBackground(String... urls) {

        String stringtoparse=null;
        for (String url : urls) {
                stringtoparse = readMovieSchedules(url); // getting XML from URL
                }
        return stringtoparse;

    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

        pd = new ProgressDialog(MainActivity.this);
        pd.setTitle("Downloading...");
        pd.setMessage("Please wait.");
        pd.setCancelable(false);
        pd.setIndeterminate(true);
        pd.show();

        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String readMovieSchedules) {

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> movieList = new ArrayList<HashMap<String, String>>();

        JSONArray jsonArray;
        try {
            jsonArray = new JSONArray(readMovieSchedules);

        Log.i(MainActivity.class.getName(),
            "Number of entries " + jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
          JSONObject jsonObject = jsonArray.getJSONObject(i);
          Log.i(MainActivity.class.getName(), jsonObject.getString("movie_name"));

          // Storing each json item in variable
          String name = jsonObject.getString(TAG_NAME);
          String type = jsonObject.getString(TAG_TYPE);
          String length = jsonObject.getString(TAG_LENGTH);
          String cinema = jsonObject.getString(TAG_CINEMA);
          String schedules = jsonObject.getString(TAG_SCHEDULES);
          String url = jsonObject.getString(TAG_URL);

          // creating new HashMap
          HashMap<String, String> map = new HashMap<String, String>();

          // adding each child node to HashMap key => value
          map.put(TAG_NAME, name);
          map.put(TAG_TYPE, type);
          map.put(TAG_LENGTH, length);
          map.put(TAG_CINEMA, cinema);
          map.put(TAG_SCHEDULES, schedules);
          map.put(TAG_URL, url);

          // adding HashList to ArrayList
          movieList.add(map);

          /**
           * Updating parsed JSON data into ListView
           * */
         THIS IS LINE 178       ListAdapter adapter = new CustomAdapter(MainActivity.this, movieList,
                R.layout.list_item,
                new String[] { TAG_NAME, TAG_CINEMA, TAG_SCHEDULES, TAG_URL }, 
                new int[] { R.id.name, R.id.cinema, R.id.schedules, R.id.image }); 


          setListAdapter(adapter);
          // selecting single ListView item
          ListView lv = getListView();

          // Launching new screen on Selecting Single ListItem
          lv.setOnItemClickListener(new OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> parent, View view,
                      int position, long id) {
                  // getting values from selected ListItem
                  String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                  String cost = ((TextView) view.findViewById(R.id.cinema)).getText().toString();
                  String description = ((TextView) view.findViewById(R.id.schedules)).getText().toString();
                  String url = ((TextView) view.findViewById(R.id.image_)).getText().toString();

                  // Starting new intent
                  Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                  in.putExtra(TAG_NAME, name);
                  in.putExtra(TAG_CINEMA, cost);
                  in.putExtra(TAG_SCHEDULES, description);
                  in.putExtra(TAG_URL, url);
                  startActivity(in);
              }
          });

        }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        pd.dismiss();

     super.onPostExecute(readMovieSchedules);   
    }

}


private class CustomAdapter extends SimpleAdapter {

    public ImageLoader imageLoader; 
    public LayoutInflater inflater = null;
    private Activity activity;
    private Context mContext;
    private URL url;
    private Bitmap bmp;

    public CustomAdapter(Context context, List<? extends Map<String, ?>> data,
            int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        mContext = context;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        THIS IS LINE 238 imageLoader = new ImageLoader(activity.getApplicationContext());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.list_item,
                    null);
        }

        HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView cinema = (TextView) convertView.findViewById(R.id.cinema);
        TextView schedules = (TextView) convertView.findViewById(R.id.schedules);
        ImageView image = (ImageView) convertView.findViewById(R.id.image);

        String nameString = (String) data.get(TAG_NAME);
        String cinemaString = (String) data.get(TAG_CINEMA);
        String schedulesString = (String) data.get(TAG_SCHEDULES);
        String imageURL = (String) data.get(TAG_URL);

        name.setText(nameString);
        cinema.setText(cinemaString);
        schedules.setText(schedulesString);


        try {
            URL newURL = new URL(imageURL);
            bmp = BitmapFactory.decodeStream(newURL.openConnection().getInputStream());
            image.setImageBitmap(bmp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        imageLoader.DisplayImage(imageURL, (Activity)mContext, image);

        return convertView;
    }
}
}

I'm having an error/NullPointerException in these lines:

  ListAdapter adapter = new CustomAdapter(MainActivity.this, movieList,
                R.layout.list_item,
                new String[] { TAG_NAME, TAG_CINEMA, TAG_SCHEDULES, TAG_URL }, 
                new int[] { R.id.name, R.id.cinema, R.id.schedules, R.id.image }); 

What is the thing that I'm missing in here? Any help is much appreciated. Thanks.

UPDATED the Log FILE:

  07-25 10:39:58.564: E/AndroidRuntime(971): FATAL EXCEPTION: main
  07-25 10:39:58.564: E/AndroidRuntime(971): java.lang.NullPointerException
  07-25 10:39:58.564: E/AndroidRuntime(971):    at com.say.stalucia.MainActivity$CustomAdapter.<init>(MainActivity.java:238)
  07-25 10:39:58.564: E/AndroidRuntime(971):    at com.say.stalucia.MainActivity$MyTask.onPostExecute(MainActivity.java:178)
  07-25 10:39:58.564: E/AndroidRuntime(971):    at com.say.stalucia.MainActivity$MyTask.onPostExecute(MainActivity.java:1)
  07-25 10:39:58.564: E/AndroidRuntime(971):    at android.os.AsyncTask.finish(AsyncTask.java:631)
  07-25 10:39:58.564: E/AndroidRuntime(971):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
  07-25 10:39:58.564: E/AndroidRuntime(971):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)

Line 238:

  imageLoader = new ImageLoader(activity.getApplicationContext());

Line 178:

  ListAdapter adapter = new CustomAdapter(MainActivity.this, movieList,
7
  • are you using that Url from top? because that page doesnt return anything. espacially no json. Commented Jul 25, 2013 at 11:06
  • I've updated my post, yes I'm using the URL from top. Please refresh it. thanks Commented Jul 25, 2013 at 11:11
  • can you indicate line 238 and 178 in MainActivity file? Commented Jul 25, 2013 at 11:13
  • @OnurA. I've added those lines. Please check thanks Commented Jul 25, 2013 at 11:14
  • no, i say can you indicate them? e.g put a marker to indicate which line is 278 etc. Commented Jul 25, 2013 at 11:16

4 Answers 4

1

activity is null in line:

imageLoader = new ImageLoader(activity.getApplicationContext());

as you have not assigned it to anything in the constructor.

Why not use the context object instead?

imageLoader = new ImageLoader(mContext);
Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure of the line number (you should get NPE on the line before it as well, which is inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); since activity is still null at this line). Avoid using activity object before initializing it
0

It looks like you never initialize the "activity" variable in the CustomAdapter.

That's probably the source of your NPE.

You should probably use MainActivity.this instead.

Comments

0

i think you are getting the NullPointerException because your JSON-message on that URL is broke. for example your json is starting with a squared bracket and json does have to begin with curly brackets.

for some example check the official page.

2 Comments

So what do you think needs to be done? I tried doing this: alyssayango.x10.mx/results.json
first impression: looks much better
0

While getting the inflater also you are using activity. Use mContext there too.

inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(mContext.getApplicationContext());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.