有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java getReadableDatabase和getWriteableDatabase无法解析

我一直在试图弄明白为什么“getWritableDatabase”和“getReadableDatabase”无法解决问题。我使用了数据库中的一个馈线。如果有人愿意破译我的主要活动和数据库中的所有代码并给出建议,我已经插入了这些代码。非常感谢。谢谢

主要活动

                 public class MainActivity extends AppCompatActivity {

String TAG = "MainActivity";
private ListView  listView ;
DBHelper mydb;
ArrayList<Call_log> calls = new ArrayList();
MyAdapter adapter;
SearchView searchView;

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

    mydb = new DBHelper();
    clear_db();

    getCallDetails();
    listView = (ListView) findViewById(R.id.listView);
    searchView = (SearchView) findViewById(R.id.searchView);

    ArrayList<Call_log> array_list= get();
    adapter =  new MyAdapter(this, array_list);
    listView.setAdapter(adapter);

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALL_LOG},20);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            adapter.items =  adapter.filter(query);
            adapter.notifyDataSetChanged();

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.items =  adapter.filter(newText);
            adapter.notifyDataSetChanged();
            return false;
        }
    });

}



private String getCallDetails() {

    StringBuffer call = new StringBuffer();
    Cursor cursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
            null, null, null);

    int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = cursor.getColumnIndex(CallLog.Calls.DATE);
    int name_index = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
    int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);

    while (cursor.moveToNext()) {
        String phNumber = cursor.getString(number);
        String callType = cursor.getString(type);
        String callDate = cursor.getString(date);
        String name = cursor.getString(name_index);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = cursor.getString(duration);
        String call_type = null;
        int call_type_indicator = Integer.parseInt(callType);
        switch (call_type_indicator) {
            case CallLog.Calls.OUTGOING_TYPE:
                call_type = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                call_type = "INCOMING";
                break;

            case CallLog.Calls.MISSED_TYPE:
                call_type = "MISSED";
                break;
        }

        insert(name,phNumber, call_type, callDuration);
    }

    Log.d("MainActivity","calls: "+call);
    if(cursor.getCount() <= 0){
        call.append("\n No calls in record");
    }
    cursor.close();
    return call.toString();

}
public void insert(String name, String phone, String call_type, String duration  ) {
    // Create a new map of values, where column names are the keys
    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, name);
   values.put(DBHelper.FeedEntry.COLUMN_NAME_PHONE, phone);
   values.put(COLUMN_CALL_TYPE, call_type);
    values.put(DBHelper.FeedEntry.COLUMN_NAME_CALL_DURATION, duration);
    SQLiteDatabase db = mydb.getWritableDatabase();
    // Insert the new row, returning the primary key value of the new row
    long newRowId = db.insert(TABLE_NAME, null, values);
}

public void delete(String phone, int i){
    Log.d(TAG, "deleting "+phone);
    
   SQLiteDatabase db_r = mydb.getReadableDatabase();
    String sql = "delete  from "+TABLE_NAME + " WHERE phone = "+phone;
    Cursor cursor = db_r.rawQuery( sql, null );
    adapter.items.remove(i);
    adapter.notifyDataSetChanged();

    StringBuffer call = new StringBuffer();


    cursor.close();


}
 public void getWhereLike(String name){
    SQLiteDatabase db_r = mydb.getReadableDatabase();
   // How you want the results sorted in the resulting Cursor
    String sortOrder =
            COLUMN_NAME + " DESC";
    Cursor cursor = db_r.rawQuery( "select * from "+TABLE_NAME+" WHERE (name LIKE "+name+" + '%')", null );

}



public  ArrayList<Call_log> get(){
    SQLiteDatabase db_r = mydb.getReadableDatabase();
    Cursor cursor = db_r.rawQuery( "select * from "+TABLE_NAME+" ORDER BY "+COLUMN_NAME, null );
    ArrayList<Call_log> array_list = new ArrayList();

    cursor.moveToFirst();
    int i = 0;
    while(cursor.isAfterLast() == false){
        String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
        String phone =cursor.getString(cursor.getColumnIndex(COLUMN_NAME_PHONE));
        String call_type =  cursor.getString(cursor.getColumnIndex(COLUMN_CALL_TYPE));
        String duration =  cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CALL_DURATION));
        String date =  cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CALL_DATE));
        Call_log call = new Call_log(call_type,date ,phone, duration, name);
        array_list.add(call);
        calls.add(call);
        cursor.moveToNext();
        i++;
    }

    cursor.close();
    return array_list;
}

public void clear_db(){
    SQLiteDatabase db_r = mydb.getWritableDatabase();
    String sql = "delete from "+ TABLE_NAME;
    db_r.execSQL(sql);
}

class MyAdapter extends BaseAdapter {

    private Context context;
    private ArrayList <Call_log> items;

    public MyAdapter( Context context, ArrayList<Call_log> items) {
        this.context = context;
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    public ArrayList filter(String query){
        ArrayList <Call_log> newItems = new ArrayList<>();
        if(query.length() > 0){
            for(Call_log log : calls){
                String name = log.caller_name != null ? log.caller_name: "Unknown";
                if (log.phone.contains(query) || name.contains(query)){
                    newItems.add(log);
                }
            }
            if(newItems.size() < 1){
                Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_LONG).show();

            }

        }else {
            newItems = calls;
        }
        return newItems;

    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        // inflate the layout for each list row
        if (view == null) {
            view = LayoutInflater.from(context).
                    inflate(R.layout.listview_layout, viewGroup, false);
        }
        // get current item to be displayed
        Call_log currentItem = (Call_log) getItem(i);
        // get the TextView for item name and item description
        TextView name =  view.findViewById(R.id.name);
        TextView phone =  view.findViewById(R.id.phone);
        TextView type =  view.findViewById(R.id.type);
        Button row_erase = (Button)  view.findViewById(R.id.row_erase);
        //sets the text for item name and item description from the current item object
        String t =  currentItem.getCaller_name() != null ?  currentItem.getCaller_name(): "Unknown";

        name.setText(t);
        phone.setText(currentItem.getPhone() != null ? currentItem.getPhone(): "Unknown");
        type.setText(currentItem.getType() != null? currentItem.getType() : "Unknown");

        row_erase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delete(currentItem.phone, i);
            }
        });

        // returns the view for the current row
        return view;
    }
}


 }

DBHelper

      package com.example.lab10.db;

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

      import com.example.lab10.bean.Call_log;

    import java.util.ArrayList;
   import java.util.List;

 public class DBHelper {



private static final String TAG=DBHelper.class.getSimpleName();




public static abstract class FeedEntry implements BaseColumns {
    public static final String DB_NAME = "MyDBName.mydb";
    private static final int DB_VERSION = 1;
    public static final String LOG_COLUMN_ID = "id";
    public static final String TABLE_NAME = "Table_Log";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_NAME_PHONE = "phone";
    public static final String COLUMN_CALL_TYPE = "call_type";
    public static final String COLUMN_NAME_CALL_DURATION = "duration";
    public static final String COLUMN_NAME_CALL_DATE = "date";


    //create table table_todo(task_id integer primary key
    private static String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_NAME + "(" +    COLUMN_NAME + " INTEGER PRIMARY KEY, " + COLUMN_NAME_PHONE + " TEXT ," + COLUMN_CALL_TYPE + " TEXT ," + COLUMN_NAME_CALL_DURATION + " TEXT ," + COLUMN_NAME_CALL_DATE + " TEXT )";

    private Context context;
    public SQLiteDatabase sqLliteDatabase;
    public static DBHelper DBHelperInstance;


    public void DBHelper(FeedEntry feedEntry) {
        sqLliteDatabase = new DBAdapter(this.context, DB_NAME, null,    DB_VERSION).getWritableDatabase();
    }


    public static DBHelper getDBHelperInstance(Context context) {
        if (DBHelperInstance == null) {
            DBHelperInstance = new DBHelper();
        }

        return DBHelperInstance;
    }
    
    
    
     //insert,delete,modify,query methods

    public boolean insert(String phone, String call_type, String duration, String date) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_NAME_PHONE, phone);
        contentValues.put(COLUMN_CALL_TYPE, call_type);
        contentValues.put(COLUMN_NAME_CALL_DURATION, duration);
        contentValues.put(COLUMN_NAME_CALL_DATE, date);


        return sqLliteDatabase.insert(TABLE_NAME, null, contentValues) > 0;
    }

    public boolean delete(String phone) {

        return sqLliteDatabase.delete(TABLE_NAME, COLUMN_NAME + " = " + phone, null) > 0;
    }

    public boolean modify(String name, String newPhone, String newCall_type, String newDuration, String newDate) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_NAME_PHONE, newPhone);
        contentValues.put(COLUMN_CALL_TYPE, newCall_type);
        contentValues.put(COLUMN_NAME_CALL_DURATION, newDuration);
        contentValues.put(COLUMN_NAME_CALL_DATE, newDate);

        return sqLliteDatabase.update(TABLE_NAME, contentValues, COLUMN_NAME + " = " + name,   null) > 0;
    }

    public List<Call_log> getAllCallLogs() {
        List<Call_log> calls = new ArrayList<Call_log>();

        Cursor cursor = sqLliteDatabase.query(TABLE_NAME, new String[]{COLUMN_NAME,    COLUMN_NAME_PHONE}, null, null, null, null, null, null);

        if (cursor != null & cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Call_log logs = new Call_log(cursor.getString(0), cursor.getString(1),      cursor.getString(2), cursor.getString(3), cursor.getString(4));
                calls.add(logs);


            }
        }
        cursor.close();
        return calls;
    }

    private static class DBAdapter extends SQLiteOpenHelper {

        public DBAdapter(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int dbVersion) {
            super(context, databaseName, factory, dbVersion);
        }

        @Override
        public void onConfigure(SQLiteDatabase db) {
            super.onConfigure(db);
            db.setForeignKeyConstraintsEnabled(true);
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE_TODO);
        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase,
                              int oldVersion, int newVersion) {
            //Not implemented now
        }

    }
}

共 (1) 个答案

  1. # 1 楼答案

    它无法解决此问题,因为mydb是您拥有的DBHelper类的实例。调用getWritableDatabase&getReadableDatabase方法

    可以在DBHelper类中为SQLiteOpenHelper创建公共字段,也可以创建getter方法来获取数据库