如何从sqlite中检索数据?

时间:2016-06-04 11:34:28

标签: android

这是我的主要活动,数据库和布局代码, 我试图从SQLite数据库中检索数据,但这段代码不起作用。我不明白为什么?? 这个问题花了这么多时间我很生气,请帮助我。我是android的新手。

主要活动文件!!

     public class MainActivity extends AppCompatActivity {

    EditText name;
    EditText phone;
    Button submit;
    Button data;
    TextView tName;
    TextView tphone;
    Cursor getData;
    String dbString="";
    String dbString2="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


            name=(EditText)findViewById(R.id.editText);
            phone=(EditText)findViewById(R.id.editText2);
            submit=(Button)findViewById(R.id.button);
            data=(Button)findViewById(R.id.button2);
            tName=(TextView)findViewById(R.id.textView);
            tphone=(TextView)findViewById(R.id.textView2);

        data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DataBase2n6 objOfDataBase2n6=new DataBase2n6(getBaseContext());
              Cursor  getData = objOfDataBase2n6.showData();
                getData.moveToFirst();
               do{
                   dbString+=getData.getString(getData.getColumnIndex("name"));
                   dbString+="\n";
                   tName.setText(dbString);
                }while(getData.moveToNext());

                Toast.makeText(getBaseContext(), "YOUR DATA", Toast.LENGTH_LONG).show();
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getName=name.getText().toString();
                String getPhone=phone.getText().toString();

                DataBase2n6 objOfDataBase2n6=new DataBase2n6(getBaseContext());

                objOfDataBase2n6.insertData(getName,getPhone);
                Toast.makeText(getBaseContext(), "data is inserted", Toast.LENGTH_LONG).show();
            }
        });

    }
}

数据库文件!!

    public class DataBase2n6 extends SQLiteOpenHelper {
    SQLiteDatabase db;
    public static final String DATABASE_NAME="myDatabase.db";
    public static final String TABLE_NAME="myTable";
    public static final String NAME="name";
    public static final String PHONE="phone";
    public static final int DATABASE_VERSION=1;

    public DataBase2n6(Context context) {

        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(//"create table" + TABLE_NAME + "(" + NAME + "," + PHONE + ")"
            "create table myTable" +
                    "(id integer primary key, name text, phone text)"
            );
        }
    catch(android.database.SQLException e){
        System.out.println("what the fuck");
    }
    }

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

        db.execSQL("DROP TABLE IF EXISTS myTable");
        onCreate(db);
    }

    public void insertData(String nam,String mob){
        db=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();

            contentValues.put(NAME,nam);
            contentValues.put(PHONE,mob);

            db.insert(TABLE_NAME, null, contentValues);
            db.close();
        }

    public Cursor showData(){

        db=this.getWritableDatabase();

        Cursor res =  db.rawQuery("SELECT  * FROM "+TABLE_NAME,null);
        return res;

    }
}

layoyt文件!!

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.firstproject.start2_6_16.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:hint="name"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_below="@+id/editText"
        android:layout_alignParentStart="true"
        android:hint="phone"
        android:layout_marginTop="55dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="submit"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="data"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:layout_below="@+id/button2"
        android:layout_alignParentStart="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView2"
        android:layout_below="@+id/button2"
        android:layout_alignParentEnd="true"/>

</RelativeLayout>

1 个答案:

答案 0 :(得分:-1)

我建议采用不同的方法:创建一个包含sqlite数据结构的类:

file.Fullname

然后从应用程序中调用此类:

public class SQLiteAdapterPrefs {

public static final String MYDATABASE_NAME = "AssetTrackerPrefs";
public static final String MYDATABASE_TABLE = "systemPrefs";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_IMEI = "Nr_Target_Imei"; 
public static final String KEY_LAT = "Nr_Track_Target_Latitude";
public static final String KEY_LON = "Nr_Track_Target_Longitude";   
public static final String KEY_TRACKTIME = "Dt_Target_Track_Point"; 
public static final String KEY_FREQUENCY = "Nr_Frequency";  // upload frequency
public static final String KEY_USER = "Ds_Target_Email";
public static final String KEY_IP = "Ds_IP";
public static final String KEY_PORT = "Nr_IP_Port"; 
public static final String KEY_STICKY = "Ic_Autostart";

public static String imeiFromDevice = "INVALID_IMEI_I9100_sqlliteadapter01";
private boolean flagSticky = true;
private int frequency = 1;
private String emailId = "";

//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
        "create table " + MYDATABASE_TABLE + " ("
        + KEY_ID + " integer default 1, " // primary key autoincrement, "
        + KEY_IMEI + " text not null, " 
        + KEY_LAT + " float default -91.0, "
        + KEY_LON + " float default -181.0, " 
        + KEY_TRACKTIME + " long NOT NULL, "
        + KEY_FREQUENCY + " integer default 1, "
        + KEY_USER + " text not null, " 
        + KEY_IP + " text not null, " 
        + KEY_PORT + " integer default 9099, "
        + KEY_STICKY + " integer default 1"
        + ");";

private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;

private String TAG = "TGPrefs";
private Context context;


public SQLiteAdapterPrefs(Context c){
    context = c;
}


public SQLiteAdapterPrefs openToRead() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
    sqLiteDatabase = sqLiteHelper.getReadableDatabase();
    return this;    
}

public SQLiteAdapterPrefs openToWrite() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
    sqLiteDatabase = sqLiteHelper.getWritableDatabase();
    return this;    
}

public void close(){
    sqLiteHelper.close();
}
public Cursor queueAll(){
    //String[] columns = new String[]{KEY_ID, KEY_IMEI, KEY_LAT, KEY_LON, KEY_TRACKTIME, KEY_USER, KEY_IP, KEY_STICKY};
    String[] columns = new String[]{KEY_ID, KEY_IMEI, KEY_LAT, KEY_LON, KEY_TRACKTIME, KEY_FREQUENCY, KEY_USER, KEY_IP, KEY_PORT, KEY_STICKY};
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, 
            null, null, null, null, null);
    return cursor;
}
public Cursor getFirst(){
    //String[] columns = new String[]{KEY_ID, KEY_IMEI, KEY_LAT, KEY_LON, KEY_TRACKTIME, KEY_USER, KEY_IP, KEY_STICKY};
    String[] columns = new String[]{KEY_ID, KEY_IMEI, KEY_LAT, KEY_LON, KEY_TRACKTIME, KEY_FREQUENCY, KEY_USER, KEY_IP, KEY_PORT, KEY_STICKY};


    String whereCondition = KEY_ID+"=1";
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, 
            whereCondition, null, null, null, null);
    return cursor;
}