-1

I have this error when i try run my app using android volley:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: umaya.edu.androidvolley, PID: 1857
              java.lang.RuntimeException: Unable to start activity ComponentInfo{umaya.edu.androidvolley/umaya.edu.androidvolley.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                  at android.app.ActivityThread.access$800(ActivityThread.java:151)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                  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:903)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference

MainActivity

This is my activity main

package umaya.edu.androidvolley;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

public class MainActivity extends AppCompatActivity {
    //creamos todas las variables
    private TextView txt;
    //Variables de volley
    private RequestQueue queue;
    private final String url = "http://mywebpage.com";
    private StringRequest stringRequest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //inicializamos
        txt = (TextView) findViewById(R.id.mtxt);
        //Pedimos la respuesta dle servidor desde la url tomada como string
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // obtenemos la respuesta del servidor
                        txt.setText(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                txt.setText("That didn't work!");
            }
        });

        //agregamos la peticion
        queue.add(stringRequest);

    }
}

I have read about this error, and the able solutions says that in my Manifest add android:name="AppController" in , but when i try put in code, send me error.

AndroidMainifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="umaya.edu.androidvolley">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     <application
        android:name="umaya.edu.androidvolley.AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
El Micke
  • 151
  • 2
  • 13

1 Answers1

2

your queue is null because you need to initialise it as a singelton

public class MyApplication extends Application {

    public static final String TAG = MyApplication.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;



    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        req.setShouldCache(false);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }


}

then make a request and simply add it to the queue instance

JsonObjectRequest jsObjRequest = new JsonObjectRequest
            (Request.Method.POST, url_register, jso, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {


            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
    MyApplication.getInstance().addToRequestQueue(jsObjRequest);
}

and you need to update your manifest with this

<application
        android:name=".utils.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" />
Tarek hemdan
  • 874
  • 2
  • 10
  • 24