0

I am getting null pointer exception on void android.view.View.unFocus. I found three similar questions on stack overflow but all of them have issues like they didn't initialize any variable or something like this. But in my case i am not providing any code here. I just want to know why this error occur. Its not appear every time but sometimes. In my case i am just getting images from camera or gallery and then post it to server along with some other info. I am not using methods like onStop , onResume. Just using onCreate. Here is the complete error.

FATAL EXCEPTION: main
Process: com.plan9.qurbaniapps.qurbani, PID: 10768
java.lang.RuntimeException: Unable to stop activity {com.plan9.qurbaniapps.qurbani/com.plan9.qurbaniapps.qurbani.Activities.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.unFocus(android.view.View)' on a null object reference
       at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4035)
       at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4084)
       at android.app.ActivityThread.-wrap24(Unknown Source:0)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1622)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6494)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.unFocus(android.view.View)' on a null object reference
       android.view.ViewGroup.removeViewInternal(ViewGroup.java:5229)
       at android.view.ViewGroup.removeViewAt(ViewGroup.java:5192)
       at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:17                                                                 
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1819)
       at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3227)
       at android.support.v4.app.FragmentManagerImpl.dispatchStop(FragmentManager.java:3204)
       at android.support.v4.app.FragmentController.dispatchStop(FragmentController.java:236)
       at android.support.v4.app.FragmentActivity.onStop(FragmentActivity.java:597)
       at android.support.v7.app.AppCompatActivity.onStop(AppCompatActivity.java:183)
       at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1375)
       at android.app.Activity.performStop(Activity.java:7181)
       at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4032)
       at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4084) 
       at android.app.ActivityThread.-wrap24(Unknown Source:0) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1622) 
       at android.os.Handler.dispatchMessage(Handler.java:106) 
       at android.os.Looper.loop(Looper.java:164) 
       at android.app.ActivityThread.main(ActivityThread.java:6494) 
       at java.lang.reflect.Method.invoke(Native Method) 
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
03-04 22:40:34.796 10768-10768/com.plan9.qurbaniapps.qurbani E/CrashlyticsCore: Failed to execute task.
                                                                                java.util.concurrent.TimeoutException
       at java.util.concurrent.FutureTask.get(FutureTask.java:206)
       at com.crashlytics.android.core.CrashlyticsBackgroundWorker.submitAndWait(CrashlyticsBackgroundWorker.java:41)
       at com.crashlytics.android.core.CrashlyticsController.handleUncaughtException(CrashlyticsController.java:312)
       at com.crashlytics.android.core.CrashlyticsController$6.onUncaughtException(CrashlyticsController.java:296)
       at com.crashlytics.android.core.CrashlyticsUncaughtExceptionHandler.uncaughtException(CrashlyticsUncaughtExceptionHandler.java:30)
       at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1068)
       at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1063)
       at java.lang.Thread.dispatchUncaughtException(Thread.java:1955)

And this error stop crasheletics to report crash. So please tell me way this error occure. Is there something i have to do in onResume or in onPause,onStop ? And i now what null pointer exception is so its not a duplicate question.

Some code here:

makepost.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                p = new ProgressDialog(MakePostActivity.this);
                if(makepost.getText().equals("Edit")){
                    p.setMessage("Editing...");
                }else {
                    p.setMessage("Posting...");
                }
                p.show();
                if(toggleButton.isChecked()){
                    salevalue = "true";
                }
                else{
                    salevalue = "false";
                }

          //      if(imageView.getTag() != null && !description.getText().toString().equals(""))

                if(imageView.getTag() != null && !category.isEmpty())
                {
                    makepost.setEnabled(false);
                    Toast.makeText(getApplicationContext() , "Post will be uploaded in few seconds" , Toast.LENGTH_LONG).show();
                    if(datafile == null) {
                        credentialsProvider();
                        TransferUtility transferUtility = new TransferUtility(s3Client, getApplicationContext());
                        String[] arr = imageView.getTag().toString().split("/");
                        File file1 = new File(imagePath);
                        Toast.makeText(getApplicationContext(), "category: " + category, Toast.LENGTH_LONG).show();
                        imageName = arr[arr.length - 1] + generateUniqueFileName();
                        TransferObserver observer = transferUtility.upload(
                                "*******",     /* The bucket to upload to */
                                imageName,    /* The key for the uploaded object */
                                file1        /* The file where the data to upload exists */
                        );

                        transferObserverListener(observer);
                    }
                    else{
                        makepost.setEnabled(false);
                        sendEditRequest();
                    }
                }

                else
                {
                    p.dismiss();
                    Toast.makeText(getApplicationContext() , "Upload Any Image and Choose the category" , Toast.LENGTH_LONG).show();
                }


            }
        });

private void sendrequest()
    {
        SharedPreferences sharedPreferences = getSharedPreferences("session"  , Context.MODE_PRIVATE);
        iddd = sharedPreferences.getString("id" , "");

        NetworkHelper.getServices().createPost(iddd,imageName,description.getText().toString(),category,"AUDIO" , salevalue).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, retrofit2.Response<String> response)
            {
                if(response.isSuccessful() && !response.body().toString().equals("-1"))
                {
                    makepost.setEnabled(true);
                    p.dismiss();
                    Toast.makeText(getApplicationContext() , "Successfully Posted" , Toast.LENGTH_LONG).show();
                    Intent it = new Intent(MakePostActivity.this , HomeActivity.class);
                    if(category.equals("Goat")) {
                        it.putExtra("VP", 2);
                    }
                    else if(category.equals("Cow")){
                        it.putExtra("VP" , 1);
                    }
                    else if(category.equals("Sheep")){
                        it.putExtra("VP" , 3);
                    }
                    startActivity(it);
                }
                else
                {
                    makepost.setEnabled(true);
                    p.dismiss();
                    Toast.makeText(getApplicationContext(),"Could'nt upload due to an error!",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t)
            {
                makepost.setEnabled(true);
                p.dismiss();
                Toast.makeText(getApplicationContext(),"Could'nt upload due to an error!",Toast.LENGTH_SHORT).show();
            }
        });
        trackScreen("Make Post Screen");
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if(EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            if (requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri uri = data.getData();
                try {
                    datafile = null;
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bytes);

                    String path = MediaStore.Images.Media.insertImage(MakePostActivity.this.getContentResolver(), bitmap, uri.getPath(), null);
                    file = Uri.parse(path);


                    imagePath = getRealPathFromURI(file);
                    imageView = (ImageView) findViewById(R.id.iv_gallery);
                    Picasso.with(MakePostActivity.this).load(path).fit().into(imageView);
                    imageView.setTag(imagePath);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (requestCode == 3 && resultCode == RESULT_OK) {
                datafile = null;
                File file1 = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES), "CameraDemo");
                file = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file1);
                bitmap = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bytes);
                String path = MediaStore.Images.Media.insertImage(MakePostActivity.this.getContentResolver(), bitmap, file.getPath(), null);
                file = Uri.parse(path);

                //path.get
                imageView.setTag(file.getPath());
                imagePath = getRealPathFromURI(file);
                Picasso.with(MakePostActivity.this).load(path).fit().into(imageView);


            }
        }
    }

1 Answers1

0

The problem is in onActivityResult. When you open the next activity, this activity is being destroyed. When you try to come back to this activity imageView is null and it crash when you try to execute this line imageView.setTag(file.getPath()); The easiest way to test this is going to your phone settings -> developer options -> don't keep activities

cherif
  • 1,164
  • 1
  • 11
  • 16