Android SQL数据未添加到DB

时间:2016-03-12 05:09:02

标签: android database sqlite

我正在尝试编写一个Android应用,让我将数据添加到数据库然后查看它。我一直在关注YouTube教程。当我点击"添加数据"按钮,我收到Toast消息,告诉我数据已添加。但是,当我单击“查看全部”按钮时,它会告诉我没有数据。我使用File explorer来检查数据库文件,那里没有任何保存。我对使用Android应用程序的SQL不是很熟悉,但我正在努力学习。

这是DBHelper类

package com.example.fourth;

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 DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Bars.db";
    public static final String TABLE_NAME = "Bar_info";
    public static final String ID = "ID";
    public static final String BAR_NAAME = "Bar Name";
    public static final String BAR_CITY = "Bar City";
    public static final String DRINK_NAME = "Drink Name";
    //public static final String DRINK_PRICE = "Drink Price";
    //public static final String DRINK_TYPE = "Drink Type";


    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+ TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, BAR_NAME TEXT, "
                + "BAR_CITY TEXT, DRINK_NAME TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);

    }
    public boolean insertData(String bar_name, String bar_city, String drink_name){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(BAR_NAAME,bar_name);
        contentValues.put(BAR_CITY ,bar_city);
        contentValues.put(DRINK_NAME,drink_name);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if(result == -1)
            return false;
        else 
            return true;
        }
    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res  = db.rawQuery("select * from "+TABLE_NAME, null);
        return res;
    }

    }

这是MainActivity.java

package com.example.fourth;

import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    DBHelper myDB;
    EditText editBarName, editBarCity, editDrinkName;
    Button btnAddData, btnViewAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDB = new DBHelper(this);

        editBarName = (EditText) findViewById(R.id.editBarName);
        editBarCity = (EditText) findViewById(R.id.editBarCity);
        editDrinkName = (EditText) findViewById(R.id.editDrinkName);
        btnAddData = (Button) findViewById(R.id.btnAddData);
        btnViewAll = (Button) findViewById(R.id.btnViewAll);
        AddData();
        ViewAll();
    }

    public void AddData() {
        btnAddData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean isInsterted = myDB.insertData(editBarName.getText().toString(),
                        editBarCity.getText().toString(), editDrinkName.getText().toString());
                if (isInsterted = true)
                    Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this, "Data Not Inserted", Toast.LENGTH_LONG).show();
            }
        });
    }

    public void ViewAll() {
        btnViewAll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Cursor res = myDB.getAllData();
                if(res.getCount() ==0){
                    // show message 
                    showMessage("Error", "No Data Found");
                    return;
                }

                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()){
                    buffer.append("ID :"+ res.getString(0)+ "\n");
                    buffer.append("Bar Name :"+ res.getString(1)+ "\n");
                    buffer.append("Bar City :"+ res.getString(2)+ "\n");
                    buffer.append("Drink Name :"+ res.getString(3)+ "\n\n");

                }
                //Show All Data
                showMessage("Data", buffer.toString());
            }
        });
    }

    public void showMessage(String title, String message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

这是Activity.xml页面

<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:gravity="top"
    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.fourth.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Bar Name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:text="Bar City"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:text="Drink Name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editBarName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_alignLeft="@+id/btnAddData"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <EditText
        android:id="@+id/editBarCity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView3"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:ems="10" />

    <EditText
        android:id="@+id/editDrinkName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnAddData"
        android:layout_alignLeft="@+id/editBarCity"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView3"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnAddData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView3"
        android:layout_centerVertical="true"
        android:text="Add Data" />

    <Button
        android:id="@+id/btnViewAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btnAddData"
        android:layout_alignBottom="@+id/btnAddData"
        android:layout_marginLeft="40dp"
        android:layout_toRightOf="@+id/btnAddData"
        android:text="View All" />

</RelativeLayout>

3 个答案:

答案 0 :(得分:1)

尝试创建表

Public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+ TABLE_NAME + "ID INTEGER PRIMARY KEY AUTOINCREMENT,"+ Bar_Name + "TEXT ,"
                + Bar_city+ "TEXT," + Drink_Name + "TEXT");

更改名称

public static final String BAR_NAAME = "Bar_Name";
public static final String BAR_CITY = "Bar_City";
public static final String DRINK_NAME = "Drink_Name";

答案 1 :(得分:1)

isInserted分配为true。您应该值与==进行比较,而不是单个=。

替换 if(isInsterted = true)使用 if (isInsterted == true)

答案 2 :(得分:-1)

创建一个这样的表...............希望它的帮助你

@Override
    public void onCreate(SQLiteDatabase db) {


          System.out.println("table...........................................................");

          String myTABLE = "CREATE TABLE " +quizTABLE+ "(" 
                    + KEY_QNO + " TEXT," + KEY_QUESTION + " TEXT,"
                    + KEY_OPTION1 + " TEXT," + KEY_OPTION2 + " TEXT,"
                    + KEY_OPTION3 + " TEXT," + KEY_OPTION4 + " TEXT,"
                    + KEY_ANSWER + " TEXT" + ")";


          db.execSQL(myTABLE);

          Log.d("Table create.........................","TABLE CREATE SUCCESSFULYL");

    }