此代码用于在应用程序中从移动设备获取帐户
package com.example.lenovo.email;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private static String[] userEmailId = null;
private static String mDeviceId = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.spinner);
String[] email_a=null;
email_a=setUserEmailId(this);
if(email_a == null)
{
throw new RuntimeException("null");
}
else {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, email_a);
dropdown.setAdapter(adapter);
EditText edit = (EditText) findViewById(R.id.editText2);
// edit.setText(setUserEmailId(this));
}
}
//used to get accounts in dropdown list
private static String[] setUserEmailId(Context mContext) {
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(mContext).getAccounts();
int i=0;
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
userEmailId[i] = account.name;
Log.d("Email",userEmailId[i]);
i++;
}
}
return userEmailId;
}
}
代码提供运行时异常 当我运行此代码时,不幸的是应用程序已停止 我无法解决这个异常......
答案 0 :(得分:1)
问题是您尚未正确初始化userEmailId
,当您尝试向其中添加元素时,它仍为null
。
我建议您使用ArrayList
代替String
数组:
private List<String> getUserEmailId(Context context) {
List<String> list = new ArrayList<>();
Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
list.add(account.name);
}
}
return list;
}
答案 1 :(得分:0)
为什么使用RuntimeException
而不解决它?我的意思是你需要捕捉异常,然后用它做点什么:)
我认为setUserEmailId
方法返回null。让检查代码的逻辑试图找到电子邮件。当您没有找到电子邮件时需要使用 Logcat ,RuntimeException
是强制停止应用的主要原因:)
if(email_a == null){
throw new RuntimeException("null");
}