【问题标题】:App crashing on buttonclick how can I solved it android studio应用程序在按钮单击时崩溃我该如何解决它android studio
【发布时间】:2018-08-30 21:24:00
【问题描述】:

代码如下:

button.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick (View view){
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}); return view;}

public void but(View v) {
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case RESULT_PICK_CONTACT:
                contactPicked(data);
                break;
        }
    } else {
        Log.e("MainActivity", "Failed to pick contact");
    }
}

private void contactPicked(Intent data) {
    Cursor cursor = null;
    try {
        String phoneNo = null;
        String name = null;
        Uri uri = data.getData();
        cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        phoneNo = cursor.getString(phoneIndex);
        name = cursor.getString(nameIndex);
        if (phoneNo.startsWith("+")) {
            if (phoneNo.length() == 13) {
                String str_getMOBILE = phoneNo.substring(4);
                editText.setText(("0") + str_getMOBILE);
            }
            if (phoneNo.length() == 16) {
                String str_getMOBILE = phoneNo.substring(4);
                editText.setText(("0") + str_getMOBILE);
            }
        } else {
            editText.setText(phoneNo);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • Masresha 您的代码中的任何引用都可能为空,或者只是您的光标为空,或者您没有足够的权限来使用您打算使用的服务。但关键是,如果您查看 Logcat 输出,则很难从代码中分辨出来。在 Android Studio 中找到底部的选项卡,并在那里查找您的致命错误。祝你好运!
  • 嗨,Masresha,如果可能的话,能否请您发布您的整个课程和日志?
  • 您需要检查崩溃的堆栈跟踪,它会引导您找到崩溃的确切行,请参阅:stackoverflow.com/questions/3988788/…

标签: android fragment onclicklistener android-contacts buttonclick


【解决方案1】:

您可能会面临以下导致崩溃的任何情况:

  • 您的按钮未在主类的 onCreate() 方法中正确声明和启动。所以请检查您的onCreate() 方法中是否有以下代码:

    Button button = (Button) findViewById(R.id.button);

  • 我相信您的应用会从用户设备中读取联系人。在这种情况下,请检查您是否具有读取联系人的必要权限。为此,只需检查AndroidManifest.xml 文件中是否包含以下行:

    <uses-permission android:name="android.permission.READ_CONTACTS" />

  • 检查您是否有权调用适当的意图。

您的logcat 跟踪将包含导致崩溃的确切代码行和错误代码。因此,如果您在此处粘贴 logcat 信息,您可以获得帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 2020-08-26
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多