数据库插入

时间:2013-01-08 10:33:07

标签: android

在我的应用程序中,我想从编辑文本中获取密码,我想将其存储在按钮上的数据库中点击

在我的主要活动中,我获取了密码值,代码为..

  db_obj = new OpenHelper(getApplicationContext()) {};  
      okBtn = (Button)findViewById(R.id.okbtn);
      passwordTxt = (TextView)findViewById(R.id.editText1);
      passwordTxtValue = passwordTxt.getText().toString();

     okBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String id1 = Integer.toString(id);
              passwordTxtValue = passwordTxt.getText().toString();
              Toast.makeText(SetteingsPage.this, passwordTxtValue, Toast.LENGTH_SHORT).show();
              System.out.println("pa"+passwordTxtValue);

              db_obj.password_varification(id1, passwordTxtValue);

        }

在openHelper中,我创建了dataBase为...

static final String password_table = "password_db";
static final String table_id = "table_id";
static final String password = "password";

  public void onCreate(SQLiteDatabase db) 
{
    db.execSQL("CREATE TABLE "+password_table+"("+table_id+" INTEGER PRIMARY KEY, "+password+" TEXT)");

}

 public void password_varification(String tableid ,String paswrd ) 
{
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues cv=new ContentValues();

     cv.put(table_id, tableid);
     cv.put(password, paswrd);

     db.insert(password_table, table_id, cv);


     db.close();
     Log.v("DB", "Inset_User OK" + tableid + " " + paswrd); 
}
 // password Data retrive here
public ArrayList<HashMap<String, String>> password_records() 
{
     SQLiteDatabase db=getReadableDatabase();
     ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

     Cursor cursor=db.rawQuery("SELECT "+table_id+" as _id,  "+password+" from "+password_table,new String [] {});
    //Cursor cursor=db.rawQuery("SELECT "+row+" as _id, "+twitter+" from "+winery_info_2,new String [] {});


         if(cursor!=null)             
         {
             if(cursor.moveToFirst())  // movies first column 
             {
                 do
                 {
                     HashMap<String, String> map = new HashMap<String, String>();

                     String  fnam        = cursor.getString(cursor.getColumnIndex("password"));

                     map.put (password      ,fnam);


                     list.add(map);
                 }
                 while(cursor.moveToNext()); // move to next row

             }
         }

         if (cursor != null && !cursor.isClosed()) 

         {
            cursor.close();
         }

         return list;
   }

但是当我要插入值时,它显示错误“没有这样的表”..我怎么能解决它

logCat输出

   01-08 16:06:33.273: E/Database(12305): Error inserting password_db
  01-08 16:06:33.273: E/Database(12305): android.database.sqlite.SQLiteException: no            such table: password_db: , while compiling: INSERT INTO password_db(table_id, password) VALUES(?, ?);
 01-08 16:06:33.273: E/Database(12305):     at       android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
01-08 16:06:33.273: E/Database(12305):  at   android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
01-08 16:06:33.273: E/Database(12305):  at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
 01-08 16:06:33.273: E/Database(12305):     at android.database.sqlite.SQLiteProgram.  <init>(SQLiteProgram.java:83)
 01-08 16:06:33.273: E/Database(12305):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41)
 01-08 16:06:33.273: E/Database(12305):     at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1151)
 01-08 16:06:33.273: E/Database(12305):     at com.example.security.database.OpenHelper.password_varification(OpenHelper.java:98)
 01-08 16:06:33.273: E/Database(12305):     at com.example.security.Setting.SetteingsPage$2.onClick(SetteingsPage.java:51)
 01-08 16:06:33.273: E/Database(12305):     at android.view.View.performClick(View.java:2485)
 01-08 16:06:33.273: E/Database(12305):     at android.view.View$PerformClick.run(View.java:9080)
01-08 16:06:33.273: E/Database(12305):  at android.os.Handler.handleCallback(Handler.java:587)
01-08 16:06:33.273: E/Database(12305):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-08 16:06:33.273: E/Database(12305):  at android.os.Looper.loop(Looper.java:130)
01-08 16:06:33.273: E/Database(12305):  at android.app.ActivityThread.main(ActivityThread.java:3687)
01-08 16:06:33.273: E/Database(12305):  at java.lang.reflect.Method.invokeNative(Native Method)
01-08 16:06:33.273: E/Database(12305):  at   java.lang.reflect.Method.invoke(Method.java:507)
01-08 16:06:33.273: E/Database(12305):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
01-08 16:06:33.273: E/Database(12305):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
01-08 16:06:33.273: E/Database(12305):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

DBAdapter Class#

这是我的示例代码,它工作得很好.AddActivity我将从编辑文本中获取一些值,并使用DBAdapter我将保存在sqlite中。

package gps.profile.changer;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DBAdapter {
    public static final String KEY_ROWID = "_id";
    public static final String KEY_LAT = "latcol";
    public static final String KEY_LON = "loncol";
    public static final String KEY_LOCNAME = "locnamecol";
    public static final String KEY_PROTYPE="protypecol";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "gps";
    private static final String DATABASE_TABLE = "locationtb";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
    "create table locationtb (_id integer autoincrement primary key,latcol real not null,"
    + "loncol real not null,locnamecol varchar not null, "
    + "protypecol varchar not null);";

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;



    public DBAdapter(Context ctx) {
        // TODO Auto-generated constructor stub
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
    DatabaseHelper(Context context)
    {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion,
    int newVersion)
    {
    Log.w(TAG, "Upgrading database from version " + oldVersion
    + " to "
    + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS locationtb");
    onCreate(db);
    }
    }

    //---opens the database---
    public DBAdapter open() throws SQLException
    {
    db = DBHelper.getWritableDatabase();

    return this;
    }

    //---closes the database---
    public void close()
    {
    DBHelper.close();
    }

    //---insert a title into the database---
    public long insertTitle(double latcol, double loncol, String locnamecol,String protypecol)
    {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_LAT, latcol);
    initialValues.put(KEY_LON, loncol);
    initialValues.put(KEY_LOCNAME, locnamecol);
    initialValues.put(KEY_PROTYPE, protypecol);


    return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular title---
    public boolean deleteTitle(String rowId)
    {
    return db.delete(DATABASE_TABLE, KEY_LOCNAME  +
    "=" + rowId, null) > 0;
    }

    //---retrieves all the titles---
    public Cursor getAllTitles()
    {
    return db.query(DATABASE_TABLE, new String[] {

    KEY_LAT,
    KEY_LON,
    KEY_LOCNAME,
    KEY_PROTYPE},
    null,null,null,null,null);//put extra null if not work
    }

    //---retrieves a particular title---
    public Cursor getTitle(String gen) throws SQLException
    {
    Cursor mCursor =
     db.query(true, DATABASE_TABLE, new String[] {

    KEY_LAT,
    KEY_LON,
    KEY_LOCNAME,
    KEY_PROTYPE
    },
    KEY_PROTYPE + "=" + gen,
    null,null,null,null,null);
    if (mCursor != null)
    {
    mCursor.moveToFirst();
    Log.e("","");
    }



    return mCursor;
    }
    //checking  profile saved for that latitude and longitude in db

    public Cursor getprofilelist(String gen) throws SQLException
    {

     Cursor mcursor = db.rawQuery("select * from locationtb where protypecol=? " ,new String [] {gen});
     if (mcursor != null)
       {
      mcursor.moveToFirst();
       Log.e("","");
       }              
     return mcursor;
    }



    public Cursor getLocationProfile(Double a,Double b ) throws SQLException
    {

     Cursor mcursor = db.rawQuery("select * from locationtb where latcol=? and loncol=?" ,new String [] {String.valueOf(a),String.valueOf(b)});
     if (mcursor != null)
       {
      mcursor.moveToFirst();
       Log.e("","");
       }              
     return mcursor;
    }

    //---updates a title---
    public boolean updateTitle(long rowId, String latcol,
    String loncol, String locnamecol,String protypecol)
    {
    ContentValues args = new ContentValues();
    args.put(KEY_LAT, latcol);
    args.put(KEY_LON, loncol);
    args.put(KEY_LOCNAME,locnamecol);
    args.put(KEY_PROTYPE, protypecol);
    return db.update(DATABASE_TABLE, args,
    KEY_LOCNAME + "=" + rowId, null) > 0;
    }


}

AddActivity

package gps.profile.changer;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class AddActivity extends Activity
{
      public EditText locationname;
      public EditText latit,longit;



    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addlayout);

        latit = (EditText) findViewById(R.id.lat1);        
        longit = (EditText) findViewById(R.id.long1);     
        locationname = (EditText) findViewById(R.id.locname);    
        adddata=(ImageView)findViewById(R.id.imageadd);
        spinn= (Spinner) findViewById(R.id.spinner1);


        locatname=locationname.getText().toString();
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.profiles, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinn.setAdapter(adapter);



        spinn.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {               
                spinsave=spinn.getSelectedItem().toString();    
                //Toast.makeText(AddActivity.this, spinsave, Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        }); 

    }

 }




      public void connect(View v)
      {


        latitude=latit.getText().toString();
         longitude=longit.getText().toString();
          latdou=Double.parseDouble(latitude);
          longdou=Double.parseDouble(longitude);
         locatname=locationname.getText().toString();
         int latlen=latitude.length();
         int lonlen=longitude.length();
         int namlen=locatname.length();
          if(latlen!=0&&lonlen!=0&&namlen!=0)
             {
              Toast.makeText(AddActivity.this, "added", Toast.LENGTH_SHORT ).show();
              db = new DBAdapter(this);

              insert();
              startService(new Intent(this, LocationAddActivity.class));
              Log.e("added","added");
              //  update();

             // dis("'Vibrate'");
              //  del("1");
             // disAll();
             //   getlocationpro(latlaa1,lnglaa1);

            }
          else
          {
              Toast.makeText(AddActivity.this, "fill all fields", Toast.LENGTH_SHORT ).show();
              startService(new Intent(this, LocationAddActivity.class));
          }
  }

    /*  private void update(){ 

            db.open();
            if (db.updateTitle(1,
                    "1",
                    "java ",
                    "ravi"))
                Toast.makeText(this, "Update successful.",
                    Toast.LENGTH_LONG).show();
            else
                Toast.makeText(this, "Update failed.",
                    Toast.LENGTH_LONG).show();
            //-------------------

            //---retrieve the same title to verify---
            Cursor c = db.getTitle(1);
            if (c.moveToFirst())
                DisplayTitle(c);
            else
                Toast.makeText(this, "No title found",
                        Toast.LENGTH_LONG).show();
            //-------------------
            db.close();

        }*/
        public void insert(){ 

            db.open();

          long  id = db.insertTitle(
                    latlaa1,
                    lnglaa1,
                    locatname,
                    spinsave
                    );

            db.close();

        }

    /*    private void disAll(){
             Toast.makeText(AddActivity.this, "disall", Toast.LENGTH_SHORT ).show();
             //db = new DBAdapter(this);
            db.open();


                Cursor c = db.getAllTitles();
                if (c.moveToFirst())
                {
                    do {
                        System.out.println("bool2");
                       if(latdou==c.getDouble(0)&&longdou==c.getDouble(1))
                       {
                           Toast.makeText(AddActivity.this, "Location Already Exist in the Name of:"+c.getString(2), Toast.LENGTH_LONG).show();
                          // startService(new Intent(this, LocationAddActivity.class));

                        if(locatname==c.getString(2))
                         {
                           Toast.makeText(AddActivity.this, "Location Name Already Exist:"+c.getString(2), Toast.LENGTH_LONG ).show();
                          // startService(new Intent(this, LocationAddActivity.class));
                         }

                       }   
                    } while (c.moveToNext());

                }
                insert();
            db.close();
        }*/

        private void dis(String j){

            db.open();

            try{
                Cursor c = db.getTitle(j);
                if (c.moveToFirst())
                {
                    do {

                        System.out.println("bool2");
                        DisplayTitle(c);
                    } while (c.moveToNext());
                }
            }catch(Exception e){
                System.out.println(e);
            }
            db.close();
        }        

      /* private void getlocationpro(Double a,Double b){

            db.open();

            try{
                Cursor c = db.getLocationProfile(a,b);
                if (c.moveToFirst())
                {
                    do {

                        System.out.println("bool2");
                        DisplayTitle(c);
                    } while (c.moveToNext());
                }
            }catch(Exception e){
                System.out.println(e);
            }
            db.close();
        }        */





        /*
         private void del(String j){

            db.open();
            if (db.deleteTitle(j))
                Toast.makeText(this, "Delete successful.",
                    Toast.LENGTH_LONG).show();
            else
                Toast.makeText(this, "Delete failed.",
                    Toast.LENGTH_LONG).show();
            db.close();

        }*/

        public void DisplayTitle(Cursor c)
        {


            Toast.makeText(this,

                    "LAITUDE: " + c.getDouble(0) + "\n" +
                    "LONGITUDE: " + c.getDouble(1) + "\n" +
                    "LOCATION NAME:  " + c.getString(2)+"\n"+
                    "PROFILE TYPE:  " + c.getString(3),
                    Toast.LENGTH_LONG).show();
        }

       private class MyReceiver extends BroadcastReceiver{

             @Override
             public void onReceive(Context arg0, Intent arg1) {

              // TODO Auto-generated method stub
                 latit = (EditText) findViewById(R.id.lat1);        
                 longit = (EditText) findViewById(R.id.long1);  

                 latlaa1 =arg1.getDoubleExtra("latlaa", 0);
                   lnglaa1=arg1.getDoubleExtra("lnglaa", 1);

                   latit.setText(String.valueOf(latlaa1));
                  longit.setText(String.valueOf(lnglaa1));

               get1();
               //startService(new Intent(AddActivity.this, LocationAddActivity.class));




            //LocationAddActivity laa=new LocationAddActivity();
           // laa.get(null);



          Toast.makeText(AddActivity.this, "receiver ", Toast.LENGTH_SHORT ).show();
       //   Intent intent=new Intent(AddActivity.this, LocationAddActivity.class);  
       //   startService(intent);



               }


        public void get1()
            {



                db = new DBAdapter(AddActivity.this);
                db.open();




                     Cursor c = db.getLocationProfile(latlaa1,lnglaa1);
                    if (c.moveToFirst())
                    {
                        do {



                              if(c!=null)
                                {



                             // Initialize the location fields

                                if(c.getString(3).equals("Vibrate"))
                                     {

                                        Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show();


                                     }
                                    else if (c.getString(3).equals("Silent"))
                                     {

                                        Toast.makeText(getBaseContext(),"silent profile activated !",Toast.LENGTH_SHORT).show();

                                     }
                                    else if (c.getString(3).equals("General"))
                                     {
                                        Toast.makeText(getBaseContext(),"Loud profile activated !",Toast.LENGTH_SHORT).show();


                                     }


                                }


                        } while (c.moveToNext());
                    }
                    else
                    {

                           Toast.makeText(getBaseContext(),"else vibrate activated !",Toast.LENGTH_SHORT).show();
                         mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                    }



             db.close();



       }


   }


}