我在将 ImageView 放入 GridView 时遇到问题,我解析 JSON,我从 json 中获取 url 并将其放入我的 ImageView 到 GridView 中,我有一个错误,你能帮帮我吗?
日志猫
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gazetaimage/com.gazetaimage.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2359)
at android.app.ActivityThread.access$600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5202)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.gazetaimage.ImageAdapter.<init>(ImageAdapter.java:37)
at com.gazetaimage.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:5106)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2263)
... 11 more
我的代码在我的 AsyncTask 中,我连接到我的 JSON 文件,并返回 JSONObject,在 ImageAdapter.class 中我得到这个对象,并放入 ImageView
public class ImageAdapter extends BaseAdapter {
public Context mContext;
public String[] mThumbs;
final static String TAG_ITEM = "item";
final static String TAG_BIG_IMAGE = "big_image";
public ImageAdapter (Context c){
mContext = c;
BackTask task = new BackTask();
task.execute();
try {
JSONObject result = task.get();
JSONArray jarray = result.getJSONArray(TAG_ITEM);
for(int i = 0; i < jarray.length(); i++){
JSONObject jrss = jarray.getJSONObject(i);
mThumbs[i] = jrss.getString(TAG_BIG_IMAGE);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getCount() {
return mThumbs.length;
}
@Override
public Object getItem(int position) {
return mThumbs[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageURI(Uri.parse(mThumbs[position]));
return imageView;
}