0

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

我的 rawQuery 有问题。它没有显示任何东西。我很确定数据库不是空的,因为我添加了几个插入语句进行测试(我也尝试过put()and 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);
        }
    }
4

3 回答 3

2
while(!c.moveToNext()) 

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

于 2012-05-17T18:20:12.853 回答
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);

    }

}

}

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

例如:

In main activity class

   TimeListDatabaseHelper db = new TimeListDatabaseHelper(this);
    db.getAllTimeRecords();
于 2012-05-17T18:24:34.400 回答
0

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

正如@Alexander Lucas 所说,您的代码使其无法进入循环,因为您将“!”放入其中 while(!c.moveToNext()),尝试替换 for while(c.moveToNext())

于 2012-05-17T18:27:39.797 回答