java.lang.RuntimeException:无法实例化活动...(android studio)

时间:2018-04-24 13:55:36

标签: java android manifest

我在教程 todolist 中学习,但是有app的问题。模拟器和我的手机显示“ todolist4已停止”。 在“Sync”中全部为绿色,但在logcat中显示一些错误。我看了不同的答案,但他们没有帮助我。我试图在模拟器和应用程序中更改固件,但它也没有解决问题。

    public class MainActivity extends AppCompatActivity {//ActivityAppCompatActivity

List<ToDo> toDoList = new ArrayList<>();
FirebaseFirestore db;

RecyclerView listItem;
RecyclerView.LayoutManager layoutManager;

FloatingActionButton fab;

public MaterialEditText title, description;
public boolean isUpdate = false;
public String idUpdate = "";

ListItemAdapter adapter;

//AlertDialog dialog;
android.app.AlertDialog dialog=new SpotsDialog(MainActivity.this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(com.example.sud.todolist4.R.layout.activity_main);


    //Init FireStore
    db = FirebaseFirestore.getInstance();

    //View
    dialog = new SpotsDialog(this);
    title = (MaterialEditText)findViewById(com.example.sud.todolist4.R.id.title);
    description = (MaterialEditText)findViewById(com.example.sud.todolist4.R.id.description);
    fab = (FloatingActionButton)findViewById(com.example.sud.todolist4.R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Add New

            if(!isUpdate)
            {
                setData(title.getText().toString(), description.getText().toString());
            }
            else
            {
                updateData(title.getText().toString(), description.getText().toString());
                isUpdate = !isUpdate; //reset flag
            }

        }

    });

    listItem = (RecyclerView)findViewById(com.example.sud.todolist4.R.id.listTodo);
    listItem.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    listItem.setLayoutManager(layoutManager);

    loadData(); //load data from FireStore
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals("DELETE"))
        deleteItem(item.getOrder());
    return super.onContextItemSelected(item);
}
private void deleteItem(int index) {
    db.collection("ToDoList")
            .document(toDoList.get(index).getId())
            .delete()
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    loadData();
                }
            });
}
private void updateData(String title, String description) {
    db.collection("ToDoList").document(idUpdate)
            .update("title",title,"descripton",description)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Toast.makeText(MainActivity.this, "Updated !", Toast.LENGTH_SHORT).show();
                }
            });

    //Realtime update refresh data;
    db.collection("ToDoList").document(idUpdate)
            .addSnapshotListener(new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                    loadData();
                }
            });

}
private void setData(String title, String description) {
    //Random id
    String id = UUID.randomUUID().toString();
    Map<String, Object> todo = new HashMap<>();
    todo.put("id", id );
    todo.put("title", title );
    todo.put("description", description );

    db.collection("ToDoList").document(id)
            .set(todo).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            //Refresh data;
            loadData();
        }
    });
}
private void loadData() {
    dialog.show();
    if(toDoList.size() > 0)
        toDoList.clear(); //Remove old value
    db.collection("ToDoList")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>()
            {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task)
                {
                    for(DocumentSnapshot doc:task.getResult())
                    {
                        ToDo todo = new ToDo(doc.getString("id"),
                                doc.getString("title"),
                                doc.getString("description"));
                        toDoList.add(todo);
                    }
                    adapter = new ListItemAdapter(MainActivity.this,toDoList);
                    listItem.setAdapter(adapter);
                    dialog.dismiss();

                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
}}

logcat的

04-24 16:33:44.697 16627-16627/com.example.sud.todolist4 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sud.todolist4, PID: 16627
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.sud.todolist4/com.example.sud.todolist4.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    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.IllegalStateException: System services not available to Activities before onCreate()
    at android.app.Activity.getSystemService(Activity.java:5915)
    at android.app.Dialog.<init>(Dialog.java:183)
    at android.app.AlertDialog.<init>(AlertDialog.java:201)
    at android.app.AlertDialog.<init>(AlertDialog.java:197)
    at dmax.dialog.SpotsDialog.<init>(SpotsDialog.java:39)
    at dmax.dialog.SpotsDialog.<init>(SpotsDialog.java:25)
    at com.example.sud.todolist4.MainActivity.<init>(MainActivity.java:55)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
    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)

清单

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-library android:name="com.google.android.maps" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

2 个答案:

答案 0 :(得分:0)

如果未创建活动,则无法使用MainActivity.this引用mainAnctivity。在调用onCreate之后创建活动。这就是你得到这个错误的原因。

更改此行:

android.app.AlertDialog dialog=new SpotsDialog(MainActivity.this);

为:

android.app.AlertDialog dialog;

并在onCreate中将其初始化为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(com.example.sud.todolist4.R.layout.activity_main);

    dialog=new SpotsDialog(MainActivity.this);

    //Init FireStore
    db = FirebaseFirestore.getInstance();
...

答案 1 :(得分:0)

错误消息非常清楚:System services not available to Activities before onCreate()。在堆栈跟踪中,您可以看到它由SpotsDialog的构造函数调用。

替换

//AlertDialog dialog;
android.app.AlertDialog dialog=new SpotsDialog(MainActivity.this);

//AlertDialog dialog;
android.app.AlertDialog dialog;

当你在onCreate方法中再次初始化它时,这个初始化是无用的。