为什么我的Android应用程序给出了一个illegalStateException

时间:2016-07-16 18:03:19

标签: android android-volley

所以我正在创建一个应用程序,将表单详细信息和图像发送到远程服务器。详细信息涉及一些文本,我可以从edittexts和图像中获取,用户可以从相机或图库中获取。 我遇到的问题是提交按钮(bSubmit),我需要在单击一次后立即禁用它。问题是它被禁用但是经过很长时间后,用户有很多时间再次点击它并再次向服务器发送不同的信息。
但是我第一次点击bSubmit时,相同的数据被发送两次。有具体原因吗?

如果我再次尝试单击bSubmit按钮,我也会得到java.lang.illegalStateException.Current线程必须有一个looper。

public class MainActivity extends ActionBarActivity implements View.OnClickListener{

    private EditText etName;
    private Button bGallery,bTakePhoto,bSubmit;
    private ImageView imReciept;

    int count = 1;  // To count the number of button clicks;

    private String UPLOAD_URL ="http://some_url.com";

    private Bitmap bitmap;

    File file;
    Uri file_uri_camera;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etName = (EditText) findViewById(R.id.etName);


        bGallery = (Button) findViewById(R.id.bGallery);
        bTakePhoto = (Button) findViewById(R.id.bTakePhoto);
        bSubmit = (Button) findViewById(R.id.bSubmit);

        imReciept = (ImageView) findViewById(R.id.imReciept);


        bGallery.setOnClickListener(this);
        bTakePhoto.setOnClickListener(this);
        bSubmit.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {

        if(v == bGallery){      //20

            Intent i = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i,20);
        }
        if(v == bTakePhoto){        //10

            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            getFileUri();
            i.putExtra(MediaStore.EXTRA_OUTPUT, file_uri_camera);
            startActivityForResult(i,10);
        }
        if(v == bSubmit){

            StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {

                            Toast.makeText(MainActivity.this, "Data Successfully sent!",
                                    Toast.LENGTH_LONG).show();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {

                            Toast.makeText(MainActivity.this, volleyError.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    //Converting Bitmap to String
                    String image = getStringImage(bitmap);

                    String name = etName.getText().toString().trim();



                    //Creating parameters
                    Map<String,String> params = new Hashtable<String, String>();

                    //Adding parameters
                    params.put("image", image);
                    params.put("name", name);


                    //THIS is where the main problem is happening 
                    if(count >1){
                        bSubmit.setEnabled(false);
                    }

                    count++;
                    //returning parameters
                    return params;
                }
            };

            //Creating a Request Queue
            RequestQueue requestQueue = Volley.newRequestQueue(this);

            //Adding request to the queue
            requestQueue.add(stringRequest);

        }
    }


    //Creates a file Uri for the image taken
    private void getFileUri() {
        //saves the photo just taken into sdcard
        String image_name = "testing123.jpg";
        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator
                + image_name);
        file_uri_camera = Uri.fromFile(file);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 10 && resultCode == RESULT_OK){


            //Uri selectedImage = data.getData();
            //imReciept.setImageURI(selectedImage);
            bitmap = BitmapFactory.decodeFile(file_uri_camera.getPath());
            imReciept.setImageBitmap(bitmap);
        }

        if(requestCode == 20 && resultCode == RESULT_OK && data != null){

            Uri selectedImage = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                //Setting the Bitmap to ImageView
                imReciept.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }
}

感谢您的帮助。我非常感激。

另外,如果你能想到其他任何可以改进的程序,请告诉我。我还是Android应用程序开发的新手。任何帮助表示赞赏。

编辑 - 为什么我在问题中得到-1?

编辑2 -

      07-17 00:00:23.918  15105-15441/com.example.username.nic_volley E/Volley﹕ [14460] NetworkDispatcher.run: Unhandled exception java.lang.IllegalStateException: The current thread must have a looper!
      java.lang.IllegalStateException: The current thread must have a looper!
              at android.view.Choreographer$1.initialValue(Choreographer.java:96)
              at android.view.Choreographer$1.initialValue(Choreographer.java:91)
              at java.lang.ThreadLocal$Values.getAfterMiss(ThreadLocal.java:460)
              at java.lang.ThreadLocal.get(ThreadLocal.java:65)
              at android.view.Choreographer.getInstance(Choreographer.java:192)
              at android.animation.ValueAnimator$AnimationHandler.<init>(ValueAnimator.java:656)
              at android.animation.ValueAnimator$AnimationHandler.<init>(ValueAnimator.java:631)
              at android.animation.ValueAnimator.getOrCreateAnimationHandler(ValueAnimator.java:1453)
              at android.animation.ValueAnimator.cancel(ValueAnimator.java:1057)
              at android.animation.AnimatorSet.cancel(AnimatorSet.java:335)
              at android.animation.StateListAnimator.cancel(StateListAnimator.java:192)
              at android.animation.StateListAnimator.setState(StateListAnimator.java:176)
              at android.view.View.drawableStateChanged(View.java:15988)
              at android.widget.TextView.drawableStateChanged(TextView.java:3659)
              at android.support.v7.widget.AppCompatButton.drawableStateChanged(AppCompatButton.java:143)
              at android.view.View.refreshDrawableState(View.java:16032)
              at android.view.View.setEnabled(View.java:6724)
              at android.widget.TextView.setEnabled(TextView.java:1446)
              at com.example.username.nic_volley.MainActivity$3.getParams(MainActivity.java:133)
              at com.android.volley.Request.getBody(Request.java:397)
              at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
              at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
              at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
              at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
              at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

这是我在android studio中得到的错误

2 个答案:

答案 0 :(得分:0)

您应该在if(v == bSubmit){之后的第一个语句中禁用该按钮。

答案 1 :(得分:0)

您的按钮未被禁用,因为您将计数器递增到代码后期。一旦你输入onClick() - 把这个

                bSubmit.setEnabled(false);

然后无法再次点击 如果转移失败,则可以重新启用按钮