Android中的rawQuery没有显示数据库内容

时间:2012-05-17 18:07:53

标签: android sqlite

是的,这是作业,但我尽职尽责,我被困住了!希望有人可以提供帮助!

我的rawQuery出现问题。它没有显示任何东西。我很确定数据库不是空的,因为我添加了几个用于测试的插入语句(我还尝试使用put()insert()),但仍然没有显示任何内容。

问题是,当我运行我的代码时,我没有得到任何错误或异常,但它从未进入logDatabase(while !c.moveToNext)中的while循环。

我做了大量的研究,但我看过的所有书籍似乎都告诉我这样做。也许我错过了一些显而易见的东西,但我不能为我的生活弄清楚它是什么。谢谢!

package jschuler.cs211d.hw06b;

    import android.app.Activity;
    import android.os.*;
    import android.widget.*;
    import android.util.Log;
    import android.view.*;
    import java.util.*;
    import java.io.*;
    import android.content.*;
    import android.database.*;
    import android.database.sqlite.SQLiteDatabase;

    public class play extends Activity 
                      implements RadioGroup.OnCheckedChangeListener
    {    
        private static final String DBNAME = "statesDB";
        static final String STATE = "state", CAPITAL = "capital";

    //*****************************onCreate()*****************************
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.play);

            // Check to see if SD card is available. If not, warn the user
            if(!sdCardAvailable())
            {
                Toast t = Toast.makeText(getApplicationContext(), 
                    "No SD card available.", 
                    Toast.LENGTH_SHORT);
                t.show();
            }
            else
            {
                Toast t = Toast.makeText(getApplicationContext(), 
                    "SD card is available.", 
                    Toast.LENGTH_SHORT);
                t.show();
            }

            loadDB();
        }
    //**************************onCheckChanged()**************************
    //  Set the variable that represents the type, depending on 
    //  what the user has selected in the radio group.    
        public void onCheckedChanged(RadioGroup g, int CheckedId)
        {

        }
    //******************************loadDB()******************************
    //  Create the data structures to hold the data
        public void loadDB()
        {
            SQLiteDatabase db;
            db = openOrCreateDatabase("statesDB", 
                SQLiteDatabase.CREATE_IF_NECESSARY, null);

            db.setVersion(1);
            db.setLockingEnabled(true);

            db.execSQL("CREATE TABLE if not exists states(_id integer primary key autoincrement, STATE text, CAPITAL text);");

            Scanner sc;

            try
            {
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath());
                File f = new File(dir, "US_states");
                sc = new Scanner(f);

                // Skip the first line
                sc.nextLine();
                sc.nextLine();

                // Read in the names of the states and capitals. 
                while(sc.hasNextLine())
                {
                    String[] nextItem = sc.nextLine().split("\\s{2,}");
                    ContentValues cv = new ContentValues();
                    cv.put(STATE, nextItem[0]);
                    db.insert("states", STATE, cv);
                    cv.put(CAPITAL, nextItem[1]);
                    db.insert("states", CAPITAL, cv);
                }
            }
            catch (FileNotFoundException e)
            {
                Toast t = Toast.makeText(getApplicationContext(), 
                    "Error loading data.", 
                    Toast.LENGTH_SHORT);
                t.show();
            }

            db.close();

            logDatabase();
        }
    //***************************logDatabase()****************************
        public void logDatabase()
        {
            SQLiteDatabase db;
            db = openOrCreateDatabase("statesDB", 
                SQLiteDatabase.CREATE_IF_NECESSARY, null);

            db.execSQL("INSERT INTO states (STATE) values ('AB');");
            db.execSQL("INSERT INTO states (STATE) values ('CD');");
            db.execSQL("INSERT INTO states (STATE) values ('EF');");

            ContentValues cv = new ContentValues();
            cv.put(STATE, "AB");
            db.insert("states", STATE, cv);

            Cursor c = db.rawQuery("SELECT STATE, CAPITAL FROM states",null);

            while(!c.moveToNext())
            {
                Log.d("mtn","in moveToNext()");
                Log.d("state",c.getString(0));
                Log.d("capital",c.getString(1));
            }

            db.close();
        }
    //*************************sdCardAvailable()**************************
    //  Determine whether there is an SD card available and if it is 
    //  writable.
        public boolean sdCardAvailable()
        {
            boolean storageAvailable = false;
            boolean storageWritable = false;

            String state = Environment.getExternalStorageState();

            if(Environment.MEDIA_MOUNTED.equals(state))
            {
                storageAvailable = storageWritable = true;
            }
            else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
            {
                storageAvailable = true;
                storageWritable = false;
            }
            else
            {
                storageAvailable = storageWritable = false;
            }

            return (storageWritable && storageAvailable);
        }
    }

3 个答案:

答案 0 :(得分:2)

while(!c.moveToNext()) 

这一行,翻译成英文,变为“当你不能移动到下一个项目时,输入循环,否则退出”。

答案 1 :(得分:0)

请参阅此代码并尝试以这种方式编写程序,我相信它会起作用....

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.database.sqlite.SQLiteOpenHelper;


public class TimeListDatabaseHelper {

    private static final String DATABASE_NAME = "timetracker.db";
    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_TABLE = "timerecords";


    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TIME = "note";
    public static final String COLUMN_NOTE = "time";


    private TimeTrackerOpenHelper openHelper;
    private SQLiteDatabase database;


    TimeListDatabaseHelper(Context context) {

        openHelper = new TimeTrackerOpenHelper(context);
        database = openHelper.getWritableDatabase();


    }

    public void saveTimeRecord(String time, String notes) {

        ContentValues contentValue = new ContentValues();

        contentValue.put(COLUMN_TIME, time);
        contentValue.put(COLUMN_NOTE, notes);

        database.insert(DATABASE_TABLE,null, contentValue);




        }



    public Cursor getAllTimeRecords() {
        return database.rawQuery(
        "select * from " + DATABASE_TABLE,
        null
        );
        }


public class TimeTrackerOpenHelper extends SQLiteOpenHelper {

    public TimeTrackerOpenHelper(Context context) {

        super(context,DATABASE_NAME, null , DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE "+DATABASE_TABLE+"("+COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT "+","+COLUMN_TIME+" TEXT "+","+COLUMN_NOTE+" NOTE"+")");



    }

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

                   db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_TABLE);
                   onCreate(db);

    }

}

}

现在你需要在main活动中创建这个类的实例,并将Activity(即“this”)传递给这个类构造函数。然后在main活动中使用此类的引用,尝试从此类中获取数据..

例如:

In main activity class

   TimeListDatabaseHelper db = new TimeListDatabaseHelper(this);
    db.getAllTimeRecords();

答案 2 :(得分:0)

添加插入的事实并不意味着它将插入到数据库中。这是一个参考Android Insert statement ...以确保填充数据库,打开您的DDMS,然后在设备上确保您选择了您的模拟器,然后单击文件浏览器>数据>数据>然后拉出数据库并使用数据库管理器程序打开它并运行select查询并确保其中包含数据。

正如@Alexander Lucas所说,你的代码不会进入循环,因为你在while(!c.moveToNext())中放了“!”,所以请尝试替换while(c.moveToNext())