Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volley request executes twice on button click

My code is working perfectly but when I click on the submit button it shows volley basic network perform request twice and my database table is updated twice.

Here is my MainActivity code:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity  {
    EditText etUsername, etPassword;
    Button bLogin;
    final String TAG= this.getClass().getSimpleName();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        etUsername = (EditText) findViewById(R.id.etUserName);
        etPassword = (EditText) findViewById(R.id.etPassword);
        bLogin = (Button) findViewById(R.id.bLogin);
        bLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url="http://10.0.2.2:8080/Login";
                final StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG,response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        NetworkResponse networkResponse = error.networkResponse;
                        if (networkResponse != null && networkResponse.statusCode == 403) {
                            // HTTP Status Code: 401 Unauthorized
                            Toast.makeText(getApplicationContext(),"Errrorrrrrrr....",Toast.LENGTH_SHORT).show();
                        }
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("userName",etUsername.getText().toString().trim());
                        params.put("password",etPassword.getText().toString().trim());
                        return params;
                    }
                };
                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
            }
        } );
    }
}

Here is my Logcat which shows same url calling twice.

06-19 13:42:12.351 25015-25015/com.test.loginapplication D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
06-19 13:42:14.721 25015-25015/com.test.loginapplication D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
06-19 13:42:14.911 25015-25820/com.test.loginapplication I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-19 13:42:14.911 25015-25820/com.test.loginapplication I/System.out: (HTTPLog)-Static: isShipBuild true
06-19 13:42:14.911 25015-25820/com.test.loginapplication I/System.out: (HTTPLog)-Thread-15685-955130212: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
06-19 13:42:14.916 25015-25820/com.test.loginapplication I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-19 13:42:14.916 25015-25820/com.test.loginapplication I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
06-19 13:42:14.916 25015-25820/com.test.loginapplication I/qtaguid: Tagging socket 42 with tag 85be69f900000000{2243848697,0} uid -1, pid: 25015, getuid(): 10225
06-19 13:42:15.086 25015-25820/com.test.loginapplication I/qtaguid: Untagging socket 42
06-19 13:42:15.086 25015-25820/com.test.loginapplication E/Volley: [15685] BasicNetwork.performRequest: Unexpected response code 403 for    http://10.0.2.2:8080/Login
06-19 13:42:15.091 25015-25820/com.test.loginapplication I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-19 13:42:15.091 25015-25820/com.test.loginapplication I/qtaguid: Tagging socket 42 with tag 85be69f900000000{2243848697,0} uid -1, pid: 25015, getuid(): 10225
06-19 13:42:15.251 25015-25820/com.test.loginapplication I/qtaguid: Untagging socket 42
06-19 13:42:15.251 25015-25820/com.test.loginapplication E/Volley: [15685] BasicNetwork.performRequest: Unexpected response code 403 for http://10.0.2.2:8080/Login
06-19 13:42:46.526 25015-25015/com.test.loginapplication V/ActivityThread: updateVisibility : ActivityRecord{b7d0dda token=android.os.BinderProxy@6966ed {com.test.loginapplication/com.test.loginapplication.LoginActivity}} show : true
06-19 13:42:46.746 25015-25015/com.test.loginapplication W/IInputConnectionWrapper: getCursorCapsMode on inactive InputConnection

MySingleton class:

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

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

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}
like image 993
Santosh Shrestha Avatar asked Jun 19 '16 08:06

Santosh Shrestha


People also ask

How do I get volley response error?

If you want to view the data in the case of an error code in response, you can use something like this: @Override public void onErrorResponse(VolleyError error) { String body; //get status code here String statusCode = String. valueOf(error. networkResponse.

What is a Volley request?

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub. Volley offers the following benefits: Automatic scheduling of network requests. Multiple concurrent network connections.

How does Volley library works?

It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again. Volley is not suitable for large download or streaming operations since Volley holds all responses in memory during parsing.

Why use Volley library in Android?

Volley is a HTTP Library which provides the facilities for network connectivity for our app. The advantages of using the Volley library are as follows: Easier and faster request management. Provide efficient network management.


1 Answers

In MainActivity, before the line

MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);

I added this line:

stringRequest.setRetryPolicy(new DefaultRetryPolicy(0,-1,
                                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
like image 145
Santosh Shrestha Avatar answered Oct 06 '22 01:10

Santosh Shrestha