Android使用上下文菜单实现LISTVIEW,尝试添加"收藏夹"



你好,我是安卓编程的初学者。 我有这个带有sqlite数据库的食谱应用程序。 我已经完成了带有添加到收藏夹的上下文菜单的制作。我的问题是我不知道如何将所选食谱放入名为"收藏夹"的dbase表中。根据TOAST我已经获得了列表视图的位置。

这是我的主要活动课

public class MainActivity extends Activity {
protected ListView lv;
protected ListAdapter adapter;
SQLiteDatabase db;
Cursor cursor;
EditText et_db;
int itemPos;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    db = (new DB_Resep(this)).getWritableDatabase();
    lv = (ListView) findViewById(R.id.lv);
    et_db = (EditText) findViewById(R.id.et);
    registerForContextMenu(lv);
    try {
        cursor = db.rawQuery("SELECT * FROM recipe ORDER BY name ASC", null);
        adapter = new SimpleCursorAdapter(this, R.layout.isi_lv, cursor,
                new String[] { "name", "ingredients", "img" }, new int[] {
                        R.id.tv_nama, R.id.tvBahan, R.id.imV });
        lv.setAdapter(adapter);
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                detail(position);
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@SuppressWarnings("deprecation")
public void search_db(View v) {
    String edit_db = et_db.getText().toString();
    if (!edit_db.equals("")) {
        try {
            cursor = db.rawQuery("SELECT * FROM recipe WHERE name LIKE ?",new String[] { "%" + edit_db + "%" });
            adapter = new SimpleCursorAdapter(this,R.layout.isi_lv,cursor,
                    new String[] { "name", "ingredients", "img" },
                    new int[] { R.id.tv_nama, R.id.tvBahan, R.id.imV });
            if (adapter.getCount() == 0) {
                Toast.makeText(
                        this,
                        "No Data Found " + edit_db
                                + "", Toast.LENGTH_SHORT).show();
            } else {
                lv.setAdapter(adapter);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            cursor = db.rawQuery("SELECT * FROM recipe ORDER BY name ASC",
                    null);
            adapter = new SimpleCursorAdapter(
                    this,
                    R.layout.isi_lv,
                    cursor,
                    new String[] { "name", "ingredients", "img" },
                    new int[] { R.id.tv_nama, R.id.tvBahan, R.id.imV });
            lv.setAdapter(adapter);
            lv.setTextFilterEnabled(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public void detail(int position) {
    int im = 0;
    String _id = "";
    String name = "";
    String ingredients = "";
    String procedure = "";
    if (cursor.moveToFirst()) {
        cursor.moveToPosition(position);
        im = cursor.getInt(cursor.getColumnIndex("img"));
        name = cursor.getString(cursor.getColumnIndex("name"));
        ingredients = cursor.getString(cursor.getColumnIndex("ingredients"));
        procedure = cursor.getString(cursor.getColumnIndex("procedure"));
    }
    Intent iIntent = new Intent(this, DB_Parse.class);
    iIntent.putExtra("dataIM", im);
    iIntent.putExtra("dataname", name);
    iIntent.putExtra("dataBahan", ingredients);
    iIntent.putExtra("dataCara", procedure);
    setResult(RESULT_OK, iIntent);
    startActivityForResult(iIntent, 99);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    // TODO Auto-generated method stub
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu,menu);
}
@SuppressLint("ShowToast") @Override
public boolean onContextItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    AdapterContextMenuInfo info =(AdapterContextMenuInfo)item.getMenuInfo();
    itemPos = info.position;
    ContentValues values = new ContentValues();
    switch (item.getItemId()) {
    case R.id.addtofavorites:

        Toast.makeText(getBaseContext(), "Added to Favorites"+itemPos, Toast.LENGTH_SHORT).show();
        return true;
    default:
    return super.onContextItemSelected(item);
    }
}

}

list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
       @Override
       public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                      int position, long rowId) {
           TextView id = (TextView) arg1.findViewById(R.id.listselectedid);
String strId=id.getText().toString;
 dbutil.addData(strId); // adding that string into local db
}
}

您可以将列表项转换为 json 并将其放在共享首选项中,而不是添加到数据库中

创建类共享首选项.java如下所示

public class SharedPreference

{

public static final String PREFS_NAME = "MY_APP";
public static final String FAVORITES = "MY_Favorite";
public SharedPreference(){
    super();
}
public void saveFavorites(Context context, List<CodeList> favorites){
    SharedPreferences settings;
    Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME,
                                            Context.MODE_PRIVATE);
    editor = settings.edit();
    Gson gson = new Gson();
    String jsonFavorites = gson.toJson(favorites);
    editor.putString(FAVORITES, jsonFavorites);
    editor.commit();
}
public void addFavorite(Context context, CodeList code){
    List<CodeList> favorites = getFavorites(context);
    if(favorites == null)
        favorites = new ArrayList<CodeList>();
    favorites.add(code);
    saveFavorites(context,favorites);
}
public void removeFavorite(Context context, CodeList code) {
    ArrayList<CodeList> favorites = getFavorites(context);
    if (favorites != null) {
        favorites.remove(code);
        saveFavorites(context, favorites);
    }
}

public ArrayList<CodeList> getFavorites(Context context) {
    SharedPreferences settings;
    List<CodeList> favorites;
    //ArrayList<CodeList> favorites;
    settings = context.getSharedPreferences(PREFS_NAME,
                                            Context.MODE_PRIVATE);
    if (settings.contains(FAVORITES)) {
        String jsonFavorites = settings.getString(FAVORITES, null);
        Gson gson = new Gson();
        CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
                                                 CodeList[].class);
        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<CodeList>(favorites);
        //favorites  = new ArrayList<CodeList>();
      //favorites.addAll(Arrays.asList(favoriteItems));
    } else
        return null;
    return (ArrayList<CodeList>) favorites;
    //return favorites;
}

}

然后在"收藏夹"

按钮上使用"将收藏夹"方法添加到列表项

不要忘记将 GSONLIBRARY 添加为您的格拉德尔的部门

最新更新