收藏夹列表,检查项目是否已记录在SQLite中

时间:2017-03-01 09:04:21

标签: android database sqlite

我是android编码的新手...... 我创建了一些活动和Sqlite ...... 我在我的活动中添加了一个按钮,将一些数据存储到数据库中,但每次我们点击按钮时都会向数据库中添加相同的数据... 如何检查数据库中是否已存在数据?!!!

我创建了一个listView来显示一些数据,当我们点击每个项目时它将我们引导到一个新的活动,在新的活动中我创建了一个新的按钮来存储数据库中的数据,所以我想看看我怎么能找出数据已经存在,因此按钮可以关闭,如果不存在,按钮应该打开...

这是我的代码: 数据库:

public class PhraseDataBaseAdapter {

private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;

public PhraseDataBaseAdapter(Context context){
    this.context = context;
    sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, 1) {
        @Override
        public void onCreate(SQLiteDatabase db) {
            String sql = "create table tb1_phrases (id integer primary key, eng text, per text)";
            db.execSQL(sql);
        }

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

        }
    };

}

public long savePhrase(Phrases phrases){
    String eng = phrases.getEng();
    String per = phrases.getPer();
    long id = -1;

    SQLiteDatabase database = null;

    try{
        ContentValues values = new ContentValues();
        values.put("eng", eng);
        values.put("per", per);

        database = sqLiteOpenHelper.getWritableDatabase();
        id = database.insert("tb1_phrases", null, values);
    }catch (Exception ex){
        Log.d("Database", "Exception: " + ex.getMessage());
    }finally {
        if (database!=null && database.isOpen()){
            database.close();
        }
    }
    return id;
}

public Phrases readPhrase(long id){
    Phrases phrases = null;
    String[] columns = new String[]{"id", "eng", "per"};
    String selection = "id=?";
    String[] selectionArgs = new String[]{String.valueOf(id)};
    String groupBy = null;
    String having = null;
    String orderBy = null;
    String limit = null;

    SQLiteDatabase database = null;

    try{
        database = sqLiteOpenHelper.getWritableDatabase();
        Cursor cursor = database.query("tb1_phrases", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
        if (cursor !=null && cursor.moveToFirst()){
            int idIndex = 0;
            int engIndex = 1;
            int perIndex = 2;

            long phraseId = cursor.getLong(idIndex);
            String phraseEng = cursor.getString(engIndex);
            String phrasePer = cursor.getString(perIndex);

            phrases = new Phrases();
            phrases.setId(phraseId);
            phrases.setEng(phraseEng);
            phrases.setPer(phrasePer);
        }
    }catch (Exception ex){
        Log.d("Database", "Exception: " + ex.getMessage());
    }finally {
        if (database!=null && database.isOpen()){
            database.close();
        }
    }
    return phrases;
}

public int updatePhrase(Phrases phrases){
    int noOfDataUpdatedRecords = 0;
    String whereClause = "id=?";
    String[] whereArgs = new String[]{String.valueOf(phrases.getId())};

    SQLiteDatabase database = null;

    try{
        ContentValues values = new ContentValues();
        values.put("eng", phrases.getEng());
        values.put("per", phrases.getPer());

        database = sqLiteOpenHelper.getWritableDatabase();
        noOfDataUpdatedRecords = database.update("tb1_phrases", values, whereClause, whereArgs);
    }catch (Exception ex){
        Log.d("Database", "Exeption: " + ex.getMessage());
    } finally {
        if(database!=null && database.isOpen()){
            database.close();
        }
    }
    return noOfDataUpdatedRecords;
}

public int deletePhrase(long id){
    int noOfDeletedRecords = 0;
    String whereClause = "id=&";
    String[] whereArgs = new String[]{String.valueOf(id)};

    SQLiteDatabase database = null;

    try{
        database = sqLiteOpenHelper.getWritableDatabase();
        noOfDeletedRecords = database.delete("tb1_phrases", whereClause, whereArgs);
    }catch (Exception ex){
        Log.d("Database", "Exception: " + ex.getMessage());
    } finally {
        if(database!=null && database.isOpen()){
            database.close();
        }
    }
    return noOfDeletedRecords;
}

public ArrayList<Phrases> readAllPhrases(){
    ArrayList<Phrases> phrasesArrayList = null;
    String[] columns = new String[]{"id", "eng", "per"};
    String selection = null;
    String[] selectionArgs = null;
    String groupBy = null;
    String having = null;
    String orderBy = null;
    String limit = null;

    SQLiteDatabase database = null;

    try{
        database = sqLiteOpenHelper.getWritableDatabase();
        Cursor cursor = database.query("tb1_phrases", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
        if (cursor !=null && cursor.moveToFirst()){
            phrasesArrayList = new ArrayList<>();

            int idIndex = 0;
            int engIndex = 1;
            int perIndex = 2;

            do {
                long phraseId = cursor.getLong(idIndex);
                String phraseEng = cursor.getString(engIndex);
                String phrasePer = cursor.getString(perIndex);

                Phrases phrases = new Phrases();
                phrases.setId(phraseId);
                phrases.setEng(phraseEng);
                phrases.setPer(phrasePer);

                phrasesArrayList.add(phrases);
            }while (cursor.moveToNext());
        }
    }catch (Exception ex){
        Log.d("Database", "Exception: " + ex.getMessage());
    }finally {
        if (database!=null && database.isOpen()){
            database.close();
        }
    }
    return phrasesArrayList;
}

收藏夹按钮:

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


            PhraseDataBaseAdapter dataBaseAdapter = new PhraseDataBaseAdapter(getApplicationContext());
            Phrases phrases = new Phrases();
            phrases.setEng(mainAdviceEnglish);
            phrases.setPer(mainAdvicePersian);
            dataBaseAdapter.savePhrase(phrases);
        }
    });

...谢谢

1 个答案:

答案 0 :(得分:0)

根据您的要求,我有一个很好的解决方案,而不使用SQLite。 您应该使用此类来存储您的单词,并且还具有检查这些单词是否已存储的功能。

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class WordListPref {
public static final String PREFS_NAME = "XYZ";
public static final String WORD_LIST = "WordList";


public void storeWords(Context context, List favorites) {
    // used for store arrayList in json format
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
    Gson gson = new Gson();
    String jsonFavorites = gson.toJson(favorites);
    editor.putString(WORD_LIST, jsonFavorites);
    editor.commit();
}

public ArrayList<String> loadWords(Context context) {

    // used for retrieving arraylist from json formatted string
    SharedPreferences settings;
    List favorites;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    if (settings.contains(WORD_LIST)) {
        String jsonFavorites = settings.getString(WORD_LIST, null);
        Gson gson = new Gson();
        String[] favoriteItems = gson.fromJson(jsonFavorites, String[].class);
        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList(favorites);
    } else
        return new ArrayList<>();
    return (ArrayList) favorites;
}

public void addWord(Context context, String beanSampleList) {
    List favorites = loadWords(context);
    if (favorites == null)
        favorites = new ArrayList();
    favorites.add(beanSampleList);
    storeWords(context, favorites);
}

public void removeUsers(Context context, String beanSampleList) {

    ArrayList<String> favorites = loadWords(context);
    if (favorites != null) {
        for (int i = 0; i < favorites.size(); i++) {
            String bean = favorites.get(i);
            if (bean == beanSampleList) {
                favorites.remove(i);
                storeWords(context, favorites);
            }

        }

    }

}

public boolean isWordExist(String bean, Context context) {

    ArrayList<String> data = loadWords(context);
    if (data != null) {

        for (int i = 0; i < data.size(); i++) {
            String beanSampleList = data.get(i);
            if (bean == beanSampleList) {
                return true;
            }
        }
    }
    return false;
}

public void flushWordPref(Context context) {
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
    editor.clear();
    editor.commit();
}
}

用于存储Word使用方法

  

addWord( “”)

用于检查单词退出

  

isWordExist()

这个类可以解决你的问题,你永远不会使用sqlite来做同样的事情。 祝你好运,别忘了投票:)