Android Volley无法返回String

时间:2016-03-30 10:24:48

标签: java android

我创建了一个类,我希望通过该类从数据库中获取列表URL。但是我得到了这个错误:

03-30 15:05:35.599 3591-3591/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.imran.myapp, PID: 3591
                                                 java.lang.NullPointerException: Attempt to read from null array
                                                     at com.example.imran.myapp.gridgallery.onCreateView(gridgallery.java:55)
                                                     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
                                                     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
                                                     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:493)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:145)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6145)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
03-30 15:05:35.599 1032-1045/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-30 15:05:35.599 1032-1045/? W/ActivityManager:   Force finishing activity com.example.imran.myapp/.Home
03-30 15:05:35.609 1032-1045/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-30 15:05:35.909 1032-1032/? D/CrashAnrDetector: processName: com.example.imran.myapp
03-30 15:05:35.919 1032-1032/? D/CrashAnrDetector: broadcastEvent : com.example.imran.myapp data_app_crash
03-30 15:05:36.159 1032-1059/? W/ActivityManager: Activity pause timeout for ActivityRecord{3f2af340 u0 com.example.imran.myapp/.Home t3125 f}
03-30 15:05:37.019 1032-1521/? I/WindowState: WIN DEATH: Window{224e112b u0 com.example.imran.myapp/com.example.imran.myapp.Home}
03-30 15:05:37.079 1032-1528/? I/ActivityManager: Process com.example.imran.myapp (pid 3591)(adj 9) has died(67,606)
03-30 15:05:37.359 10199-10199/? D/AASAservice-UpdateReceiver: AASAUpdateReceiver: android.intent.action.PACKAGE_REPLACED, package = com.example.imran.myapp, uid = -1
03-30 15:05:37.379 2433-3619/? D/PkgBroadcastIntentOp: Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.imran.myapp
03-30 15:05:37.559 2433-3974/? D/k: Processing package: com.example.imran.myapp
03-30 15:05:37.559 2227-3976/? D/Compatibility: intentservice saw: Intent { act=android.intent.action.PACKAGE_REPLACED dat=package:com.example.imran.myapp flg=0x4000010 cmp=com.sec.android.app.soundalive/.compatibility.Compatibility$Receiver (has extras) } Bundle[{android.intent.extra.UID=10252, android.intent.extra.REPLACING=true, android.intent.extra.user_handle=0}]
03-30 15:05:37.589 2433-3974/? D/GassUtils: Found app info for package com.example.imran.myapp:1. Hash: 6b9333e031907d7a6a6c12cd9fdfa0d23bd13ee0f40c9617ddd005dc358321b0
03-30 15:05:37.589 2433-3974/? D/k: Found info for package com.example.imran.myapp in db.

这是我使用该课程的活动: gridgallery.java

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_gridgallery, null);
    Myserver myserver = new Myserver();
    //postStringRequest(myserver.url + "/api/albums/getalbums.php", view);
AlbumsList albumsList = new AlbumsList(myserver.url+"/api/albums/getalbums.php",getContext(),view);
albumsList.connection(); // Do connection
Toast.makeText(getContext(),albumsList.imgsurls[1],Toast.LENGTH_LONG).show();
/*
GridView gv = (GridView)view.findViewById(R.id.fragment_gridgallery);
ImageAdapter myadapter = new ImageAdapter(getContext(),albumsList.imgurls());
gv.setAdapter(myadapter);
*/
return view;
}

AlbumsList.java

public class AlbumsList {
    private String server;
    Context mycontext;
    public String[] imgsurls;
    private View view;
    AlbumsList(String serverurl, Context c,View uview){
        mycontext = c;
        server = serverurl;
        view = uview;
    }

    public View connection(){
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(mycontext);
        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, server,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //GridView gv = (GridView)view.findViewById(R.id.fragment_gridgallery);
                        final ArrayList<String> urls2 = new ArrayList<String>();
                        try {
                            JSONArray jsonObj = new JSONArray(response);
                            Myserver myserver = new Myserver();
                            for (int i=0;i<jsonObj.length();i++){
                                JSONObject c = jsonObj.getJSONObject(i);
                                String imgurl = myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail");
                                urls2.add(imgurl);
                            }
                            final String myabc[] = urls2.toArray(new String[urls2.size()]); //Do not remove this
                            imgsurls = myabc;
                            Toast.makeText(mycontext, imgsurls[0], Toast.LENGTH_LONG).show(); //Interestingly this toast works and imgsurls[] is ok

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(mycontext,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mycontext, "Unable to reach server", Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getalbum", "getalbum");
                return params;
            }
        };
        queue.add(stringRequest);
        return view;
    }

    public String[] imgurls(){
        return imgsurls;
    }
}

AlbumsList.java中,我想通过函数或变量返回URLS列表,但这两种方法都不起作用。有趣的是,url是从数据库中获取的。而AlbumsList.java Toast.makeText(mycontext, imgsurls[0], Toast.LENGTH_LONG).show();内的Toast也有效。然后我不知道为什么imgsurls没有返回到main函数。提前致谢。

2 个答案:

答案 0 :(得分:1)

因为Volley请求异步

因此,您何时调用albumsList.connection();,请求在后台运行,在完成之前,控制权将转到以下行:

Toast.makeText(getContext(),albumsList.imgsurls[1],Toast.LENGTH_LONG).show();

到那时,您的请求尚未完成。

答案 1 :(得分:0)

Volley以异步方式工作。这意味着它不会立即返回操作的结果。您试图在从服务器获取结果之前访问结果。

当实际传递结果时,您应该将视图初始化逻辑移动到onResponse()