如何检查数据库连接采用的是Android成功与否? [英] How to check if the database connection is successful or not in android?

查看:164
本文介绍了如何检查数据库连接采用的是Android成功与否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试使用数据库中的几个codeS。我试图使用现有的数据库,我复制到文件夹中的资产。我希望我的弹出来显示一个SQL查询的结果。在code我试图为

I have tried several codes on using database. i am trying to use an existing database which i copy to assets folder. I want my pop up to display the outcome of an sql query. The code i have tried is

package com.example.singlepop;

import java.io.IOException;
import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.view.Menu;

import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class Single extends Activity {
    PopupWindow popUp;
     LinearLayout layout;
     TextView tv;
     LayoutParams params;
     LinearLayout mainLayout;
     Button but;
     boolean click = true;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DataBaseHelper myDbHelper = new DataBaseHelper(this);
         try {

             myDbHelper.createDataBase();

             } catch (IOException ioe) {

             throw new Error("Unable to create database");

             }
         try {

             myDbHelper.openDataBase();

             }catch(SQLException sqle){

             throw sqle;

             }

          popUp = new PopupWindow(this);
          layout = new LinearLayout(this);
          mainLayout = new LinearLayout(this);



          final Calendar cld = Calendar.getInstance();

          int time = cld.get(Calendar.HOUR_OF_DAY);
          if(time==20)
          {
              tv = new TextView(this);
              but = new Button(this);

          but.setText("Click me for pop up");
          but.setOnClickListener(new OnClickListener() {

           public void onClick(View v) {
            if (click) {
             popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
             popUp.update(50, 50, 300, 80);
             click = false;
            } else {
             popUp.dismiss();
             click = true;
            }
           }

          });
          params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
          layout.setOrientation(LinearLayout.VERTICAL);
          //tv.setText("Time is 8 pm");

          // display the outcome of the query
          tv.setText(myDbHelper.thought());


          layout.addView(tv, params);
          popUp.setContentView(layout);
          // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
          mainLayout.addView(but, params);
          setContentView(mainLayout);
          }
          else
          {
              tv.setText("NO TIME");
          }




    }




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

}

这code给了我成功弹出。我有一个数据库MyDatabase的生成的N复制到文件夹中的资产。我DataBaseHelper类是

This code gives me successful pop up. I have a database "MyDatabase" created n copied on to assets folder. My DataBaseHelper class is

package com.example.singlepop;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper {
     private static final int _id = 1;

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.singlepop/databases/";

    private static String DB_NAME = "MyDatabase";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    private static String DB_TABLE = "Totlist";

    private static final String tot = null;

    String des=tot;

    /**
      * Constructor
      * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
      */
    public DataBaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
    }

     /**
      * Creates a empty database on the system and rewrites it with your own database.
      * */
    public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
    //do nothing - database already exist
    }else{

    //By calling this method and empty database will be created into the default system path
    //of your application so we are gonna be able to overwrite that database with our database.
    this.getReadableDatabase();

    try {

    copyDataBase();

    } catch (IOException e) {

    throw new Error("Error copying database");


    }

    }
    }   

     /**
      * Check if the database already exist to avoid re-copying the file each time you open the application.
      * @return true if it exists, false if it doesn't
      */
    private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
    String myPath = DB_PATH + DB_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

    //database does't exist yet.

    }

    if(checkDB != null){

    checkDB.close();

    }

    return checkDB != null ? true : false;
    }

     /**
      * Copies your database from your local assets-folder to the just created empty database in the
      * system folder, from where it can be accessed and handled.
      * This is done by transfering bytestream.
      * */
    private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
    myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

    }

     public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }

     @Override
     public synchronized void close() {

     if(myDataBase != null)
     myDataBase.close();

     super.close();

     }

     @Override
     public void onCreate(SQLiteDatabase db) {

     }

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

     }

         // This function should return the outcome of the query but below code is wrong
     public String thought()
     {

         String quer="Hello";
         String sql = "SELECT * FROM option WHERE id = 1";
         Cursor check = myDataBase.rawQuery(sql, null);
         quer=String.valueOf(check);
        return quer;

     }



}

rawQuery 返回光标键入这我不使用的setText无法显示。我该怎么办,这样我可以得到查询结果来显示。B在弹出。
当我运行此我得到了的logcat 许多错误。它可能是与连接问题。

rawQuery returns a Cursor type which i am not able display using setText. what should I do so that I can get the outcome of the query to b displayed in the pop up. when i run this i get many errors in logcat. it could be problem with connectivity.

08-28 20:00:57.396: E/Trace(841): error opening trace file: No such file or directory (2)
08-28 20:00:59.003: E/SQLiteLog(841): (14) cannot open file at line 30176 of [00bb9c9ce4]
08-28 20:00:59.023: E/SQLiteLog(841): (14) os_unix.c:30176: (2) open(/data/data/com.example.singlepop/databases/MyDatabase) - 
08-28 20:00:59.173: E/SQLiteDatabase(841): Failed to open database '/data/data/com.example.singlepop/databases/MyDatabase'.
08-28 20:00:59.173: E/SQLiteDatabase(841): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

还是有很多误区

推荐答案

您得到的错误消息表明数据库文件 /data/data/com.example.singlepop/databases/MyDatabase 不存在。你可以检查吗?

The error messages you get indicate that a database file /data/data/com.example.singlepop/databases/MyDatabase does not exist. Can you check that?

此外,一旦这个作品中,光标重新presents你从查询得到的结果。多个记录可以退换。你首先将光标定位到要读取,然后您可以访问各个列的行。例如(离开了所有的错误处理和假设你的表中有一个名为列 COL1

Also, once this works, the Cursor represents all the results you get from the query. More than one record can be returned. You first position the cursor to the row you want to read and then you have access to the individual columns. For example (leaving out all error handling and assuming that your table has a column named col1):

check.moveToFirst();
String col1 = check.getString(check.getColumnIndex("col1"));

这篇关于如何检查数据库连接采用的是Android成功与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆