点击按钮时,滚动请求执行两次

时间:2016-06-19 08:10:14

标签: java android android-volley

我的代码工作正常,但是当我点击提交按钮时,它会显示两次凌空基本网络执行请求,并且我的数据库表会更新两次。

这是我的MainActivity代码:

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);
            }
        } );
    }
}

这是我的Logcat,它显示了两次调用相同的url。

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课程:

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;
    }
}

1 个答案:

答案 0 :(得分:9)

在MainActivity中,在行

之前
var data = {
  particles: {
    name: 'particles',
    values: []
  },
  timestamps: {
    name: 'timestamps',
    values: []
  }
}

var newK = {
  particles: 'particle',
  timestamps: 'timestamp'
};

// get all object keys and iterate over them
Object.keys(newK).forEach(function(ele) {
  // assign object property based on old property value
  data[newK[ele]] = data[ele];
  // update name property
  data[newK[ele]].name = newK[ele];
  // delete old object property
  delete data[ele];
})

console.log(data);

我添加了这一行:

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