onActivityResult работает нормально на всех моих и 100 выше устройств, но не на некоторых устройствах, таких как micromax AQ4501

#java #android #bitmap

#java #Android #растровое изображение

Вопрос:

Я не знаю, почему data.getParcelableExtra("data"); возвращает null.

Мой код:

     public class ProfilePage extends AppCompatActivity implements View.OnClickListener {

    ImageView Profile_pic;
    EditText Name, Designation, Mobile, Email, City, State, Country, Website;
    Button Save, Back;
    private int ProfileID = 0;
    DbHelper MYDB;

    private static final int RESULT = 1;
    private Menu mainMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_page);
        try{
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setIcon(R.mipmap.ic_logo);
        }catch (Exception e){
            e.printStackTrace();
            Log.w("DS Nav:", e.getMessage());
        }

        MYDB = new DbHelper(this);

        Profile_pic = (ImageView) findViewById(R.id.ivProfilePicture);
        Profile_pic.setOnClickListener(this);

        Name = (EditText) findViewById(R.id.etProfileName);
        Designation = (EditText) findViewById(R.id.etProfileDesignation);
        Mobile = (EditText) findViewById(R.id.etProfileMobile);
        Email = (EditText) findViewById(R.id.etProfileEmail);
        City = (EditText) findViewById(R.id.etProfileCity);
        State = (EditText) findViewById(R.id.etProfileState);
        Country = (EditText) findViewById(R.id.etProfileCountry);
        Website = (EditText) findViewById(R.id.etProfileWebsite);

        Save = (Button) findViewById(R.id.btnProfileSave);
        Save.setOnClickListener(this);

        Back = (Button) findViewById(R.id.btnProfileBack);
        Back.setOnClickListener(this);


        try{
            String ProfilePicturePath = Environment.getExternalStorageDirectory().toString() "/DS Images/Profile_Picture.png";
            File Picfile = new File(ProfilePicturePath);
            if(Picfile.exists()){
                final Bitmap bitmap = BitmapFactory.decodeFile(ProfilePicturePath);
                Profile_pic.setImageBitmap(bitmap);
                Toast.makeText(ProfilePage.this, "You can change Your Picture with Click on Profile Picture.", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(ProfilePage.this, "Please Click on Default Picture and Change Your Profile Picture with Your Original Picture.", Toast.LENGTH_LONG).show();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        // Load data In EditText Fields if Available in Database:
        try{
            Cursor datacursor = MYDB.getData(null, null);
            if(datacursor.moveToFirst()) {
                this.ProfileID = datacursor.getInt(0);
                Name.setText(datacursor.getString(1));
                Designation.setText(datacursor.getString(2));
                Mobile.setText(datacursor.getString(3));
                Email.setText(datacursor.getString(4));
                City.setText(datacursor.getString(5));
                State.setText(datacursor.getString(6));
                Country.setText(datacursor.getString(7));
                Website.setText(datacursor.getString(8));
            }else{
                NotRegistered();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

        if(requestCode == RESULT amp;amp; resultCode == RESULT_OK amp;amp; data != null){
/*
*            Uri SelectedImage = data.getData();
*            String[] filepath = {MediaStore.Images.Media.DATA};
*
*            Cursor cursor = getContentResolver().query(SelectedImage, filepath, *null, null, null);
*            cursor.moveToFirst();
*
*            int Column = cursor.getColumnIndex(filepath[0]);
*            String PicPath = cursor.getString(Column);
*/

            final Bitmap b = data.getParcelableExtra("data");
            /*BitmapFactory.decodeFile(PicPath);*/

            try{
                File file = new File(Environment.getExternalStorageDirectory(), "DS Images");
                if(!file.exists()){
                    if(!file.mkdirs()){
                        Toast.makeText(ProfilePage.this, "Error: Folder Not Created!", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(ProfilePage.this, "Folder Successfully Created!", Toast.LENGTH_LONG).show();
                    }
                }

                FileOutputStream fos = new FileOutputStream(new File(Environment
                        .getExternalStorageDirectory().toString() "/DS Images/", "Profile_Picture"
                          ".png"));


                Boolean savePic = b.compress(Bitmap.CompressFormat.PNG, 100, fos);

                    if(savePic){
                        Toast.makeText(ProfilePage.this, "Picture Successfully Saved.", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(ProfilePage.this, "Error: Picture Not Saved!", Toast.LENGTH_SHORT).show();
                    }

                fos.flush();
                    fos.close();

                    String ProfilePicturePath = Environment.getExternalStorageDirectory().toString() "/DS Images/Profile_Picture.png";
                    final Bitmap bitmap = BitmapFactory.decodeFile(ProfilePicturePath);
                    Profile_pic.setImageBitmap(b);
                ExtraFunctions funcs = new ExtraFunctions(ProfilePage.this);
                funcs.refreshGallery(ProfilePage.this, new File(ProfilePicturePath));

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.ivProfilePicture:

                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.putExtra("crop","true");
                intent.putExtra("outputX", 300);
                intent.putExtra("outputY", 300);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, RESULT);

                break;

            case R.id.btnProfileSave:

                final String ProfileName, ProfileDesignation, ProfileMobile, ProfileEmail, ProfileCity, ProfileState, ProfileCountry, ProfileWebsite;
                ProfileName = Name.getText().toString();
                ProfileDesignation = Designation.getText().toString();
                ProfileMobile = Mobile.getText().toString();
                ProfileEmail = Email.getText().toString();
                ProfileCity = City.getText().toString();
                ProfileState = State.getText().toString();
                ProfileCountry = Country.getText().toString();
                ProfileWebsite = Website.getText().toString();

                int update;

                try{
                    Cursor chkData = MYDB.getData(null, null);
                    if(chkData.moveToFirst()) {

                        update = MYDB.updateData(this.ProfileID , ProfileName, ProfileDesignation, ProfileMobile, ProfileEmail, ProfileCity, ProfileState, ProfileCountry, ProfileWebsite, null, null);

                        if (update == 1) {
                            Toast.makeText(ProfilePage.this, "Your Profile is Successfully Updated", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(ProfilePage.this, "Profile Not Updated", Toast.LENGTH_LONG).show();
                        }
                    }else{
                        NotRegistered();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(ProfilePage.this, "Profile Not Updated : " e, Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btnProfileBack:
                onBackPressed();
                break;
        }
    }
 }
  

Журнал:

 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/file/3508/ORIGINAL/NONE/605209574 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/file/3508/ORIGINAL/NONE/605209574} }} to activity {in.mydiscover.discover_branding/in.mydiscover.discover_branding.ProfilePage}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
    at android.app.ActivityThread.-wrap16(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
    at in.mydiscover.discover_branding.ProfilePage.onActivityResult(ProfilePage.java:140)
    at android.app.Activity.dispatchActivityResult(Activity.java:6456)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
    ... 9 more
  

Еще раз я проверю все свои устройства, и мои 99% клиентских устройств работают отлично, но показывают вышеуказанные исключения на некоторых моих клиентских устройствах. Поэтому, пожалуйста, помогите мне решить эту проблему.

Комментарии:

1. У вас есть исключение NullPointerException. C!ранее отмечен в журнале. Почему вы опубликовали так много нерелевантного кода?

2. @greenapps Да! Я проверил. Но почему data.getParcelableExtra(«данные»); возвращает нулевое значение? Потому что данные не равны нулю. Вы можете проверить в журнале.

3. данные могут быть не нулевыми, но там нет такого разделяемого дополнительного. Поэтому проверьте наличие null самостоятельно, прежде чем выполнять больше кода. Попробуйте другое намерение без обрезки или просто другое.

4. Также попробуйте data.getData() посмотреть, выдает ли он растровое изображение.

5. @greenapps Спасибо за ответ, и я проверю ваши предложения 🙂