java – i need to add a new table for favorite list that if the user entered with log in information it can save user favorite list but i dont know how

i’m doing an app that user can add to favorite some drawings but i want each user account is connected to their list in the database, and i am new to android studio and what i want is to connect the favorite list to the logged in user, i tried making two database helper but the app do not processed after log in, and i tried two add the favorite with the log in database helper but it gets error so what should i do?


this is Mainactivity.java

public class MainActivity extends AppCompatActivity {

EditText username, password, repassword;
Button signup, login;
DBHelper DB;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    username = (EditText) findViewById(R.id.username);
    //email = (EditText) findViewById(R.id.email);
    password = (EditText) findViewById(R.id.password);
    repassword = (EditText) findViewById(R.id.repassword);
    signup = (Button) findViewById(R.id.btnsignup);
    login = (Button) findViewById(R.id.btnlogin);
    DB = new DBHelper(this);

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String user = username.getText().toString();
            //String em = email.getText().toString();
            String pass = password.getText().toString();
            String repass = repassword.getText().toString();

            if (user.equals("") || pass.equals("") || repass.equals(""))
                Toast.makeText(MainActivity.this, "Please enter Your Information", Toast.LENGTH_SHORT).show();
            else {
                if (pass.equals(repass)) {
                    Boolean checkuser = DB.checkusername(user);
                    if (checkuser == false) {
                        Boolean insert = DB.insertData(user, pass);
                        if (insert == true) {
                            Toast.makeText(MainActivity.this, "Registered successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this, Home1Activity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(MainActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "The Account Already Registered, Please Login", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "Passwords are not matching", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    });

}}

and here is the loginactivity.java

  public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button btnlogin;
DBHelper DB;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    //getActionBar().setDisplayHomeAsUpEnabled(true);

    username = (EditText) findViewById(R.id.username1);
    password = (EditText) findViewById(R.id.password1);
    btnlogin = (Button) findViewById(R.id.btnlogin1);
    DB = new DBHelper(this);
    //FavDB favDB = new FavDB(this);
    btnlogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String user = username.getText().toString();
            String pass = password.getText().toString();

            if(user.equals("")||pass.equals(""))
                Toast.makeText(LoginActivity.this, "Please enter Username and Password", Toast.LENGTH_SHORT).show();
            else{
                Boolean checkuserpass = DB.checkusernamepassword(user, pass);
                if(checkuserpass==true){
                    Toast.makeText(LoginActivity.this, "Login successfully", Toast.LENGTH_SHORT).show();
                    Intent intent  = new Intent(LoginActivity.this,Home1Activity.class);
                    //startIntent.putExtra();
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(LoginActivity.this, "Invalid Entries", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}}

and here is the homeactivity.java

    public class Home1Activity extends AppCompatActivity {
private DrawerLayout drawer;
ActivityHome1Binding binding;
private Toolbar mtoolbar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home1);
    binding = ActivityHome1Binding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    repleceFragment(new HomeFragment());
    //repleceFragment(new FavouriteFragment());
    mtoolbar = findViewById(R.id.menu_toolbar);
    setSupportActionBar(mtoolbar);
    FavDB favDB = new FavDB(this);

    binding.bottomNavigationView.setOnItemReselectedListener(item -> {
        switch (item.getItemId()){
            case R.id.home:
                repleceFragment(new HomeFragment());
                break;
            case R.id.favourite:
                repleceFragment(new FavouriteFragment());
                break;
            case R.id.artist:
                repleceFragment(new ArtistFragment());
                break;
        } return ;
    });
}
private void repleceFragment(Fragment fragment){
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frameLayout,fragment);
    fragmentTransaction.commit();
}}

here is the DBHelper

   public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Login.db";


public DBHelper(Context context) { super(context, "Login.db", null, 1); }
//public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); }

@Override
public void onCreate(SQLiteDatabase MyDB) {
    MyDB.execSQL("create Table users(username TEXT primary key, password TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase MyDB, int i, int i1) {
    MyDB.execSQL("drop Table if exists users");
}

public Boolean insertData(String username, String password){
    SQLiteDatabase MyDB = this.getWritableDatabase();
    ContentValues contentValues= new ContentValues();
    contentValues.put("username", username);
    contentValues.put("password", password);
    long result = MyDB.insert("users", null, contentValues);
    if(result==-1) return false;
    else
        return true;
}

public Boolean checkusername(String username) {
    SQLiteDatabase MyDB = this.getWritableDatabase();
    Cursor cursor = MyDB.rawQuery("Select * from users where username = ?", new String[]{username});
    if (cursor.getCount() > 0)
        return true;
    else
        return false;
}

public Boolean checkusernamepassword(String username, String password){
    SQLiteDatabase MyDB = this.getWritableDatabase();
    Cursor cursor = MyDB.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password});
    if(cursor.getCount()>0)
        return true;
    else
        return false;
}}

and here is made second Database i thought it will work but it didnt i know i should only have one database but if i added this code to the DBHelper it get all error


favDB

    public class FavDB extends SQLiteOpenHelper {
private static int DB_VERSION = 1;
private static String DATABASE_NAME = "favouriteDB";
private static String TABLE_NAME = "favoriteTable";
public static String KEY_ID = "id";
public static String ITEM_TITLE = "itemTitle";
public static String ITEM_IMAGE = "itemImage";
public static String FAVORITE_STATUS = "fStatus";
// dont forget write this spaces
private static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + KEY_ID + " TEXT," + ITEM_TITLE+ " TEXT,"
        + ITEM_IMAGE + " TEXT," + FAVORITE_STATUS+" TEXT)";

public FavDB(Context context) { super(context,DATABASE_NAME,null,DB_VERSION);}

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

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

// create empty table
public void insertEmpty() {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    // enter your value
    for (int x = 1; x < 11; x++) {
        cv.put(KEY_ID, x);
        cv.put(FAVORITE_STATUS, "0");

        db.insert(TABLE_NAME,null, cv);
    }
}

// insert data into database
public void insertIntoTheDatabase(String item_title, int item_image, String id, String fav_status) {
    SQLiteDatabase db;
    db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(ITEM_TITLE, item_title);
    cv.put(ITEM_IMAGE, item_image);
    cv.put(KEY_ID, id);
    cv.put(FAVORITE_STATUS, fav_status);
    db.insert(TABLE_NAME,null, cv);
    Log.d("FavDB Status", item_title + ", favstatus - "+fav_status+" - . " + cv);
}

// read all data
public Cursor read_all_data(String id) {
    SQLiteDatabase db = this.getReadableDatabase();
    String sql = "select * from " + TABLE_NAME + " where " + KEY_ID+"="+id+"";
    return db.rawQuery(sql,null,null);
}

// remove line from database
public void remove_fav(String id) {
    SQLiteDatabase db = this.getWritableDatabase();
    String sql = "UPDATE " + TABLE_NAME + " SET  "+ FAVORITE_STATUS+" ='0' WHERE "+KEY_ID+"="+id+"";
    db.execSQL(sql);
    Log.d("remove", id.toString());

}

// select all favorite list

public Cursor select_all_favorite_list() {
    SQLiteDatabase db = this.getReadableDatabase();
    String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+FAVORITE_STATUS+" ='1'";
    return db.rawQuery(sql,null,null);
}}

i want the code above to be written in the DBHelper so can use help me


here is favItem.java

   public class FavItem {
private String item_title;
private String key_id;
private int item_image;

public FavItem() {
}

public FavItem(String item_title, String key_id, int item_image) {
    this.item_title = item_title;
    this.key_id = key_id;
    this.item_image = item_image;
}
public String getItem_title() {
    return item_title;
}

public void setItem_title(String item_title) {
    this.item_title = item_title;
}

public String getKey_id() {
    return key_id;
}

public void setKey_id(String key_id) {
    this.key_id = key_id;
}

public int getItem_image() {
    return item_image;
}

public void setItem_image(int item_image) {
    this.item_image = item_image;
}}

here is the drawing adapter

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

private ArrayList<DrawingItem> drawingItems;
private Context context;
private FavDB favDB;
//private DrawingItem drawingItem;

public DrawingAdapter(ArrayList<DrawingItem> drawingItems, Context context) {
    this.drawingItems = drawingItems;
    this.context = context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    favDB = new FavDB(context);
    //create table on first
    SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
    boolean firstStart = prefs.getBoolean("firstStart", true);
    if (firstStart) {
        createTableOnFirstStart();
    }

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fav_item,
          parent, false);
     return new ViewHolder(view);
}

here is drawing item.java

 public class DrawingItem {
private int imageResourse;
private String title;
private String key_id;
private String favStatus;

public DrawingItem() {
}

public DrawingItem(int imageResourse, String title, String key_id, String favStatus) {
    this.imageResourse = imageResourse;
    this.title = title;
    this.key_id = key_id;
    this.favStatus = favStatus;
}

public int getImageResourse() {
    return imageResourse;
}

public void setImageResourse(int imageResourse) {
    this.imageResourse = imageResourse;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getKey_id() {
    return key_id;
}

public void setKey_id(String key_id) {
    this.key_id = key_id;
}

public String getFavStatus() {
    return favStatus;
}

public void setFavStatus(String favStatus) {
    this.favStatus = favStatus;
}}

and this is the Homefragment.java

 public class HomeFragment extends Fragment {

private ArrayList<DrawingItem> drawingItems = new ArrayList<>();

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_home, container, false);

    RecyclerView recyclerView = root.findViewById(R.id.recycleView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(new DrawingAdapter(drawingItems, getActivity()));
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    drawingItems.add(new DrawingItem(R.drawable.girl_with_a_pearl_earing, "Girls with a pearl Earring","0","0"));
    drawingItems.add(new DrawingItem(R.drawable.self_portait_ear, "Self Portrait Ear","1","0"));
    drawingItems.add(new DrawingItem(R.drawable.vase, "Vase with 12 Sunflowers","2","0"));
    drawingItems.add(new DrawingItem(R.drawable.night_cafe, "Coffee Terrace at Night","3","0"));
    drawingItems.add(new DrawingItem(R.drawable.gurnica, "Guernica","4","0"));
    drawingItems.add(new DrawingItem(R.drawable.the_scream, "The Scream","5","0"));
    drawingItems.add(new DrawingItem(R.drawable.the_falling_rocket, "Nocturne in Black and Gold, the Falling Rocket","6","0"));
    drawingItems.add(new DrawingItem(R.drawable.monalisa, "Monalisa","7","0"));
    drawingItems.add(new DrawingItem(R.drawable.impresstion_sunrise, "Impression, Sunrise","9","0"));
    drawingItems.add(new DrawingItem(R.drawable.water_lilies, "Water Lilies","10","0"));
    drawingItems.add(new DrawingItem(R.drawable.the_magpie, "The Magpie","11","0"));


    return root;
}}

so how can i link the user account with what the user added to the list?

Leave a Comment