2017-06-28 14 views
0

ナビゲーションメニュー付きナビゲーション棚があります。各アイテムのナビゲーションドロワーをクリックすると、1つのフラグメントがロードされます。各フラグメントの内部では、外部SQLiteデータベースからデータをロードし、Recyclerviewで表示します。今すぐお気に入りボタンを追加したいときは、それをクリックするとお気に入りアイテムに追加されたアイテムと背景ボタンが好きに変更されます。または、お気に入りアイテムをクリックするとUnFavoritedアイテムと背景がUnLikedボタンに変わりました。私はテーブルの "お気に入り"の列を作成し、それぞれの生の値を0 =テキストにintiallizedします。なぜなら、最初に読み込まれたときには何もお気に入りではないからです。今私はどのようにこの機能を行っていません。私を助けてください。AndroidのプログラミングでSQLiteデータベースを使ってお気に入りのアクティビティにアイテムを追加する方法

これは、これは私のContentAdapter

public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> { 

public Context context; 
private boolean isFavorite; 
WorldCountryDatabase worldCountryDatabase; 
private List<AsiaCountry> item = Collections.emptyList(); 
private int mLastPosition = -1; 
private Listener listener; 


public ContentAdapter(Context context, List<AsiaCountry> item) { 
    this.context = context; 
    this.item = item; 

} 


public void setListener(Listener listener) { 
    this.listener = listener; 
} 

@Override 
public ContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) { 
    //Defain the view for take layout 
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, 
      parent, false); 
    Log.d("Adapter", "Loaded"); 
    return new ViewHolder(view); 
} 

@Override 
public void onBindViewHolder(final ViewHolder holder, final int position) { 


    final AsiaCountry asia = item.get(position); 

    isFavorite = true; 
    holder.titleNameCountry.setText(asia.getName()); 
    Log.d("TAG", asia.getName()); 


    Glide.with(context).load(asia.getFlag(context)).into(holder.titleImageCountry); 


    holder.itemView.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if (listener != null) { 
       listener.onClick(position); 

       String nameCountry = holder.titleNameCountry.getText().toString(); 

       Intent intent = new Intent(context, DetailsCountry.class); 
       intent.putExtra("name", nameCountry); 
       Log.d("CONT", nameCountry); 

       context.startActivity(intent); 
      } 
     } 
    }); 


    if (position > mLastPosition) { 
     AnimatorSet animatorSet = new AnimatorSet(); 
     animatorSet.playTogether(
       ObjectAnimator.ofFloat(holder.itemView, "translationY", 
         holder.itemView.getMeasuredHeight() * 2, 0)); 
     ObjectAnimator.ofFloat(holder.itemView, "alpha", 0, 1); 
     ObjectAnimator.ofFloat(holder.itemView, "scaleX", 0.5f, 1); 
     ObjectAnimator.ofFloat(holder.itemView, "scaleY", 0.5f, 1); 


     animatorSet.setInterpolator(new DecelerateInterpolator()); 
     animatorSet.start(); 

     mLastPosition = position; 
    } else { 

     ViewHolder.clear(holder.itemView); 
    } 


} 

private void updateUnFavoriteCountry() { 

    AsiaCountry asiaCountry; 
    int position = item.size(); 
    asiaCountry = item.get(position); 
    String nameCountry = asiaCountry.getName(); 
    worldCountryDatabase.QueryData("UPDATE country SET FavoriteCountry = 1 WHERE name =' " + nameCountry); 
    worldCountryDatabase.close(); 
} 

private void updateFavoriteCountry() { 

    AsiaCountry asiaCountry; 
    int position = item.size(); 
    asiaCountry = item.get(position); 
    String nameCountry = asiaCountry.getName(); 
    worldCountryDatabase.QueryData("UPDATE country SET FavoriteCountry = 0 WHERE name =' " + nameCountry); 
    worldCountryDatabase.close(); 
} 

@Override 
public int getItemCount() { 
    return item.size(); 
} 

public void setFilter(ArrayList<AsiaCountry> arrayList) { 

    item.clear(); 
    item.addAll(arrayList); 
    notifyDataSetChanged(); 
} 

public static interface Listener { 
    public void onClick(int position); 
} 

public static class ViewHolder extends RecyclerView.ViewHolder { 

    private ImageView titleImageCountry; 
    public TextView titleNameCountry; 
    private ImageButton favoriteCountry; 
    private ImageButton shareFavoriteCountry; 

    // Defian the viewHolder 
    private ViewHolder(View itemView) { 
     super(itemView); 

     titleImageCountry = (ImageView) itemView.findViewById(R.id.imageHolder); 
     titleNameCountry = (TextView) itemView.findViewById(R.id.titleCountry); 
     favoriteCountry = (ImageButton) itemView.findViewById(R.id.favoriteCountryImage); 
     shareFavoriteCountry = (ImageButton) itemView.findViewById(R.id.shareFavoriteCountry); 
    } 

    // public static class ViewHolder { 

    private static void clear(View itemView) { 
     ViewCompat.setAlpha(itemView, 1); 
     ViewCompat.setTranslationY(itemView, 0); 
     itemView.setPivotY(itemView.getMeasuredHeight()/2); 
     ViewCompat.setScaleX(itemView, 1); 
     ViewCompat.setScaleY(itemView, 1); 
     ViewCompat.animate(itemView).setInterpolator(null); 
     Log.d("Animationg", "Loaded"); 


    } 
} 

}

私は以下のような項目をロードし、ボタンのようにクリックしたときに、でなければなりません私のWorldCOuntryDabase

public class WorldCountryDatabase extends SQLiteOpenHelper { 

private static final String TAG = "databaseHelper"; 
private static final String DB_NAME = "worldCountries.db"; 
private static final int DB_VERSION = 1; 
private static final String TABLE_NAME = "country"; 
private static String DB_PATH = ""; 
private Context mContext; 
private SQLiteDatabase database; 


public WorldCountryDatabase(Context context) { 
    super(context, DB_NAME, null, DB_VERSION); 

    DB_PATH = context.getDatabasePath(DB_NAME).getPath(); 

    File file = new File(DB_PATH + "worldCountries.db"); 
    if (file.exists()) 

     openDataBase(); 

    this.mContext = context; 


} 

public void createDatabase() { 

    boolean dbExist = checkDatabase(); 

    if (dbExist) { 

     Log.d("MIN1", "Database already Exist"); 

    } else { 
     this.getReadableDatabase(); 
    } 
    try { 
     copyDataBase(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Log.i("MIN2", e.getMessage()); 

    } 


} 

private boolean checkDatabase() { 
    SQLiteDatabase checkDB = null; 

    try { 


     String myPath = DB_PATH + DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 

    } catch (SQLiteException e) { 
     e.printStackTrace(); 
     Log.d("MIN3", e.getMessage()); 

    } 
    if (checkDB != null) { 
     checkDB.close(); 
    } 
    return checkDB != null; 
} 

public synchronized void close() { 
    if (database != null) { 
     database.close(); 
     SQLiteDatabase.releaseMemory(); 
    } 
    super.close(); 

} 


private void copyDataBase() throws IOException { 

    try { 


     InputStream in = mContext.getAssets().open(DB_NAME); 
     String outFileName = DB_PATH + DB_NAME; 
     OutputStream out = new FileOutputStream(outFileName); 
     byte[] buffer = new byte[1024]; 
     int length; 

     while ((length = in.read(buffer)) > 0) { 
      out.write(buffer, 0, length); 
     } 


     out.flush(); 
     out.close(); 
     in.close(); 

     Log.d("MIN4", "Database copy"); 


    } catch (SQLiteException e) { 
     Log.d("MIN5", e.getMessage()); 

    } 
} 

public Cursor QueryData(String query) { 
    return database.rawQuery(query, null); 
} 


@Override 
public void onCreate(SQLiteDatabase db) { 

    Log.d("MIN6", "onCreate"); 



} 

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




    Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion + 
      "Which will destroy all oldest data"); 


    if (newVersion > oldVersion) { 
     try { 
      copyDataBase(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 


} 

public void openDataBase() { 

    String myPath = DB_PATH + DB_NAME; 
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 
    Log.d("MIN7", "Opened database"); 


} 

// CRUD Table 
public List<Questions> getAllQuestions() { 

    List<Questions> questionsList = new ArrayList<>(); 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor c; 

    try { 
     c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null); 
     if (c == null) return null; 
     c.moveToFirst(); 
     do { 
      int Id = c.getInt(c.getColumnIndex("id")); 
      String Image = c.getString(c.getColumnIndex("Image")); 
      String AnswerA = c.getString(c.getColumnIndex("AnswerA")); 
      String AnswerB = c.getString(c.getColumnIndex("AnswerB")); 
      String AnswerC = c.getString(c.getColumnIndex("AnswerC")); 
      String AnswerD = c.getString(c.getColumnIndex("AnswerD")); 
      String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer")); 

      Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer); 
      questionsList.add(question); 


     } while (c.moveToNext()); 
     c.close(); 


    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    database.close(); 
    return questionsList; 
} 


// Insert Score to Ranking table. 
public void insertScore(double score) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues content = new ContentValues(); 
    content.put("Score", score); 
    db.insert("Ranking", null, content); 
} 

// Get score and sort Ranking. 
public List<Ranking> getRanking() { 

    List<Ranking> rankingList = new ArrayList<>(); 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor c; 
    try { 
     c = db.rawQuery("SELECT * FROM Ranking ORDER BY Score DESC;", null); 
     if (c == null) return null; 
     c.moveToFirst(); 
     do { 

      int Id = c.getInt(c.getColumnIndex("Id")); 
      int Score = c.getInt(c.getColumnIndex("Score")); 

      Ranking ranking = new Ranking(Id, Score); 
      rankingList.add(ranking); 


     } while (c.moveToNext()); 
     c.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    db.close(); 
    return rankingList; 
} 


//Update version 2.0 
public int getPlayCount(int level) { 
    int result = 0; 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor c; 
    try { 
     c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level=" + level + ";", null); 
     if (c == null) return 0; 
     c.moveToNext(); 
     do { 
      result = c.getInt(c.getColumnIndex("PlayCount")); 
     } while (c.moveToNext()); 
     c.close(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    return result; 
} 

public void updatePlayCount(int level, int PlayCount) { 
    String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d", PlayCount, level); 
    database.execSQL(query); 
} 

です好きなアイテムにアイテムが追加されました。データベース内

+1

へようこそ起こるのだろうスタックオーバーフロー。 [ツアー]に参加してください。ちょうどいいアイデアだから、バッジをもらえます。あなたの問題に関しては、SQLiteのコマンドラインツールでちょっとしたおもちゃデータベースを作って、それを純粋なSQLite構文で演奏することで、データベース側に集中することをお勧めします。そのおもちゃのデータベースは、読者があなたの質問を理解するのを助ける非常に素晴らしい[mcve]の役割も果たします。 – Yunnosch

+0

@Yunnosch私の質問ははっきりしていると思います。 –

答えて

1

Recylerview items inside fragment、ITEM_TABLEは整数値を持つ列FAVORITEを有していなければならない(0 ==偽と1 == TRUE)。お気に入りのユーザーがボタンをクリック1.

にFAVORITE値を変更するとさらにあなたは、あなたの項目の設定リスナーをすべき項目FAVORITE値が変わるので、もし何かが(ボタンのデザイン意志変化等...)

+0

お返事ありがとうございます。私は型の列を整数に変更します。私はプロセスを知っていますが、これを行うためのコードを書く方法がわかりません。 –

関連する問題