1

I have creted a class through which i want to get a list url's from the database. But I get this error:

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.

This is the activity in which i am using the class: 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;
    }
}

In AlbumsList.java, I want to return the list of URLS by either a function or variables, but both approachs don't work. Interestingly the url's are fetched proper from database. And that Toast inside AlbumsList.java: Toast.makeText(mycontext, imgsurls[0], Toast.LENGTH_LONG).show(); also works. Then I don't know why the imgsurls is not returned to main function. Thanks in advance.

Imran Aslam
  • 208
  • 2
  • 15

2 Answers2

1

Because Volley request is asynchronous.

Thus when are you calling albumsList.connection();, the request is running in background and before it is completed, control comes to the following line:

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

And by that time, your request is not completed.

Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
0

Volley works in an asynchronous fashion. This means that it doesn't return the result of the operation immediately. You are trying to access the results before they are fetched from the server.

You should move your view initialisation logic to the onResponse(), when the result is actually being delivered.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28
  • are you saying that i should initialize `String[] imgsurls` in `onResponse()` ? – Imran Aslam Mar 30 '16 at 10:42
  • 1
    Yes .when imgresponse is received then initialize your imgurls there making it a private class member variable first .then use it in your toast when control has passed on from onresponse – VarunJoshi129 Mar 30 '16 at 11:13