Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取所选id';android sqlite数据库中的s值?_Android_Sqlite - Fatal编程技术网

如何获取所选id';android sqlite数据库中的s值?

如何获取所选id';android sqlite数据库中的s值?,android,sqlite,Android,Sqlite,我使用AndroidSQLite数据库创建了一个示例应用程序,我的要求是(请不要点击此链接)。我使用下面的代码来实现这一点 MainClass.java public class MainClass extends Activity implements OnClickListener { Button NUM_INPUT; EditText enter_NUM; int number; DatabaseHandler db = new DatabaseHand

我使用AndroidSQLite数据库创建了一个示例应用程序,我的要求是(请不要点击此链接)。我使用下面的代码来实现这一点

MainClass.java

public class MainClass extends Activity implements OnClickListener {

    Button NUM_INPUT;
    EditText enter_NUM;
    int number;
    DatabaseHandler db = new DatabaseHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sai_answers_home);
        NUM_INPUT = (Button) findViewById(R.id.answerButton);
        enter_NUM = (EditText) findViewById(R.id.saiAnssersEditText);
        NUM_INPUT.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.answerButton) {
             number = Integer.parseInt(this.enter_NUM.getText().toString());
            // /System.out.println("EDITTEXTVALUE" + number);
            Log.d("Reading: ", "Reading all contacts..");
            List<Contact> contacts = db.getAllContacts(number);
            for (Contact cn : contacts) {
                String log = "Id: " + cn.getID() + " ,Name: " + cn.getName();
                // Writing Contacts to log
                Log.d("Name: ", log);
            }
            db.close();
        }
    }
}
   public class DatabaseHandler extends SQLiteOpenHelper {

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

        private static String DB_NAME = "answers";

        private SQLiteDatabase myDataBase;

        private final Context myContext;
        String myPath;

        /**
         * Constructor Takes and keeps a reference of the passed context in order to
         * access to the application assets and resources.
         * 
         * @param context
         */
        public DatabaseHandler(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 {
                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
            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) {

        }

        // Add your public helper methods to access and get content from the
        // database.
        // You could return cursors by doing "return myDataBase.query(....)" so it'd
        // be easy
        // to you to create adapters for your views.

        public List<Contact> getAllContacts(int muNumber) {
            List<Contact> contactList = new ArrayList<Contact>();
            // Select All Query
            String selectQuery = "SELECT * FROM ANSWER WHERE ID= " + muNumber;
    System.out.println("QUERY STRING IS......>>>>>> " + selectQuery);

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    Contact contact = new Contact();
                    contact.setID(Integer.parseInt(cursor.getString(0)));
                    contact.setName(cursor.getString(1));
                    // contact.setPhoneNumber(cursor.getString(2));
                    // Adding contact to list
                    contactList.add(contact);
                } while (cursor.moveToNext());
            }

            // return contact list
            return contactList;
        }
}
public类MainClass扩展活动实现OnClickListener{
按钮数输入;
编辑文本输入_NUM;
整数;
DatabaseHandler db=新的DatabaseHandler(此);
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.sai_answers_home);
NUM_INPUT=(按钮)findviewbyd(R.id.answerButton);
输入_NUM=(EditText)findViewById(R.id.saiAnssersEditText);
NUM_INPUT.setOnClickListener(此);
}
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
if(v.getId()==R.id.answerButton){
number=Integer.parseInt(this.enter_NUM.getText().toString());
///System.out.println(“EDITTEXTVALUE”+数字);
日志d(“读取:”,“读取所有联系人…”);
列表联系人=db.getAllContacts(编号);
用于(联系人cn:联系人){
字符串log=“Id:”+cn.getID()+”,名称:“+cn.getName();
//将联系人写入日志
Log.d(“名称:”,Log);
}
db.close();
}
}
}
DataBaseHandler.java

public class MainClass extends Activity implements OnClickListener {

    Button NUM_INPUT;
    EditText enter_NUM;
    int number;
    DatabaseHandler db = new DatabaseHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sai_answers_home);
        NUM_INPUT = (Button) findViewById(R.id.answerButton);
        enter_NUM = (EditText) findViewById(R.id.saiAnssersEditText);
        NUM_INPUT.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.answerButton) {
             number = Integer.parseInt(this.enter_NUM.getText().toString());
            // /System.out.println("EDITTEXTVALUE" + number);
            Log.d("Reading: ", "Reading all contacts..");
            List<Contact> contacts = db.getAllContacts(number);
            for (Contact cn : contacts) {
                String log = "Id: " + cn.getID() + " ,Name: " + cn.getName();
                // Writing Contacts to log
                Log.d("Name: ", log);
            }
            db.close();
        }
    }
}
   public class DatabaseHandler extends SQLiteOpenHelper {

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

        private static String DB_NAME = "answers";

        private SQLiteDatabase myDataBase;

        private final Context myContext;
        String myPath;

        /**
         * Constructor Takes and keeps a reference of the passed context in order to
         * access to the application assets and resources.
         * 
         * @param context
         */
        public DatabaseHandler(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 {
                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
            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) {

        }

        // Add your public helper methods to access and get content from the
        // database.
        // You could return cursors by doing "return myDataBase.query(....)" so it'd
        // be easy
        // to you to create adapters for your views.

        public List<Contact> getAllContacts(int muNumber) {
            List<Contact> contactList = new ArrayList<Contact>();
            // Select All Query
            String selectQuery = "SELECT * FROM ANSWER WHERE ID= " + muNumber;
    System.out.println("QUERY STRING IS......>>>>>> " + selectQuery);

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    Contact contact = new Contact();
                    contact.setID(Integer.parseInt(cursor.getString(0)));
                    contact.setName(cursor.getString(1));
                    // contact.setPhoneNumber(cursor.getString(2));
                    // Adding contact to list
                    contactList.add(contact);
                } while (cursor.moveToNext());
            }

            // return contact list
            return contactList;
        }
}
公共类DatabaseHandler扩展了SQLiteOpenHelper{
//应用程序数据库的Android默认系统路径。
私有静态字符串DB_PATH=“/data/data/com.sqlite.example/databases/”;
私有静态字符串DB_NAME=“answers”;
私有SQLiteDatabase-myDataBase;
私有最终上下文myContext;
字符串myPath;
/**
*构造函数获取并保留所传递上下文的引用,以便
*访问应用程序资产和资源。
* 
*@param上下文
*/
公共数据库处理程序(上下文){
super(上下文,DB_名称,null,1);
this.myContext=上下文;
}
/**
*在系统上创建一个空数据库,并用自己的数据库重写它
*数据库。
* */
public void createDataBase()引发IOException{
布尔值dbExist=checkDataBase();
if(dbExist){
//不执行任何操作-数据库已存在
}否则{
//通过调用此方法,空数据库将被创建到
//默认系统路径
//你的应用程序,所以我们可以覆盖它
//数据库与我们的数据库。
这是.getReadableDatabase();
试一试{
copyDataBase();
}捕获(IOE异常){
抛出新错误(“复制数据库时出错”);
}
}
}
/**
*检查数据库是否已存在,以避免每次重新复制文件
*打开应用程序的时间。
* 
*@如果存在则返回true,如果不存在则返回false
*/
私有布尔校验数据库(){
SQLiteDatabase checkDB=null;
试一试{
myPath=DB_PATH+DB_NAME;
checkDB=SQLiteDatabase.openDatabase(myPath,null,
SQLiteDatabase.OPEN_READONLY);
}catch(sqlitee异常){
//数据库还不存在。
}
if(checkDB!=null){
checkDB.close();
}
return checkDB!=null?true:false;
}
/**
*将数据库从本地资产文件夹复制到刚创建的
*系统文件夹中的空数据库,从中可以访问和
*已处理。这是通过传输ByTestStream来完成的。
* */
私有void copyDataBase()引发IOException{
//打开本地数据库作为输入流
InputStream myInput=myContext.getAssets().open(DB_NAME);
//刚创建的空数据库的路径
字符串outFileName=DB_路径+DB_名称;
//打开空数据库作为输出流
OutputStream myOutput=新文件OutputStream(outFileName);
//将字节从输入文件传输到输出文件
字节[]缓冲区=新字节[1024];
整数长度;
而((长度=myInput.read(缓冲区))>0){
写入(缓冲区,0,长度);
}
//关闭溪流
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase()引发SQLException{
//打开数据库
myPath=DB_PATH+DB_NAME;
myDataBase=SQLiteDatabase.openDatabase(myPath,null,
SQLiteDatabase.OPEN_READONLY);
}
@凌驾
公共同步作废关闭(){
if(myDataBase!=null)
myDataBase.close();
super.close();
}
@凌驾
public void onCreate(SQLiteDatabase db){
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
}
//添加公共助手方法以访问和获取
//数据库。
//您可以通过执行“returnmydatabase.query(..”)来返回游标,因此
//放轻松
//为您的视图创建适配器。
公共列表getAllContacts(int muNumber){
List contactList=new ArrayList();
//选择所有查询
String selectQuery=“SELECT*FROM ANSWER WHERE ID=“+muNumber;
System.out.println(