1

だからここに私が取り組んでいるコードがあります:

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

4 に答える 4

1

activity次の行でnullです:

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

コンストラクターで何にも割り当てていないためです。

代わりに context オブジェクトを使用しないのはなぜですか?

imageLoader = new ImageLoader(mContext);
于 2013-07-25T11:20:51.197 に答える
0

CustomAdapter で「アクティビティ」変数を初期化していないようです。

それがおそらくあなたのNPEの原因です。

MainActivity.thisおそらく代わりに使用する必要があります。

于 2013-07-25T11:20:34.203 に答える
0

そのURLのJSONメッセージが壊れているため、NullPointerExceptionが発生していると思います。たとえば、json は角かっこで始まり、json は中かっこで始まる必要があります。

いくつかの例については、公式ページを確認してください。

于 2013-07-25T11:25:53.267 に答える
0

を手に入れながらinflaterも使っていactivityます。mContextそこでも使う。

inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(mContext.getApplicationContext());
于 2013-07-25T12:22:07.493 に答える