android通用图像加载器json

时间:2013-05-27 18:06:14

标签: android json

我使用代码失败了。 错误:

  

05-28 00:40:18.646:E / AndroidRuntime(854):致命异常:主要   05-28 00:40:18.646:E / AndroidRuntime(854):java.lang.NullPointerException   05-28 00:40:18.646:E / AndroidRuntime(854):at> com.nostra13.example.universalimageloader.ImageGridActivity $ ImageAdapter.getView(ImageGrid>> activity.java:130)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.widget.AbsListView.obtainView(AbsListView.java:1430)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.widget.GridView.onMeasure(GridView.java:935)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.View.measure(View.java:8313)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.widget.FrameLayout.onMeasure(FrameLayout.java:250)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.View.measure(View.java:8313)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.widget.LinearLayout.measureVertical(LinearLayout.java:531)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.widget.LinearLayout.onMeasure(LinearLayout.java:309)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.View.measure(View.java:8313)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.widget.FrameLayout.onMeasure(FrameLayout.java:250)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.View.measure(View.java:8313)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.ViewRoot.performTraversals(ViewRoot.java:839)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.view.ViewRoot.handleMessage(ViewRoot.java:1859)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.os.Handler.dispatchMessage(Handler.java:99)   05-28 00:40:18.646:E / AndroidRuntime(854):在android.os.Looper.loop(Looper.java:123)   05-28 00:40:18.646:E / AndroidRuntime(854):at> android.app.ActivityThread.main(ActivityThread.java:3683)   05-28 00:40:18.646:E / AndroidRuntime(854):at> java.lang.reflect.Method.invokeNative(Native Method)   05-28 00:40:18.646:E / AndroidRuntime(854):at> java.lang.reflect.Method.invoke(Method.java:507)   05-28 00:40:18.646:E / AndroidRuntime(854):at> com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839)   05-28 00:40:18.646:E / AndroidRuntime(854):at> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)   05-28 00:40:18.646:E / AndroidRuntime(854):at dalvik.system.NativeStart.main(Native> Method)

我的代码:

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.Closeable;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.Dialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;
    import android.widget.Toast;

    public class ImageGridActivity extends Activity {

JSONArray str_json = null;
public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
private ProgressDialog mProgressDialog;
ArrayList<HashMap<String, Object>> MyArrList;
String result = "";

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ac_image_grid);

    // Permission StrictMode
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    // Download JSON File
    new DownloadJSONFileAsync().execute();
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_JSON_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading.....");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

public void ShowAllContent() {
    final GridView gridView1 = (GridView) findViewById(R.id.gridview);
    gridView1
            .setAdapter(new ImageAdapter(ImageGridActivity.this, MyArrList));
    gridView1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            Toast.makeText(getApplicationContext(), "this is",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

public class ImageAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();

    public ImageAdapter(Context c,
            ArrayList<HashMap<String, Object>> myArrList) {
        context = c;
        MyArr = myArrList;
    }

    public int getCount() {
        return MyArr.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        View myView = convertView;
        viewHolder = new ViewHolder();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            myView = inflater.inflate(R.layout.item_grid_image, null);

            viewHolder.imageView = (ImageView) myView
                    .findViewById(R.id.image);
            viewHolder.imageView.getLayoutParams().height = 120;
            viewHolder.imageView.getLayoutParams().width = 120;
            viewHolder.imageView.setPadding(5, 5, 5, 5);
            viewHolder.imageView
                    .setScaleType(ImageView.ScaleType.CENTER_CROP);
            try {
                viewHolder.imageView.setImageBitmap((Bitmap) MyArr.get(
                        position).get("ImageThumBitmap"));
            } catch (Exception e) {
                viewHolder.imageView
                        .setImageResource(android.R.drawable.ic_menu_report_image);
            }
        }
        return myView;
    }
}

private static class ViewHolder {
    public ImageView imageView;
}

// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {

    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }

    @Override
    protected Void doInBackground(String... params) {

        String url = "http://10.0.2.2/andro_stie/berita.php";
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.AmbilJson(url);

        try {
            str_json = json.getJSONArray("berita");
            MyArrList = new ArrayList<HashMap<String, Object>>();
            HashMap<String, Object> map;
            for (int i = 0; i < str_json.length(); i++) {
                JSONObject ar = str_json.getJSONObject(i);
                map = new HashMap<String, Object>();

                map.put("photo", (String) ar.getString("gambar"));
                map.put("ImageThumBitmap",
                        (Bitmap) loadBitmap(ar.getString("gambar")));

                // Full (for View Popup)

                MyArrList.add(map);
            }

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

    @SuppressWarnings("deprecation")
    protected void onPostExecute(Void unused) {
        ShowAllContent(); // When Finish Show Content
        dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
        removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }
}

/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
    StringBuilder str = 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) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download file..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}

/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(),
                IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        // options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }
    return bitmap;
}

private static void closeStream(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            android.util.Log.e(TAG, "Could not close stream", e);
        }
    }
}

private static void copy(InputStream in, OutputStream out)
        throws IOException {
    byte[] b = new byte[IO_BUFFER_SIZE];
    int read;
    while ((read = in.read(b)) != -1) {
        out.write(b, 0, read);
    }
}
    }

1 个答案:

答案 0 :(得分:0)

View上有一个id =“image”的ImageView吗?因为它在第130行显示NullPointerException viewHolder.imageView = (ImageView) myView.findViewById(R.id.image); 还请检查您的第128行myView = inflater.inflate(R.layout.item_grid_image, null);