无法打开数据库(Android Studio)

时间:2015-07-29 05:21:57

标签: android database sqlite

我是Android编程的新手。 在这里,我想制作一个可以记录我们所有现金流的应用程序。 但是当我想制作一个具有数据库价值的Spinner时,我遇到了一些问题。 当我运行该程序时,Android Studio中的报告部分会给我一个报告" android.database.sqlite.SQLiteCantOpenDatabaseException:未知错误(代码14):无法打开数据库", 我对这个错误有点沮丧。我谷歌搜索它,但仍然无法找到解决方法,或者因为我不明白教程说的内容。请高手帮我解决一下这个错误。 非常感谢。

NB。这是Main_Activity(创建微调器的位置)的源代码

public class MainActivity extends ActionBarActivity {

private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
DatabaseHelper dbHelper = new DatabaseHelper(this);
Spinner selectCategory;
//ArrayAdapter<String> adapterCategory;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    onButtonClickButtonListener();
    select_spinner_Category();


}

/*ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();

Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);*/

public void select_spinner_Category (){
    ArrayList<String> arrayCategory = new ArrayList<String>();
    arrayCategory = dbHelper.getAllCategory();
    selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
    ArrayAdapter adapterCategory  = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayCategory);
   // adapterCategory = new ArrayList<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryList);
    adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    selectCategory.setAdapter(adapterCategory);
    selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    return true;
}

public void onButtonClickButtonListener(){
    BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
    BtnINewTrans.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
                    startActivity(intentNewTrans);
                }
            }
    );

    BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
    BtnIViewCash.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
                    startActivity(intentViewCash);
                }
            }
    );

    BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
    BtnIAddCateg.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
                    startActivity(intentAddCateg);
                }
            }
    );

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

这个是Database_Helper

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String MyVillageSoftware = "MyVillageSoftware";
public static final String DATABASE_NAME = "Cashflow.db";
public static final String TABLE_Categ_NAME = "category_table";
public static final String COL1 = "CategId";
public static final String COL2 = "CategName";
public static final String COL3 = "Note";
public static final String COL4 = "Currency";
SQLiteDatabase db;


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 2);


}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("Create table " + TABLE_Categ_NAME +
            " (CategID Integer PRIMARY KEY AUTOINCREMENT, " +
            "CategName Text," +
            " Note Text," +
            " Currency Text)");

}

public boolean insertCategData(String categname, String note, String currency){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, categname);
    contentValues.put(COL3, note);
    contentValues.put(COL4, currency);
    long result = db.insert(TABLE_Categ_NAME, null, contentValues);
     if (result == 1)
         return true;
     else
         return false;

}

public ArrayList<String> getAllCategory() {

    ArrayList<String> AllCategoryList = new ArrayList<String>();
    try {
        db = SQLiteDatabase.openOrCreateDatabase(DATABASE_NAME, null, null);
        Cursor allrows = db.rawQuery("SELECT * FROM " + TABLE_Categ_NAME, null);
        System.out.println("COUNT : " + allrows.getCount());

        if (allrows.moveToFirst()) {
            do {

                String ID = allrows.getString(0);
                String Categ = allrows.getString(1);
                String Note = allrows.getString(2);
                String Curr = allrows.getString(3);
                AllCategoryList.add(Categ);

            } while (allrows.moveToNext());
        }
        allrows.close();
        db.close();
    } catch (Exception e) {


    }
    return AllCategoryList;
}

/*public ArrayList<String>getAllCategory(){
    ArrayList<String> AllCategoryList = new ArrayList<String>();
    SQLiteDatabase db = this.getReadableDatabase();
    String selectCateg="Select * FROM " +TABLE_Categ_NAME;
    Cursor cursor = db.rawQuery(selectCateg, null);
    if(cursor.getCount()>0){
        while (cursor.moveToNext()){
            String categname1=cursor.getString(cursor.getColumnIndex(COL2));
            AllCategoryList.add(COL2);

        }return AllCategoryList;
    }

    return AllCategoryList;

}*/


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " +TABLE_Categ_NAME);
    onCreate(db);

}

}

1 个答案:

答案 0 :(得分:0)

  1. 首先创建DBHelper类。

    public class DBAdapter {     私有DBHelper dbHelper;     私有上下文;     私有SQLiteDatabase db;

    public DBAdapter(Context context) {
        this.context = context;
        dbHelper = new DBHelper(context);
    }
    
    public void open() {
        db = dbHelper.getWritableDatabase();
    }
    
    public void close() {
        db.close();
    }
    
    public long insertBook(Book book) {
        ContentValues values = new ContentValues();
        values.put(DBHelper.TITLE, book.getTitle());
        values.put(DBHelper.AUTHOR, book.getAuthor());
        values.put(DBHelper.CATEGORY, book.getCategory());
        values.put(DBHelper.ISBN, book.getISBN());
        values.put(DBHelper.PRICE, book.getPrice());
    
        long inserted = db.insert(DBHelper.TABLE_NAME, null, values);
    
        return inserted;
    }
    
    public ArrayList<Book> getAllBooks() {
        ArrayList<Book> allBooks = null;
        String[] columns = { DBHelper.TITLE, DBHelper.AUTHOR };
    
        Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null,
                null, null);
        // select * from books;
        if (cursor != null && cursor.getCount() > 0) {
            int size = cursor.getCount();
            cursor.moveToFirst();
            allBooks = new ArrayList<Book>();
            for (int i = 0; i < size; i++) {
                String title = cursor.getString(cursor
                        .getColumnIndex(DBHelper.TITLE));
                String author = cursor.getString(cursor
                        .getColumnIndex(DBHelper.AUTHOR));
                String category = cursor.getString(cursor
                        .getColumnIndex(DBHelper.CATEGORY));
                String ISBN = cursor.getString(cursor
                        .getColumnIndex(DBHelper.ISBN));
                double price = cursor.getDouble(cursor
                        .getColumnIndex(DBHelper.PRICE));
                allBooks.add(new Book(title, author, category, ISBN, price));
                cursor.moveToNext();
            }
        }
    
        cursor.close();
    
        return allBooks;
    }
    

    }

  2. 然后创建DBAdapter

    public class DBAdapter {
    private DBHelper dbHelper;
    private Context context;
    private SQLiteDatabase db;
    
    public DBAdapter(Context context) {
        this.context = context;
        dbHelper = new DBHelper(context);
    }
    
    public void open() {
        db = dbHelper.getWritableDatabase();
    }
    
    public void close() {
        db.close();
    }
    
    public long insertBook(Book book) {
        ContentValues values = new ContentValues();
        values.put(DBHelper.TITLE, book.getTitle());
        values.put(DBHelper.AUTHOR, book.getAuthor());
        values.put(DBHelper.CATEGORY, book.getCategory());
        values.put(DBHelper.ISBN, book.getISBN());
        values.put(DBHelper.PRICE, book.getPrice());
    
        long inserted = db.insert(DBHelper.TABLE_NAME, null, values);
    
        return inserted;
    }
    
    public ArrayList<Book> getAllBooks() {
        ArrayList<Book> allBooks = null;
        String[] columns = { DBHelper.TITLE, DBHelper.AUTHOR };
    
        Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null,
                null, null);
        // select * from books;
        if (cursor != null && cursor.getCount() > 0) {
            int size = cursor.getCount();
            cursor.moveToFirst();
            allBooks = new ArrayList<Book>();
            for (int i = 0; i < size; i++) {
                String title = cursor.getString(cursor
                        .getColumnIndex(DBHelper.TITLE));
                String author = cursor.getString(cursor
                        .getColumnIndex(DBHelper.AUTHOR));
                String category = cursor.getString(cursor
                        .getColumnIndex(DBHelper.CATEGORY));
                String ISBN = cursor.getString(cursor
                        .getColumnIndex(DBHelper.ISBN));
                double price = cursor.getDouble(cursor
                        .getColumnIndex(DBHelper.PRICE));
                allBooks.add(new Book(title, author, category, ISBN, price));
                cursor.moveToNext();
            }
        }
    
        cursor.close();
    
        return allBooks;
    }
    

    }

  3. DBAdapter类在DBhelper类中创建一个对象并打开exit数据库,否则会创建一个新的数据库。

    1. 最终可以通过这种方式获取数据表单数据库

      public class MainActivity extends Activity implements OnClickListener {
      
      private EditText etTitle, etAuthor, etCategory, etISBN, etPrice;
      private Button btnSave, btnView;
      private DBAdapter dbAdapter;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
          dbAdapter = new DBAdapter(this);
          etTitle = (EditText) findViewById(R.id.etTitle);
          etAuthor = (EditText) findViewById(R.id.etAuthor);
          etCategory = (EditText) findViewById(R.id.etCategory);
          etISBN = (EditText) findViewById(R.id.etISBN);
          etPrice = (EditText) findViewById(R.id.etPrice);
      
          btnSave = (Button) findViewById(R.id.btnSave);
          btnView = (Button) findViewById(R.id.btnView);
          btnSave.setOnClickListener(this);
          btnView.setOnClickListener(this);
      
      }
      
      @Override
      public void onClick(View v) {
          switch (v.getId()) {
          case R.id.btnSave:
              String title = etTitle.getText().toString();
              String author = etAuthor.getText().toString();
              String category = etCategory.getText().toString();
              String ISBN = etISBN.getText().toString();
              double price = Double.parseDouble(etPrice.getText().toString());
      
              dbAdapter.open();
              long inserted = dbAdapter.insertBook(new Book(title, author,
                      category, ISBN, price));
              dbAdapter.close();
      
              if (inserted >= 0) {
                  Toast.makeText(getApplicationContext(), "Insert Successful",
                          Toast.LENGTH_LONG).show();
              }
      
              break;
          case R.id.btnView:
              // retrieve a list of books
              dbAdapter.open();
              ArrayList<Book> books = dbAdapter.getAllBooks();
              dbAdapter.close();
              for (Book book : books) {
                  Toast.makeText(getApplicationContext(), book.toString(),
                          Toast.LENGTH_LONG).show();
              }
              // view
              break;
      
          default:
              break;
          }
      
      }
      

      }

    2. ////////////////////////

      public class Book {
          private String title;
          private String author;
          private String category;
          private String ISBN;
          private double price;
      
          public Book(String title, String author, String category, String iSBN,
                  double price) {
              super();
              this.title = title;
              this.author = author;
              this.category = category;
              ISBN = iSBN;
              this.price = price;
          }
      
          public String getTitle() {
              return title;
          }
      
          public void setTitle(String title) {
              this.title = title;
          }
      
          public String getAuthor() {
              return author;
          }
      
          public void setAuthor(String author) {
              this.author = author;
          }
      
          public String getCategory() {
              return category;
          }
      
          public void setCategory(String category) {
              this.category = category;
          }
      
          public String getISBN() {
              return ISBN;
          }
      
          public void setISBN(String iSBN) {
              ISBN = iSBN;
          }
      
          public double getPrice() {
              return price;
          }
      
          public void setPrice(double price) {
              this.price = price;
          }
      
          public String toString() {
              return "[" + title + " " + author + " " + category + " " + ISBN + " "
                      + price + "]";
          }
      
      }