无法解析SQlite dbhandler类的符号

时间:2014-08-27 14:04:10

标签: android sqlite

我正在尝试在android中创建/访问SQLite数据库。我创建了一个名为MDbHandler.java的文件,我编写了代码来创建数据库,插入,更新和删除。现在在需要使用此数据库的活动中,我正在onCreate()方法下创建一个对象。但是在Android Studio 0.8中,我收到“mDbHandler”符号无法解决的错误。 可能是什么解决方案?

mDbHandler.java文件:

package com.example.smashingwheels;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class mileageDbHandler extends SQLiteOpenHelper {
    public static final String TABLE_MILEAGE = "mileage";
    public static final String COL_ID = BaseColumns._ID;
    public static final String COL_DATE = "date";
    public static final String COL_LTR = "ltr";
    public static final String COL_ODO = "odo";
    private static final String DATABASE_NAME = "mileageDb";
    private static final int DATABASE_VERSION = 1;

    public mileageDbHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_MILEAGE + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COL_DATE + " TEXT NOT NULL,"
                + COL_LTR + " INTEGER,"
                + COL_ODO + " INTEGER"
                + ");");
    }

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

    public long insert(String tableName, ContentValues values) throws NotValidException {
        validate(values);

        return getWritableDatabase().insert(tableName, null, values);
    }

    public int update(String tableName, long id, ContentValues values) throws NotValidException {
        validate(values);

        String selection = COL_ID + " = ?";
        String[] selectionArgs = {String.valueOf(id)};

        return getWritableDatabase().update(tableName, values, selection, selectionArgs);
    }

    public int delete(String tableName, long id) {
        String selection = COL_ID + " = ?";
        String[] selectionArgs = {String.valueOf(id)};

        return getWritableDatabase().delete(tableName, selection, selectionArgs);
    }

    protected void validate(ContentValues values) throws NotValidException {
        if (!values.containsKey(COL_DATE) || values.getAsString(COL_DATE) == null || values.getAsString(COL_DATE).isEmpty()) {
            throw new NotValidException("Please enter a valid date.");
        }
    }

    public Cursor query(String tableName, String orderedBy) {
        String[] projection = {COL_ID, COL_DATE, COL_LTR, COL_ODO};
        return getReadableDatabase().query(tableName, projection, null, null, null, null, orderedBy);
    }

    public static class NotValidException extends Throwable {
        public NotValidException(String msg) {
            super(msg);
        }
    }
}

mActivity文件:

package com.example.user.smashingwheels;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.example.user.smashingwheels.R;

public class mileagecal extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mileagecal);

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setDisplayShowHomeEnabled(false);

        mileageDbHandler mDatabaseHelper = new mileageDbHandler(this);


        addUser("12/5/14", 2, 4500);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mileagecal, 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;
        }


        onBackPressed();
        return super.onOptionsItemSelected(item);
    }

    private void addUser(String date, int ltr, int odo) {
        ContentValues values = new ContentValues();
        values.put(mileageDbHandler.COL_DATE, date);

        values.put(mileageDbHandler.COL_LTR, ltr);

        values.put(mileageDbHandler.COL_ODO, odo);

        try {
            mDatabaseHelper.insert(mileageDbHandler.TABLE_USERS, values);
        } catch (mileageDbHandler.NotValidException e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}

这两个文件都位于src / java / com文件夹中 请帮忙!

5 个答案:

答案 0 :(得分:0)

这样做

在OnCreate()里程cal活动方法之前添加此

mileageDbHandler mDatabaseHelper;

以便此活动中的所有方法都可以访问DatabaseHelper

就像这样

public class mileagecal extends Activity {

mileageDbHandler mDatabaseHelper; //add this here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mileagecal);

    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setDisplayShowHomeEnabled(false);

    //make an object of that class here
    mDatabaseHelper = new mileageDbHandler(this);


    addUser("12/5/14", 2, 4500);

}

答案 1 :(得分:0)

就像我在评论中所述,add mDbHandler对于addUser()是不可见的。所以你可以创建一个类级变量,即

public class mileagecal extends Activity {

mileageDbHandler mDatabaseHelper;

并使用此变量。 或修改您的addUser()

private void addUser(String date, int ltr, int odo,mileageDbHandler mDatabaseHelper)

并将addUser("12/5/14", 2, 4500);替换为addUser("12/5/14", 2, 4500,mDatabaseHelper);

中的onCreate()

答案 2 :(得分:0)

package com.casper.pp1.Database;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.casper.pp1.UserModal;
import com.casper.pp1.Userprofile;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String CREATE_USERINFO_TABLE =
         "CREATE TABLE "+Userprofile.Users.TABLE_NAME+ "("
            +Userprofile.Users.COLUMN_ID+" INT PRIMARY KEY,"
            +Userprofile.Users.COLUMN_USERNAME+" TEXT,"
            +Userprofile.Users.COLUMN_PASSWORD+" TEXT,"
            +Userprofile.Users.COLUMN_DATEOFBIRTH+" TEXT,"
            +Userprofile.Users.COLUMN_GENDER+" TEXT)";
    public static final String DELETE_USERINFO_TABLE=
       "DROP TABLE IF EXISTS "+Userprofile.Users.TABLE_NAME;

    public DatabaseHelper(Context context) {
        super(context, "casper", null, 1);
    }

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

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
   {
        db.execSQL(DELETE_USERINFO_TABLE);
        onCreate(db);
    }

    public boolean addInfo(String username, String password,
                 String dateofbirth, String gender){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values= new ContentValues();
        values.put(Userprofile.Users.COLUMN_USERNAME,username);
        values.put(Userprofile.Users.COLUMN_PASSWORD,password);
        values.put(Userprofile.Users.COLUMN_DATEOFBIRTH,dateofbirth);
        values.put(Userprofile.Users.COLUMN_GENDER,gender);

        long count=db.insert(Userprofile.Users.TABLE_NAME, null, values);
        return count>=0;

    }

    public boolean updateInfo(String username,
           String password, String dateofbirth, String gender){
        int id = getIdByUsername(username);
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues values= new ContentValues();
        values.put(Userprofile.Users.COLUMN_USERNAME,username);
        values.put(Userprofile.Users.COLUMN_PASSWORD,password);
        values.put(Userprofile.Users.COLUMN_DATEOFBIRTH,dateofbirth);
        values.put(Userprofile.Users.COLUMN_GENDER,gender);

        String selection=Userprofile.Users.COLUMN_ID+" = ?";
        String[] selectionArgs = {Integer.toString(id)};

        long result=db.update(Userprofile.Users.TABLE_NAME,
             values,selection, selectionArgs);
         return result>0;
    }

    public List<UserModal> readAllInfo(){

        SQLiteDatabase db=this.getReadableDatabase();
        List<UserModal> list = new ArrayList<>();

        String sql = "SELECT * FROM "+Userprofile.Users.TABLE_NAME;

        Cursor rs = db.rawQuery(sql,null);

        if (rs.getCount()==0){
            return list;
        }else {
            while (rs.moveToNext()){
                list.add(new UserModal(rs.getInt(0),rs.getString(1),
                        rs.getString(2),rs.getString(3),rs.getString(4)));
            }
            return list;
        }
    }
    public UserModal readAllInfo(String username){

        int id = getIdByUsername(username);
        SQLiteDatabase db=this.getReadableDatabase();
       UserModal user = null;

        String selection=Userprofile.Users.COLUMN_ID+" = ?";
        String[] selectionArgs = {Integer.toString(id)};

        Cursor rs = db.query(Userprofile.Users.TABLE_NAME,
           null,selection,selectionArgs,null,null,null);

        if (rs.getCount()==0){
            return user;
        }else {
            while (rs.moveToNext()){
                user = new UserModal(rs.getInt(0),rs.getString(1),
                        rs.getString(2),rs.getString(3),rs.getString(4));
            }
            return user;
        }
    }

    public boolean deleteInfo(String username){
        int id = getIdByUsername(username);
        SQLiteDatabase db=this.getWritableDatabase();

        String selection=Userprofile.Users.COLUMN_ID+" = ?";
        String[] selectionArgs = {Integer.toString(id)};

        int count = db.delete(Userprofile.Users.TABLE_NAME,
            selection,selectionArgs);
        return count>0;

    }

    public int getIdByUsername(String username){

        SQLiteDatabase db=this.getReadableDatabase();
        UserModal user = null;

        String selection=Userprofile.Users.COLUMN_USERNAME+" LIKE ?";
        String[] selectionArgs = {username};
        int id = -1;



        Cursor rs = db.query(Userprofile.Users.TABLE_NAME,
             null,selection,selectionArgs,null,null,null);

        if (rs.getCount()==0){
            return id;
        }else {
            while (rs.moveToNext()){
                id=rs.getInt(0);
            }
            return id;
        }

    }

}


//********************Home Activity**********************************

public class Home extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
}


public void onClickRegister(View view){
    Intent intent=new Intent(this,ProfileManagement.class);
    startActivity(intent);
}
}


//******************************Profile Management*********************

public class ProfileManagement extends AppCompatActivity {

EditText userName,password,dob;
RadioGroup gender;
RadioButton x;
DatabaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_management);
    db= new DatabaseHelper(this);
    userName = findViewById(R.id.uname_edit);
    password = findViewById(R.id.pass_e22);
    dob = findViewById(R.id.dob_mg);
    gender=findViewById(R.id.gender_mg);
}
public void onClickUpdateProfile(View view){
    int id=gender.getCheckedRadioButtonId();
    x=findViewById(id);



  if(db.addInfo(userName.getText().toString(),
   password.getText().toString(),dob.getText().toString(),
     x.getText().toString())){
        Toast.makeText(this,"successfully registered",
        Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(this,"not registered",Toast.LENGTH_SHORT).show();
    }
    Intent intent = new Intent(this,EditProfile.class);
    startActivity(intent);
}
}


//*********************************Edit Profile**************************

public class EditProfile extends AppCompatActivity {
  EditText userName,password,dob;
  RadioGroup gender;
  RadioButton x, male,female;
  DatabaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_profile);
    db= new DatabaseHelper(this);
    userName = findViewById(R.id.uname_edit);
    password = findViewById(R.id.pass_e22);
    dob = findViewById(R.id.dob_edit);
    gender=findViewById(R.id.gender_edit);
    male = findViewById(R.id.male_edit);
    female = findViewById(R.id.female_edit);
}
public void OnClickSearch(View view){
    UserModal user;
    user=db.readAllInfo(userName.getText().toString());
    password.setText(user.getPassword());
    dob.setText(user.getDateOfBirth());
    if(user.getGender().equals("Male")){
        male.setChecked(true);
    }else{
        female.setChecked(true);
    }}
public void OnclickEdit(View view){
    int id=gender.getCheckedRadioButtonId();
    x=findViewById(id);


if(db.updateInfo(userName.getText().toString(),
password.getText().toString(),dob.getText().toString(),
x.getText().toString()
    )){
        Toast.makeText(this,"Successfully updated",
       Toast.LENGTH_SHORT).show();
    }else {
        }    }

public void deleteEdit(View view){
    if(db.deleteInfo(userName.getText().toString())){
        //toast
    }
}
}


//*****************************UserProfile*****************************

public final class Userprofile {
private Userprofile(){}

public final static class Users implements BaseColumns {
    public static final String TABLE_NAME = "UserInfo";
    public static final String  COLUMN_ID=BaseColumns._ID;
    public static final String COLUMN_USERNAME="Username";
    public static final String COLUMN_PASSWORD="Password";
    public static final String COLUMN_DATEOFBIRTH="Dateofbirth";
    public static final String  COLUMN_GENDER="Gender";


}

}

答案 3 :(得分:0)

公共类DBHandler扩展了SQLiteOpenHelper {

public static final String DataBase="DataBase.db";
public static final String Table_Name="UserInfo";
public static final String col1="id";
public static final String col2="name";
public static final String col3="dob";
public static final String col4="password";
public static final String col5="gender";



public DBHandler(Context context) {
    super(context,DataBase , null, 1);


}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table "+Table_Name+"("+col1+" integer primary key autoincrement ,"+col2+" text,"+col3+" text ,"+col4+" text ,"+col5+" text )");



}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("drop table if exists "+Table_Name);
    onCreate(sqLiteDatabase);



}
public boolean AddInfo(String name,String dob,String password,String gender){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    ContentValues val=new ContentValues();

    val.put(col2,name);
    val.put(col3,dob);
    val.put(col4,password);
    val.put(col5,gender);

    int i=(int)sqLiteDatabase.insert(Table_Name,null,val);

    if(i>0){
        return true;
    }
    else{
        return false;
    }


}
public boolean updateInfo(String name,String dob,String password,String gender){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    ContentValues val=new ContentValues();

    val.put(col2,name);
    val.put(col3,dob);
    val.put(col4,password);
    val.put(col5,gender);

    int i=sqLiteDatabase.update(Table_Name,val,"name="+name,null);
    if(i>0){
        return true;
    }
    else{
        return false;
    }



}
public Cursor readAllInfor(){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    Cursor c=sqLiteDatabase.rawQuery("select*from "+Table_Name,null);

    return c;
}

public Cursor readAllInfor(String name){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    Cursor c= sqLiteDatabase.rawQuery("select * from "+Table_Name+" where "+col2 +"=\""+name+"\"",null);
    return c;

}

public boolean deleteInfo(String name){

    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    int i=sqLiteDatabase.delete(Table_Name,"name="+name,null);
    if(i>0){
        return true;
    }
    else{
        return false;
    }

}

}

答案 4 :(得分:0)

公共类DBHandler扩展了SQLiteOpenHelper {

public static final String DataBase="DataBase.db";
public static final String Table_Name="UserInfo";
public static final String col1="id";
public static final String col2="name";
public static final String col3="dob";
public static final String col4="password";
public static final String col5="gender";



public DBHandler(Context context) {
    super(context,DataBase , null, 1);


}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table "+Table_Name+"("+col1+" integer primary key autoincrement ,"+col2+" text,"+col3+" text ,"+col4+" text ,"+col5+" text )");



}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("drop table if exists "+Table_Name);
    onCreate(sqLiteDatabase);



}
public boolean AddInfo(String name,String dob,String password,String gender){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    ContentValues val=new ContentValues();

    val.put(col2,name);
    val.put(col3,dob);
    val.put(col4,password);
    val.put(col5,gender);

    int i=(int)sqLiteDatabase.insert(Table_Name,null,val);

    if(i>0){
        return true;
    }
    else{
        return false;
    }


}
public boolean updateInfo(String name,String dob,String password,String gender){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    ContentValues val=new ContentValues();

    val.put(col2,name);
    val.put(col3,dob);
    val.put(col4,password);
    val.put(col5,gender);

    int i=sqLiteDatabase.update(Table_Name,val,"name="+name,null);
    if(i>0){
        return true;
    }
    else{
        return false;
    }



}
public Cursor readAllInfor(){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    Cursor c=sqLiteDatabase.rawQuery("select*from "+Table_Name,null);

    return c;
}

public Cursor readAllInfor(String name){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    Cursor c= sqLiteDatabase.rawQuery("select * from "+Table_Name+" where "+col2 +"=\""+name+"\"",null);
    return c;

}

public boolean deleteInfo(String name){

    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    int i=sqLiteDatabase.delete(Table_Name,"name="+name,null);
    if(i>0){
        return true;
    }
    else{
        return false;
    }

}

}