Android Lazy将图像从JSON加载到gridview中

时间:2013-03-22 12:13:48

标签: android gridview lazy-loading

所以我试图将我返回的json数组中的图像加载到交错的gridview中。我已经测试过将链接直接放入数组中,就像示例一样,它运行良好,但是一旦我尝试使用json数据,我就会出错。(网络和存储错误) 我的清单中有所有必需的权限(即互联网,内部和外部存储)

这是我的代码,有人可以让我知道什么是错的吗?谢谢!

package com.example.staggeredgridviewdemo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;

import com.origamilabs.library.views.StaggeredGridView;

/**
 * 
 * This will not work so great since the heights of the imageViews are
 * calculated on the iamgeLoader callback ruining the offsets. To fix this try
 * to get the (intrinsic) image width and height and set the views height
 * manually. I will look into a fix once I find extra time.
 * 
 * @author Maurycy Wojtowicz
 * 
 */
public class MainActivity extends Activity {

    /*
     * Images are taken by Romain Guy ! He's a great photographer as well as a
     * great programmer. http://www.flickr.com/photos/romainguy
     */

    private String urls[];
    String location = "http://snapoodle.com/APIS/android/feed.php";
    static final String TAG_ITEMS = "print";

    /*
     * private String urls[] = {
     * "http://farm7.staticflickr.com/6101/6853156632_6374976d38_c.jpg",
     * "http://farm8.staticflickr.com/7084/6885444694_6272874cfc.jpg" };
     */
    /**
     * This will not work so great since the heights of the imageViews are
     * calculated on the iamgeLoader callback ruining the offsets. To fix this
     * try to get the (intrinsic) image width and height and set the views
     * height manually. I will look into a fix once I find extra time.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        StaggeredGridView gridView = (StaggeredGridView) this
                .findViewById(R.id.staggeredGridView1);


        getImages get= (getImages) new getImages();
        get.execute(location);

        //int margin = getResources().getDimensionPixelSize(R.dimen.margin);

        //gridView.setItemMargin(margin); // set the GridView margin

        //gridView.setPadding(margin, 0, margin, 0); // have the margin on the
                                                    // sides as well

        StaggeredAdapter adapter = new StaggeredAdapter(MainActivity.this,
                R.id.imageView1, urls);

        gridView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    class getImages extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            JSONObject json = JSONfunctions
                    .getJSONfromURL(location);

            try {
                JSONArray jarray;
                jarray = json.getJSONArray(TAG_ITEMS);
                urls = new String[jarray.length()];

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject gridImages = jarray.getJSONObject(i);
                    urls[i] = gridImages.getString("saved_location");
                }

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


            return null;
        }

    }

}

logcat的

    03-22 14:57:59.276: D/AndroidRuntime(1183): Shutting down VM
    03-22 14:57:59.276: W/dalvikvm(1183): threadid=1: thread exiting with uncaught exception (group=0x4111f930)
    03-22 14:57:59.286: E/AndroidRuntime(1183): FATAL EXCEPTION: main
    03-22 14:57:59.286: E/AndroidRuntime(1183): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.staggeredgridviewdemo/com.example.staggeredgridviewdemo.MainActivity}: java.lang.NullPointerException: storage == null
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.os.Handler.dispatchMessage(Handler.java:99)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.os.Looper.loop(Looper.java:137)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.ActivityThread.main(ActivityThread.java:5041)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at java.lang.reflect.Method.invokeNative(Native Method)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at java.lang.reflect.Method.invoke(Method.java:511)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at dalvik.system.NativeStart.main(Native Method)
    03-22 14:57:59.286: E/AndroidRuntime(1183): Caused by: java.lang.NullPointerException: storage == null
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at java.util.Arrays.asList(Arrays.java:154)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at com.example.staggeredgridviewdemo.StaggeredAdapter.<init>(StaggeredAdapter.java:20)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at com.example.staggeredgridviewdemo.MainActivity.onCreate(MainActivity.java:89)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.Activity.performCreate(Activity.java:5104)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    03-22 14:57:59.286: E/AndroidRuntime(1183):     ... 11 more
    03-22 14:57:59.316: D/dalvikvm(1183): GC_CONCURRENT freed 176K, 3% free 8878K/9084K, paused 3ms+1ms, total 19ms

4 个答案:

答案 0 :(得分:2)

 StaggeredAdapter adapter = new StaggeredAdapter(MainActivity.this,
                R.id.imageView1, urls);

        gridView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

onPostExecute

中的AsyncTask中添加以上代码

希望这会对你有所帮助。

答案 1 :(得分:0)

这一行 03-22 14:57:59.286: E/AndroidRuntime(1183): at com.example.staggeredgridviewdemo.MainActivity.onCreate(MainActivity.java:89)表示MainActivity的第89行存在一些问题。这是您创建适配器的位置。如果仔细观察,您会发现尝试使用null项目列表创建适配器 - urls尚未初始化。

您使用的AsyncTask在不同的线程中执行,因此doInBackground中发生的所有事情(如urls = new String[jarray.length()];)都在另一个线程中。在这种情况下,这意味着urls数组在用于创建适配器后初始化。

为避免这种情况,您可以在开始活动之前初始化阵列。如果此时您不知道它的大小,您可以使用另一个适配器(如ListAdapter)使用非空列表对其进行初始化,然后从活动中填写此列表并在之后调用notifyDataSetChanged任务已经完成。

答案 2 :(得分:0)

检查数据Feed http://snapoodle.com/APIS/android/feed.php,我没有看到请求返回任何数据。

{ “打印”:[]}

答案 3 :(得分:0)

我有点愚蠢,但我通过将交错的网格视图移动到onPostExecute并从背景中的do返回网址来解决它