无法从第二个类访问数据库帮助程序

时间:2017-06-11 02:43:38

标签: java android database

我在我的应用程序中创建了CurrentChanceDatabse类。它扩展了SQLiteOpenHelper。我已经制定了一些评估表格和数据的方法。 当我使用以下代码访问CurrentChanceDatabase类时,它在MainActivity(在启动应用程序时启动的默认值)中运行良好。所有方法都运行良好。

public class MainActivity extends AppCompatActivity {
CurrentChanceDatabase db;  //this line
//more declarations
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = new CurrentChanceDatabase(this);  //and this line
//more onCreate functions
}

现在,我想从第二个活动访问同一个数据库。我使用相同的两行连接到我的数据库类,但第二个活动启动时应用程序崩溃。我最后解释了我的目标。

代码和logcat:

MainActivity.java

package com.example.snehit.probablity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
CurrentChanceDatabase db;
EditText nameOfExperiment;
EditText noOfOutcomes;
Button ContinueBt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = new CurrentChanceDatabase(this);
    ContinueBt = (Button) findViewById(R.id.continueButtton);
    registerExperimentFunction();
    db.deleteAllData();  //see the very end of this question to know about this
    force(); //continues to the seconnd class without entring any experiment. will be used for debugging once the app works.

}

public void force(){
    Button bt = (Button) findViewById(R.id.force);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(MainActivity.this, CurrentChanceDatabase.class);
            db.close();
            startActivity(myIntent);
        }
    });
}

public void registerExperimentFunction(){
   ContinueBt.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           nameOfExperiment = (EditText) findViewById(R.id.nameOfExperiment);
           noOfOutcomes = (EditText) findViewById(R.id.noOfChance);
           String nameOfExperimentString = nameOfExperiment.getText().toString();
           Integer noOfOutcomesInt = Integer.parseInt(noOfOutcomes.getText().toString());
           Boolean success = db.registerExperiment(nameOfExperimentString, noOfOutcomesInt);
           if (success)
               Toast.makeText(MainActivity.this,"Done Success", Toast.LENGTH_SHORT).show();
           else

               Toast.makeText(MainActivity.this,"UnDone UnSuccess", Toast.LENGTH_SHORT).show();
           Intent myIntent = new Intent(MainActivity.this, CurrentChanceDatabase.class);
           db.close();
           startActivity(myIntent);

       }
   });
}

}

AddNames.java

package com.example.snehit.probablity;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * Created by Snehit on 6/10/2017.
 */
public class AddNames extends AppCompatActivity {
CurrentChanceDatabase db;
LinearLayout ll;
EditText editText;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_names);
    db = new CurrentChanceDatabase(this);
    addTextBox();
}


public void addTextBox(){
    ll = (LinearLayout) findViewById(R.id.linearLayout1);
    Cursor res = db.getAllChance();
    //StringBuffer buffer = new StringBuffer();
    String chance = res.getString(res.getColumnIndex("CHANCE"));
    Integer chanceInt = Integer.parseInt(chance);
    //buffer.append(res.getString(0) + "\n");
    for(int i=0;i<chanceInt;i++)
    {
        editText = new EditText(this);
        editText.setHint("Name here");
       ll.addView(editText);
    }
}
}

CurrentChanceDatabse.java

package com.example.snehit.probablity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Snehit on 6/9/2017.
  */
public class CurrentChanceDatabase extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "probablity.db";
public static final String TABLE_NAME = "experiments";

public CurrentChanceDatabase(Context context) {
    super(context,DATABASE_NAME, null, 1);
    SQLiteDatabase db = this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,CHANCE TEXT, COMPLETED INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public boolean registerExperiment(String name, Integer chance){

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("NAME", name);
    contentValues.put("CHANCE", chance);
    contentValues.put("COMPLETED", 0);

    long result =  db.insert(TABLE_NAME, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;
}

public Integer deleteData(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?", new String[] {id});
}

public void deleteAllData(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_NAME);
    db.execSQL("vacuum");
}

public Cursor getAllChance(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from where COMPLETED = 0" + TABLE_NAME, null);
    return res;
}

}

add_names.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout1">

</LinearLayout>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.snehit.probablity.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Name"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/nameOfExperiment"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="No. of outcomes"
    android:id="@+id/textView2"
    android:layout_below="@+id/nameOfExperiment"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/noOfChance"
    android:layout_below="@+id/textView2"
    android:layout_centerHorizontal="true"
    android:inputType="number" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Continue"
    android:id="@+id/continueButtton"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Force continue"
    android:id="@+id/force"
    android:layout_below="@+id/continueButtton"
    android:layout_alignStart="@+id/textView2" />

在MainActivity上按下继续按钮时出现Logcat错误:

799/com.example.snehit.probablity E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.example.snehit.probablity, PID: 1799
                                                                         android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.snehit.probablity/com.example.snehit.probablity.CurrentChanceDatabase}; have you declared this activity in your AndroidManifest.xml?
                                                                             at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                                                                             at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                                                                             at android.app.Activity.startActivityForResult(Activity.java:4225)
                                                                             at android.app.Activity.startActivityForResult(Activity.java:4183)
                                                                             at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
                                                                             at android.app.Activity.startActivity(Activity.java:4522)
                                                                             at android.app.Activity.startActivity(Activity.java:4490)
                                                                             at com.example.snehit.probablity.MainActivity$2.onClick(MainActivity.java:56)
                                                                             at android.view.View.performClick(View.java:5637)
                                                                             at android.view.View$PerformClick.run(View.java:22429)
                                                                             at android.os.Handler.handleCallback(Handler.java:751)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
06-10 21:43:46.216 795-807/system_process W/ActivityManager:   Force finishing activity com.example.snehit.probablity/.MainActivity

从MainActivity类加载数据库类时,不会出现此错误。

我想做什么

用户从activity_main.xml(MainActivity.java)注册实验。当用户点击继续时,名称以及机会数将被放入数据库中。除了数据库函数之外,还会传递一个intent来启动AddNames.java。此活动从数据库获取no。未完成实验的数据库的机会*并创建相同的否。 add_names.xml中的EditTexts,以便用户可以为其命名。

*未完成的实验/ deleteAllData(); - 当用户命名实验的所有机会时,它将被标记为已完成,并且表中的“COMPLETED”值将从0增加到1.此功能旨在添加到AddNames.java中,但是那件事甚至拒绝发布,我还没有把那段代码。从MainActivity.java添加新实验时,其“COMPLETED”值为零。所有其他实验的'COMPLETED'值为1.(一旦开发进展,这个东西的代码将被放置)。因此,为了确保只有'COMPLETED'值为0的实验,我会在应用启动时删除所有条目。为了获得未完成的实验,我使用'WHERE COMPLETED = 0'查询数据库。 谢谢!

编辑:

我的Android清单xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snehit.probablity">

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

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



<activity android:name="com.example.snehit.probablity.AddNames" android:label="@string/app_name">


</activity>

我忘了在之前添加这个......

再次感谢你!

2 个答案:

答案 0 :(得分:2)

  

但第二个活动启动时应用程序崩溃。

这显然意味着第二个活动AddNames未在项目清单中注册。因此得到此错误:

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.snehit.probablity/com.example.snehit.probablity.CurrentChanceDatabase}; have you declared this activity in your AndroidManifest.xml?

确保在清单

中注册AddNames活动

将此添加到您的manifest.xml

<activity android:name="AddNames" >

答案 1 :(得分:0)

在使用ide中的调试工具后,我自己发现了错误。错误发生在MainActivity.java中,我在其中设置了按钮的onClick函数。

意图的代码应该是

Intent myIntent = new Intent(MainActivity.this, AddNames.class);

我的初始代码在点击时启动CurrentChanceDatabase.java,我不想这样做。

另外,在addTextBox()函数中获取AddNames.java类中未完成实验的机会数的代码是错误的。没有。必须使用res.moveToNext()作为条件,使用while循环检索机会。在循环中,必须检索no.of机会并将其转换为整数,以便在添加文本框的循环中使用。