运行时异常无法启动活动

时间:2017-09-03 00:17:10

标签: android android-library

我在android中创建了一个应用程序并且它工作正常但是当我将我的应用程序移动到我的主应用程序时它开始显示错误从那一点包名称与我以前的应用程序相同然后这也是我的错误得到。我跟着很多问题,但无法找到任何解决方案。

 FATAL EXCEPTION: main
                                              Process: unnion.neelay.beatbox, PID: 12739
                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{unnion.neelay.beatbox/unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                       at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:148)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
                                                                       at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
                                                                       at android.app.Activity.performCreate(Activity.java:6303)
                                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483) 
                                                                       at android.app.ActivityThread.access$900(ActivityThread.java:153) 
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                       at android.os.Looper.loop(Looper.java:148) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5441) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 

它显示了零点异常,但在未添加到主应用程序时它正常工作。 ringdroid选择活动

public class RingdroidSelectActivity
    extends ListActivity
    implements LoaderManager.LoaderCallbacks<Cursor> {
private SearchView mFilter;
private SimpleCursorAdapter mAdapter;
private boolean mWasGetContentIntent;
private boolean mShowAll;

private Cursor mExternalCursor;

// Result codes
private static final int EXT_STORAGE_PERMISSION_REQ_CODE = 2;
private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;
private static final int WRITE_SETTINGS = 3;
private static final int CHANGE_CONFIGURATION = 1;
private static final int MODIFY_AUDIO_SETTINGS = 5;
private static final int INTERNET = 6;
private static final int REQUEST_CODE_EDIT = 1;
private static final int REQUEST_CODE_CHOOSE_CONTACT = 2;

// Context menu
private static final int CMD_EDIT = 4;
private static final int CMD_DELETE = 5;
private static final int CMD_SET_AS_DEFAULT = 6;
private static final int CMD_SET_AS_CONTACT = 7;


public RingdroidSelectActivity() {
}

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    checkReadStoragePermission();


    mShowAll = false;

    String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
        showFinalAlert(getResources().getText(R.string.sdcard_readonly));
        return;
    }
    if (status.equals(Environment.MEDIA_SHARED)) {
        showFinalAlert(getResources().getText(R.string.sdcard_shared));
        return;
    }
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        showFinalAlert(getResources().getText(R.string.no_sdcard));
        return;
    }

    Intent intent = getIntent();
    mWasGetContentIntent = intent.getAction().equals(
            Intent.ACTION_GET_CONTENT);

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.media_select);
    getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    getActionBar().setDisplayShowTitleEnabled(false);
    try {
        mAdapter = new SimpleCursorAdapter(
                this,
                // Use a template that displays a text view
                R.layout.media_select_row,
                null,
                // Map from database columns...
                new String[]{
                        MediaStore.Audio.Media.ARTIST,

                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media._ID},
                // To widget ids in the row layout...
                new int[]{
                        R.id.row_artist,

                        R.id.row_title,
                        R.id.row_icon,
                        R.id.row_options_button},
                0);

        setListAdapter(mAdapter);


        // Normal click - open the editor
        getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent,
                                    View view,
                                    int position,
                                    long id) {
                startRingdroidEditor();
            }
        });


        mExternalCursor = null;

        getLoaderManager().initLoader(EXTERNAL_CURSOR_ID, null, this);

    } catch (SecurityException e) {
        // No permission to retrieve audio?
        Log.e("Ringdroid", e.toString());

        // TODO error 1
    } catch (IllegalArgumentException e) {
        // No permission to retrieve audio?
        Log.e("Ringdroid", e.toString());

        // TODO error 2
    }

    mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (view.getId() == R.id.row_options_button) {
                // Get the arrow ImageView and set the onClickListener to open the context menu.
                ImageView iv = (ImageView) view;
                iv.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        openContextMenu(v);
                    }
                });
                return true;
            } else if (view.getId() == R.id.row_icon) {
                setSoundIconFromCursor((ImageView) view, cursor);
                return true;
            }

            return false;
        }
    });

    // Long-press opens a context menu
    registerForContextMenu(getListView());

}

private void setSoundIconFromCursor(ImageView view, Cursor cursor) {

    if (0 != cursor.getInt(cursor.getColumnIndexOrThrow(
            MediaStore.Audio.Media.IS_MUSIC))) {
        view.setImageResource(R.drawable.type_music);
        ((View) view.getParent()).setBackgroundColor(
                getResources().getColor(R.color.type_bkgnd_music));
    }

    String filename = cursor.getString(cursor.getColumnIndexOrThrow(
            MediaStore.Audio.Media.DATA));

}

/**
 * Called with an Activity we started with an Intent returns.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent dataIntent) {
    if (requestCode != REQUEST_CODE_EDIT) {
        return;
    }

    if (resultCode != RESULT_OK) {
        return;
    }

    setResult(RESULT_OK, dataIntent);
    //finish();  // TODO(nfaralli): why would we want to quit the app here?
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.select_options, menu);

    mFilter = (SearchView) menu.findItem(R.id.action_search_filter).getActionView();
    if (mFilter != null) {
        mFilter.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            public boolean onQueryTextChange(String newText) {
                refreshListView();
                return true;
            }

            public boolean onQueryTextSubmit(String query) {
                refreshListView();
                return true;
            }
        });
    }

    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    menu.findItem(R.id.action_record).setVisible(true);
    // TODO(nfaralli): do we really need a "Show all audio" item now?
    menu.findItem(R.id.action_show_all_audio).setVisible(true);
    menu.findItem(R.id.action_show_all_audio).setEnabled(!mShowAll);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.action_record:
            onRecord();
            return true;
        case R.id.action_show_all_audio:
            mShowAll = true;
            refreshListView();
            return true;
        default:
            return false;
    }
}

@Override
public void onCreateContextMenu(ContextMenu menu,
                                View v,
                                ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    Cursor c = mAdapter.getCursor();
    String title = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));

    menu.setHeaderTitle(title);

    menu.add(0, CMD_EDIT, 0, R.string.context_menu_edit);
    menu.add(0, CMD_DELETE, 0, R.string.context_menu_delete);

    // Add items to the context menu item based on file type
    if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
        menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_ringtone);
        menu.add(0, CMD_SET_AS_CONTACT, 0, R.string.context_menu_contact);
    } else if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_NOTIFICATION))) {
        menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_notification);
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case CMD_EDIT:
            startRingdroidEditor();
            return true;
        case CMD_DELETE:
            confirmDelete();
            return true;
        case CMD_SET_AS_DEFAULT:
            setAsDefaultRingtoneOrNotification();
            return true;
        case CMD_SET_AS_CONTACT:
            return chooseContactForRingtone(item);
        default:
            return super.onContextItemSelected(item);
    }
}

private void setAsDefaultRingtoneOrNotification() {
    Cursor c = mAdapter.getCursor();

    // If the item is a ringtone then set the default ringtone,
    // otherwise it has to be a notification so set the default notification sound
    if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
        RingtoneManager.setActualDefaultRingtoneUri(
                RingdroidSelectActivity.this,
                RingtoneManager.TYPE_RINGTONE,
                getUri());
        Toast.makeText(
                RingdroidSelectActivity.this,
                R.string.default_ringtone_success_message,
                Toast.LENGTH_SHORT)
                .show();
    } else {
        RingtoneManager.setActualDefaultRingtoneUri(
                RingdroidSelectActivity.this,
                RingtoneManager.TYPE_NOTIFICATION,
                getUri());
        Toast.makeText(
                RingdroidSelectActivity.this,
                R.string.default_notification_success_message,
                Toast.LENGTH_SHORT)
                .show();
    }
}

private int getUriIndex(Cursor c) {
    int uriIndex;
    String[] columnNames = {
            MediaStore.Audio.Media.INTERNAL_CONTENT_URI.toString(),
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()
    };

    for (String columnName : Arrays.asList(columnNames)) {
        uriIndex = c.getColumnIndex(columnName);
        if (uriIndex >= 0) {
            return uriIndex;
        }
        // On some phones and/or Android versions, the column name includes the double quotes.
        uriIndex = c.getColumnIndex("\"" + columnName + "\"");
        if (uriIndex >= 0) {
            return uriIndex;
        }
    }
    return -1;
}

private Uri getUri() {
    //Get the uri of the item that is in the row
    Cursor c = mAdapter.getCursor();
    int uriIndex = getUriIndex(c);
    if (uriIndex == -1) {
        return null;
    }
    String itemUri = c.getString(uriIndex) + "/" +
            c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
    return (Uri.parse(itemUri));
}

private boolean chooseContactForRingtone(MenuItem item) {
    try {
        //Go to the choose contact activity
        Intent intent = new Intent(Intent.ACTION_EDIT, getUri());
        intent.setClassName(
                "unnion.neelay.beatbox.ringdroid",
                "unnion.neelay.beatbox.ringdroid.ChooseContactActivity");
        startActivityForResult(intent, REQUEST_CODE_CHOOSE_CONTACT);
    } catch (Exception e) {
        Log.e("Ringdroid", "Couldn't open Choose Contact window");
    }
    return true;
}

private void confirmDelete() {
    // See if the selected list item was created by Ringdroid to
    // determine which alert message to show
    Cursor c = mAdapter.getCursor();
    String artist = c.getString(c.getColumnIndexOrThrow(
            MediaStore.Audio.Media.ARTIST));
    CharSequence ringdroidArtist =
            getResources().getText(R.string.artist_name);

    CharSequence message;
    if (artist.equals(ringdroidArtist)) {
        message = getResources().getText(
                R.string.confirm_delete_ringdroid);
    } else {
        message = getResources().getText(
                R.string.confirm_delete_non_ringdroid);
    }

    CharSequence title;
    if (0 != c.getInt(c.getColumnIndexOrThrow(
            MediaStore.Audio.Media.IS_RINGTONE))) {
        title = getResources().getText(R.string.delete_ringtone);
    } else if (0 != c.getInt(c.getColumnIndexOrThrow(
            MediaStore.Audio.Media.IS_ALARM))) {
        title = getResources().getText(R.string.delete_alarm);
    } else if (0 != c.getInt(c.getColumnIndexOrThrow(
            MediaStore.Audio.Media.IS_NOTIFICATION))) {
        title = getResources().getText(R.string.delete_notification);
    } else if (0 != c.getInt(c.getColumnIndexOrThrow(
            MediaStore.Audio.Media.IS_MUSIC))) {
        title = getResources().getText(R.string.delete_music);
    } else {
        title = getResources().getText(R.string.delete_audio);
    }

    new AlertDialog.Builder(RingdroidSelectActivity.this)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(
                    R.string.delete_ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int whichButton) {
                            onDelete();
                        }
                    })
            .setNegativeButton(
                    R.string.delete_cancel_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int whichButton) {
                        }
                    })
            .setCancelable(true)
            .show();
}

private void onDelete() {
    Cursor c = mAdapter.getCursor();
    int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    String filename = c.getString(dataIndex);

    int uriIndex = getUriIndex(c);
    if (uriIndex == -1) {
        showFinalAlert(getResources().getText(R.string.delete_failed));
        return;
    }

    if (!new File(filename).delete()) {
        showFinalAlert(getResources().getText(R.string.delete_failed));
    }

    String itemUri = c.getString(uriIndex) + "/" +
            c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
    getContentResolver().delete(Uri.parse(itemUri), null, null);
}

private void showFinalAlert(CharSequence message) {
    new AlertDialog.Builder(RingdroidSelectActivity.this)
            .setTitle(getResources().getText(R.string.alert_title_failure))
            .setMessage(message)
            .setPositiveButton(
                    R.string.alert_ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int whichButton) {
                            finish();
                        }
                    })
            .setCancelable(false)
            .show();
}

private void onRecord() {
    try {
        Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse("record"));
        intent.putExtra("was_get_content_intent", mWasGetContentIntent);
        intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
        startActivityForResult(intent, REQUEST_CODE_EDIT);
    } catch (Exception e) {
        Log.e("Ringdroid", "Couldn't start editor");
    }
}

private void startRingdroidEditor() {
    Cursor c = mAdapter.getCursor();
    int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    String filename = c.getString(dataIndex);
    try {
        Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse(filename));
        intent.putExtra("was_get_content_intent", mWasGetContentIntent);
        intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
        startActivityForResult(intent, REQUEST_CODE_EDIT);
    } catch (Exception e) {
        Log.e("Ringdroid", "Couldn't start editor");
    }
}

private void refreshListView() {

    mExternalCursor = null;
    Bundle args = new Bundle();
    args.putString("filter", mFilter.getQuery().toString());
    getLoaderManager().restartLoader(EXTERNAL_CURSOR_ID, args, this);
}


private static final String[] EXTERNAL_COLUMNS = new String[]{
        MediaStore.Audio.Media._ID,
        MediaStore.Audio.Media.DATA,
        MediaStore.Audio.Media.TITLE,
        MediaStore.Audio.Media.ARTIST,
        MediaStore.Audio.Media.ALBUM,
        MediaStore.Audio.Media.IS_RINGTONE,
        MediaStore.Audio.Media.IS_ALARM,
        MediaStore.Audio.Media.IS_NOTIFICATION,
        MediaStore.Audio.Media.IS_MUSIC,
        "\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\""
};

private static final int EXTERNAL_CURSOR_ID = 1;

/* Implementation of LoaderCallbacks.onCreateLoader */
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    ArrayList<String> selectionArgsList = new ArrayList<String>();
    String selection;
    Uri baseUri;
    String[] projection;

    switch (id) {

        case EXTERNAL_CURSOR_ID:
            baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            projection = EXTERNAL_COLUMNS;
            break;
        default:
            return null;
    }

    if (mShowAll) {
        selection = "(_DATA LIKE ?)";
        selectionArgsList.add("%");
    } else {
        selection = "(";
        for (String extension : SoundFile.getSupportedExtensions()) {
            selectionArgsList.add("%." + extension);
            if (selection.length() > 1) {
                selection += " OR ";
            }
            selection += "(_DATA LIKE ?)";
        }
        selection += ")";

        selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
        selectionArgsList.add("%espeak-data/scratch%");
    }

    String filter = args != null ? args.getString("filter") : null;
    if (filter != null && filter.length() > 0) {
        filter = "%" + filter + "%";
        selection =
                "(" + selection + " AND " +
                        "((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
        selectionArgsList.add(filter);
        selectionArgsList.add(filter);
        selectionArgsList.add(filter);
    }

    String[] selectionArgs =
            selectionArgsList.toArray(new String[selectionArgsList.size()]);
    return new CursorLoader(
            this,
            baseUri,
            projection,
            selection,
            selectionArgs,
            MediaStore.Audio.Media.DEFAULT_SORT_ORDER
    );
}

/* Implementation of LoaderCallbacks.onLoadFinished */
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    switch (loader.getId()) {

        case EXTERNAL_CURSOR_ID:
            mExternalCursor = data;
            break;
        default:
            return;
    }
    // TODO: should I use a mutex/synchronized block here?
    if (mExternalCursor != null) {
        Cursor mergeCursor = new MergeCursor(new Cursor[]{mExternalCursor});
        mAdapter.swapCursor(mergeCursor);
    }
}

/* Implementation of LoaderCallbacks.onLoaderReset */
@Override
public void onLoaderReset(Loader<Cursor> loader) {
    // This is called when the last Cursor provided to onLoadFinished()
    // above is about to be closed.  We need to make sure we are no
    // longer using it.
    mAdapter.swapCursor(null);
}

@TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
            DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {

                        ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);


                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        onPermissionsNotGranted();

                    }
                    dialog.dismiss();
                    finish();
                    startActivity(getIntent());
                }
            };
            new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle(R.string.permissions_title)
                    .setMessage(R.string.read_ext_permissions_message)
                    .setPositiveButton(R.string.btn_continue, onClickListener)
                    .setNegativeButton(R.string.btn_cancel, onClickListener)
                    .setCancelable(false)
                    .show();
            return;
        }
        ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
        return;
    }

}

private void onPermissionsNotGranted() {
    Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
    Log.v("tom", "JERRY");
}

}

1 个答案:

答案 0 :(得分:6)

查看你的callstack它应该可以帮助你缩小你的问题范围。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
   at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
   at android.app.Activity.performCreate(Activity.java:6303)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)

例如,在你的callstack中,你首先得到被抛出的异常NullPointerException,它告诉你是什么导致它。

java.lang.String.equals(java.lang.Object)

因此,您有一个String,您尝试拨打.equals,但String为空。

现在,稍低一些,它会显示发生此问题的行号。

unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)

因此,您在.equals RingdroidSelectActivity onCreate123内呼叫.equals

但是,自您发布错误后,您的代码可能已更改,但该行周围没有getExternalStroage(),但我认为它可能是您的String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { showFinalAlert(getResources().getText(R.string.sdcard_readonly)); return; }

mWasGetContentIntent = Intent.ACTION_GET_CONTENT.equals(intent.getAction());

也许您没有此权限或其他权限。添加一些null检查,这将帮助您调试问题。

希望这有帮助!

编辑: 问题是this 所以答案是

private function openImage($file) {
    $image = file_get_contents($file);
    $img = imagecreatefromstring($image);
    $return $img;
}