Java Android截击无法返回字符串

Java Android截击无法返回字符串,java,android,Java,Android,我已经创建了一个类,通过它我想从数据库中获取一个列表url。但我得到了这个错误: 03-30 15:05:35.599 3591-3591/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.imran.myapp, PID: 3591

我已经创建了一个类,通过它我想从数据库中获取一个列表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;
}
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

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;
}
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;
    }
}
公共类相册列表{
私有字符串服务器;
语境;
公共字符串[]imgsurls;
私人视野;
AlbumsList(字符串服务器URL、上下文c、视图uview){
mycontext=c;
server=serverurl;
视图=uview;
}
公共视图连接(){
//实例化RequestQueue。
RequestQueue=Volley.newRequestQueue(mycontext);
//从提供的URL请求字符串响应。
StringRequest StringRequest=新的StringRequest(Request.Method.POST,服务器,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
//GridView gv=(GridView)view.findViewById(R.id.fragment\u gridgallery);
最终ArrayList urls2=新ArrayList();
试一试{
JSONArray jsonObj=新JSONArray(响应);
Myserver Myserver=新的Myserver();

对于(inti=0;i,因为
Volley
请求是异步的

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

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

此时,您的请求尚未完成。

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


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

您是说我应该在
onResponse()中初始化
String[]imgsurls
?是的。当收到imgresponse时,然后在那里初始化imgurls,使其首先成为私有类成员变量。然后在从OnResponseAnks传递控制以获得答复时,在toast中使用它。您能给出一个如何克服此问题的想法吗?请在
Volley的
onResponse
上使用
imgurls
这就是你说的吗?是的,你可以这样做。