从json url Android显示图像时出现Nullpointerexception

时间:2013-07-25 10:56:16

标签: android json

所以这是我正在处理的代码:

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;
    }
}
}

我在这些行中遇到错误/ NullPointerException:

  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 }); 

我在这里缺少的是什么?任何帮助深表感谢。感谢。

更新了日志文件:

  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)

第238行:

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

第178行:

  ListAdapter adapter = new CustomAdapter(MainActivity.this, movieList,

4 个答案:

答案 0 :(得分:1)

activity在行中为空:

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

因为你没有将它分配给构造函数中的任何内容。

为什么不使用上下文对象?

imageLoader = new ImageLoader(mContext);

答案 1 :(得分:0)

看起来你永远不会在CustomAdapter中初始化“activity”变量。

这可能是您的NPE的来源。

您应该使用MainActivity.this代替。

答案 2 :(得分:0)

我认为您正在获取NullPointerException,因为该URL上的JSON消息已损坏。例如,你的json以方括号开头,json必须以大括号开头。

对于某些示例检查the official page.

答案 3 :(得分:0)

获取inflater时,您还在使用activity。在那里也使用mContext

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