Multiple List RecyclerView SQLitedatabase - java

here's the structure
I have an app that makes the users' all his/her favorites placed on one place. So that he/she will not go through all the data. All I want is to have a recyclerview with multiple list that the "ListTitle" dynamically created, and when the "ListTitle" is already in it, only the child will appear. If not, create again another cardview. Thanks in advance.
My Code:
LoadsFavoriteAdapter.java
public class LoadFavoritesAdapter extends RecyclerView.Adapter<LoadFavoritesAdapter.LoadFavoritesViewHolder> {
private ArrayList<LoadFavorites> loadFavorites;
private Context context;
private ArrayList<LoadFavorites> mloadFavorites;
final String loadParent = "";
public LoadFavoritesAdapter(ArrayList<LoadFavorites> loadFavorites, Context context){
this.loadFavorites = loadFavorites;
this.context = context;
this.mloadFavorites = loadFavorites;
}
public class LoadFavoritesViewHolder extends RecyclerView.ViewHolder{
TextView txtLoadNameTest, txtLoadAmountTest;
public LoadFavoritesViewHolder(View view){
super(view);
txtLoadAmountTest = view.findViewById(R.id.txtLoadAmountTest);
txtLoadNameTest = view.findViewById(R.id.txtLoadNameTest);
}
}
public LoadFavoritesViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favorite_item, parent, false);
return new LoadFavoritesViewHolder(itemView);
}
public void onBindViewHolder(final LoadFavoritesViewHolder holder, int position){
holder.txtLoadNameTest.setText(loadFavorites.get(position).getLoadName());
holder.txtLoadAmountTest.setText(loadFavorites.get(position).getLoadAmount());
}
public int getItemCount(){
return mloadFavorites.size();
}}
Favorites.java
public class Favorites extends AppCompatActivity {
Database localDb;
Context CTX = this;
private RecyclerView recyclerView;
private ArrayList<LoadFavorites> loadFavorites;
private LoadFavoritesAdapter loadFavoritesAdapter;
private Database database;
private ArrayList<LoadFavorites> mloadFavorites;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
localDb = new Database(this);
recyclerView = findViewById(R.id.recycler_favorites);
loadFavorites = new ArrayList<>();
loadFavoritesAdapter = new LoadFavoritesAdapter(loadFavorites, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(loadFavoritesAdapter);
database = new Database(this);
getDataFromSQLite();
}
private void getDataFromSQLite(){
new AsyncTask<Void, Void, Void>(){
protected Void doInBackground(Void... params){
loadFavorites.clear();
loadFavorites.addAll(database.getFavorites());
return null;
}
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
}
}.execute();
}}
Database.java
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="Favorites.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
try{
String myPath = context.getFilesDir().getAbsolutePath(); // also check the extension of you db file
File dbfile = new File(myPath);
if(dbfile.exists()){
Toast.makeText(context, "database exists", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cant find database", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}
}
catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
}
public void addToFavorites(String loadId, String loadName, String loadDetail, String loadNumber, String loadDuration, String loadAmount, String loadParent){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO Favorites(LoadId, LoadName, LoadDetail, LoadNumber, LoadDuration, LoadAmount, LoadParent) VALUES('%s','%s','%s','%s','%s','%s','%s');", loadId, loadName, loadDetail, loadNumber, loadDuration, loadAmount, loadParent);
db.execSQL(query);
}
public void removeFromFavorites(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM Favorites WHERE LoadId='%s';", loadId);
db.execSQL(query);
}
public boolean isFavorite(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT * FROM Favorites WHERE LoadId='%s';", loadId);
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
public Cursor getInformation(Database database){
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] columns = {"LoadId", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor CR = qb.query(db,columns,null,null,null,null,null);
return CR;
}
public List<LoadFavorites> getFavorites(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"LoadId", "LoadName", "LoadDetail", "LoadNumber", "LoadDuration", "LoadAmount", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<LoadFavorites> result = new ArrayList<>();
if(c.moveToFirst()){
do{
result.add(new LoadFavorites(c.getString(c.getColumnIndex("LoadId")),
c.getString(c.getColumnIndex("LoadName")),
c.getString(c.getColumnIndex("LoadDetail")),
c.getString(c.getColumnIndex("LoadNumber")),
c.getString(c.getColumnIndex("LoadDuration")),
c.getString(c.getColumnIndex("LoadAmount")),
c.getString(c.getColumnIndex("LoadParent"))
));
}while(c.moveToNext());
}
return result;
}}

Related

ListView not populating using Cursoradapter

I have an input page which submits 4 strings into the helper. The helper is supposed to get the data and put it into the listView.
When I insert my data, the app doesnt crash but it leads me to the listview page with no rows inflated. The 4 data inputs are all strings and is submitted through a button. I'm not too sure what is wrong with my code. Would appreciate some advice :)
listview code
public class MyActivitiesPage extends AppCompatActivity {
private Cursor model = null;
private ListView list;
private dbHandler helper = null;
private activityAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activities_page);
helper = new dbHandler(this);
list = findViewById(R.id.listView);
model = helper.getall();
adapter = new activityAdapter(this, model, 0);
list.setAdapter(adapter);
}
public static class activityHolder {
private TextView activitytext;
private TextView datetext;
private TextView timetext;
private TextView addresstext;
activityHolder(View row) {
activitytext = row.findViewById(R.id.activitytext);
datetext = row.findViewById(R.id.datetext);
timetext = row.findViewById(R.id.timetext);
addresstext = row.findViewById(R.id.addresstext);
}
void populateFrom(Cursor c, dbHandler helper){
activitytext.setText(helper.getActi(c));
datetext.setText(helper.getDate(c));
timetext.setText(helper.getTime(c));
addresstext.setText(helper.getAddr(c));
}
}
class activityAdapter extends CursorAdapter {
activityAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
}
public void bindView(View view, Context context, Cursor cursor) {
activityHolder holder = (activityHolder) view.getTag();
holder.populateFrom(cursor, helper);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
activityHolder holder = new activityHolder(row);
row.setTag(holder);
return (row);
}
}
helper code
public class dbHandler extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "handler.db";
private static final int SCHEMA_VERSION = 1;
public dbHandler(#Nullable Context context){
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
//Will be called ones when the database is not created
db.execSQL("CREATE TABLE dbTable ( _id INTEGER PRIMARY KEY AUTOINCREMENT, acti TEXT, date TEXT, time TEXT, addr TEXT );");
}
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
//Will not be called upon until SCHEMA_VERSION increases
//For future upgrades
}
public Cursor getall() {
return (getReadableDatabase().rawQuery("SELECT * FROM dbTable", null));
}
public Cursor getById(String id) {
String[] args = {id};
return (getReadableDatabase().rawQuery("SELECT _id, acti, date, time, addr FROM dbTable WHERE _ID = ?", args));
}
public void insert(String acti, String date, String time, String addr) {
ContentValues cv = new ContentValues();
cv.put("acti", acti);
cv.put("date", date);
cv.put("time", time);
cv.put("addr", addr);
long result = getWritableDatabase().insert("dbTable", "firstvalue", cv);
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
public void updateDetails(String id, String acti, String date, String time, String addr) {
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("acti", acti);
cv.put("date", date);
cv.put("time", time);
cv.put("addr", addr);
getWritableDatabase().update("dbTable", cv, " _ID = ?", args);
}
public String getID(Cursor c) { return (c.getString(0));}
public String getActi(Cursor c) { return (c.getString(1));}
public String getDate(Cursor c) { return (c.getString(2));}
public String getTime(Cursor c) { return (c.getString(3));}
public String getAddr(Cursor c) { return (c.getString(4));}
}```

Radio Button is messed up when its scrolling

i have 57 radio button in list view, i want to divide those radio button into 19 groups, so each group has 3 radio button. but when i scrolled it the view is messed up and automatically adding radio button become double.
the data is gotten from sqlite database.
KlasifikasiActivity
public class KlasifikasiActivity extends AppCompatActivity {
private ListView lvKlasifikasi;
private ListKlasifikasiAdapter adapter;
private List<Klasifikasi> mKlasifikasiList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klasifikasi);
lvKlasifikasi = (ListView)findViewById(R.id.stepSwitcher);
mDBHelper = new DatabaseHelper(this);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if (false == database.exists()){
mDBHelper.getReadableDatabase();
if (copyDatabase(this)){
Toast.makeText(this,"COPY SUCCESS",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"COPY ERROR",Toast.LENGTH_SHORT).show();
return;
}
}
//get db metode
mKlasifikasiList = mDBHelper.getListKlasifikasiByGroup();
adapter = new ListKlasifikasiAdapter(this,mKlasifikasiList);
lvKlasifikasi.setAdapter(adapter);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0){
outputStream.write(buff,0,length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
DatabaseHelper and function method
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "database.db";
public static final String DBLOCATION = "/data/data/com.example.damar.finalproject/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context,DBNAME,null,1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if (mDatabase!=null){
mDatabase.close();
}
}
public List<Klasifikasi> getListKlasifikasiByGroup(){
Klasifikasi klasifikasi = null;
List<Klasifikasi> klasifikasiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM klasifikasi group by group_index", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
klasifikasi = new Klasifikasi(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getInt(4));
klasifikasiList.add(klasifikasi);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return klasifikasiList;
}
}
have you checked list just after fetching from db and before set to adapter

Delete data from ListView (Android Studio)

I have 3 java classes (MainActivity, DatabaseOpenHelper and DatabaseAccess)
My add and show buttons work perfectly, but not my delete button. Add adds name and nickname into the database, show shows the list of names in the same layout under the buttons.
Here is my code in MainActivity.class
public class MainActivity extends AppCompatActivity {
public EditText name123, dogName, dogNickname;
public Button query_button, add_button, show_button, delete_button;
public TextView result_address;
public ListView listView;
ArrayList<String> naziv = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name123 = findViewById(R.id.name);
query_button = findViewById(R.id.query_button);
result_address = findViewById(R.id.result);
dogName = findViewById(R.id.et_dogName);
dogNickname = findViewById(R.id.et_dogNickname);
add_button = findViewById(R.id.add_button);
show_button = findViewById(R.id.show_button);
delete_button = findViewById(R.id.delete_button);
listView = findViewById(R.id.doglistview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, naziv);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
long result = databaseAccess.add(dogName.getText().toString(), dogNickname.getText().toString());
if(result > 0){
dogName.setText("");
dogNickname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Dodaj ime i nadimak", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
show_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
naziv.clear();
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Cursor cnn = databaseAccess.getAllNames();
while (cnn.moveToNext()){
String name = cnn.getString(0);
naziv.add(name);
}
listView.setAdapter(adapter);
databaseAccess.close();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), naziv.get(position), Toast.LENGTH_SHORT).show();
}
});
//setting onclicklistener to query button
query_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//create the instance of database access class and open database connection
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
//getting sting value of edittext
String n = name123.getText().toString();
String address = databaseAccess.getAddress(n);//getAddress method to get address
//setting text to result field
result_address.setText(address);
databaseAccess.close();
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Integer deletedRows = databaseAccess.deleteData("id_dogName");
if (deletedRows > 0){
Toast.makeText(MainActivity.this, "Deleted data", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Data not deleted", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
}
}
And here is the code from DatabaseAccess.class:
public class DatabaseAccess {
static final String NAME = "name_dogName";
static final String NICKNAME = "nickname_dogName";
static final String TBNAME = "dogName";
static final String ROWID = "id_dogName";
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DatabaseAccess instance;
Cursor c = null;
//private constructor so that object creation from outside the class is avoided
private DatabaseAccess(Context context)
{
openHelper = new DatabaseOpenHelper(context);
}
//to return the single instance of database
public static DatabaseAccess getInstance(Context context)
{
if(instance == null)
{
instance = new DatabaseAccess(context);
}
return instance;
}
//to open the database
public void open()
{
db = openHelper.getWritableDatabase();
}
//closing the database connection
public void close()
{
if(db!=null)
{
db.close();
}
}
//method to query and return the results from database
//query for address by passing name
public String getAddress(String name)
{
c = db.rawQuery("select nickname_dogName from dogName where name_dogName = ?", new String[]{name});
String nickname = "";
while (c.moveToNext())
{
String address = c.getString(0);
nickname += address;
}
return nickname;
}
//add
public long add(String name, String nickname){
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(NICKNAME, nickname);
return db.insert(TBNAME, ROWID, contentValues);
} catch (SQLException e){
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames (){
String[] columns = {NAME, ROWID, NICKNAME};
return db.query(TBNAME, columns, null, null, null, null, null);
}
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName", new String[]{id});
}
}
When I click on my phone on the delete button it throws me out of the app. How to correct my code and make the delete button delete a selected item from the list?
something wrong in the second argument, your where clause should include "=?"
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName=?", new String[]{id});
}

Database not restored from Activity

I have a problem with database in android.
I'd like to collect data from an activity then transfer them to another activity that should show them into a ListView and save them into the DB.
The problem is that the app shows only the first item in the listview and I don't know if all data are saved into the DB. When I try to insert a new item, the app probably overrides the first item and shows the newest one.
Thanks a lot!
public class HomeActivity extends AppCompatActivity {
Button addPets;
private ListView mainListView;
private ArrayList<User> listUser;
private ArrayAdapter adapter;
private DBAdapter dbAdapter;
DBOpenHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
addPets = (Button)findViewById(R.id.add_friends);
addPets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent apriRegistraPet = new Intent(HomeActivity.this, RegisterActivity.class);
startActivity(apriRegistraPet);
}
});
dbAdapter = DBAdapter.getInstance(this);
mainListView = (ListView)findViewById(R.id.elenco_pets);
listUser = new ArrayList<User>();
adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, listUser);
mainListView.setAdapter(adapter);
mainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
onLongClick(position, mainListView);
return true;
}
});
}
private void addNewItem(User user) {
long idx = dbAdapter.insertUser(user);
user.setId(idx);
listUser.add(0, user);
adapter.notifyDataSetChanged();
}
private void onLongClick(final int position, final ListView listView){
User user = (User)listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Deleted Item", Toast.LENGTH_LONG).show();
if(!dbAdapter.deleteUser(user)){
return;
}
listUser.remove(user);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
dbAdapter.open();
fillData();
Bundle extras = getIntent().getExtras();
if(extras != null){
String nome = extras.getString("Nome");
String razza = extras.getString("Razza");
String sesso = extras.getString("Sesso");
User user = new User(0, nome, razza, sesso, 10, 2000);
addNewItem(user);
}
}
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
this.listUser.add(0, new User(idx, nome, razza, sesso, 10, 2000));
cursor.moveToNext();
}
cursor.close();
adapter.notifyDataSetChanged();
}
And this is Register Activity
public class RegisterActivity extends AppCompatActivity {
ImageButton settaImmagine;
String imgDecodableString;
Spinner sprazza;
Spinner spsesso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Clicco V e mette nella listview
ImageButton salva = (ImageButton)findViewById(R.id.button_salva);
salva.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText editText = (EditText)findViewById(R.id.name);
sprazza = (Spinner)findViewById(R.id.spinner_razza);
String razza = sprazza.getSelectedItem().toString();
spsesso = (Spinner)findViewById(R.id.spinner_sesso);
String sesso = spsesso.getSelectedItem().toString();
Intent resultIntent = new Intent(RegisterActivity.this, HomeActivity.class);
resultIntent.putExtra("Nome", editText.getText().toString());
resultIntent.putExtra("Razza", razza);
resultIntent.putExtra("Sesso", sesso);
startActivity(resultIntent);
}
});
DBAdapter class;
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static DBAdapter dbAdapter;
private static DBOpenHelper dbOpenHelper;
private SQLiteDatabase db;
public synchronized static DBAdapter getInstance(Context context){
if(dbAdapter==null) {
dbAdapter = new DBAdapter(context.getApplicationContext());
}
return dbAdapter;
}
private DBAdapter(Context context) {dbOpenHelper = DBOpenHelper.getInstance(context);}
public DBAdapter open() throws SQLException{
try{
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLException e){
Log.e(TAG, e.toString());
throw e;
}
return this;
}
public void close() {
db.close();
}
public long insertUser (User user){
Log.v(TAG, "Inserisci un User to DB: " +user.getNome());
long idx = db.insert(DBContract.AttributiRegistrazione.NOME_TABELLA, null, user.getAsContentValue());
user.setId(idx);
Log.v(TAG, "Added user with ID: "+idx);
return idx;
}
public boolean deleteUser (User user){
Log.v(TAG, "Removing User: " + user.getClass());
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + user.getNome(), null) == 1;
}
public boolean deleteUser(String name){
Log.v(TAG, "Removing user: " + name);
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + name, null) == 1;
}
public Cursor getAllEntries(){
return db.query(DBContract.AttributiRegistrazione.NOME_TABELLA,
null, null, null, null, null, null);
}
ERROR LOG
E/SQLiteLog: (1) table Registrazione has no column named Anno_nascita 04-10 13:57:21.142 10175-10175/com.b.uzzo.snappaw E/SQLiteDatabase: Error inserting Anno_nascita=2000 Peso=10.0 Nome=simone Sesso=Maschio Razza=Akita Inu
android.database.sqlite.SQLiteException: table Registrazione has no column named Anno_nascita (code 1): , while compiling: INSERT INTO Registrazione(Anno_nascita,Peso,Nome,Sesso,Razza) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1500)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1373)
at com.b.uzzo.snappaw.DBAdapter.insertUser(DBAdapter.java:49)
at com.b.uzzo.snappaw.HomeActivity.addNewItem(HomeActivity.java:105)
at com.b.uzzo.snappaw.HomeActivity.onResume(HomeActivity.java:140)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6770)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3522)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3591)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2825)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1085)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:946)
But it's created in DBContract class
public class DBContract {
static final String DB_NAME = "RegistrazioneCuccioli";
static final int DB_VERSION = 1;
static abstract class AttributiRegistrazione implements BaseColumns{
static final String NOME_TABELLA = "Registrazione";
static final String NOME = "Nome";
static final String RAZZA = "Razza";
static final String SESSO = "Sesso";
static final String PESO = "Peso";
static final String ANNO_NASCITA = "Anno_nascita";
}
}
In fillData method of HomeActivity class, You are adding data into Arraylist using list.add(0,new User()),which add your data into 0 index, that is cause of your problem. You should have to call list.add(user)
Try this updated Code:
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
if (cursor.moveToFirst()){
do {
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
User user = new User(idx, nome, razza, sesso, 10, 2000);
this.listUser.add(user);
}while(cursor.moveToNext());
}
cursor.close();
adapter.notifyDataSetChanged();}

how to pass Position wise object data one activity to another using recyclerview and databse in android

I have create the recycerview and this recycerview display the Person image ,person name and + button when i have press + button change the button image like true.and after recycerview bottom one button this button click all data show the next activity..
My Adapter
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
public BuildCustomAdapter(List<People> buildList) {
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.isSelected());
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// public ImageView ivPeopleImage;
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
}
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
People people = peopleList.get(mPosition);
people.setSelected(!people.isSelected());
notifyDataSetChanged();
}
}
Activity
public class BulidActivity extends AppCompatActivity {
private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bulid);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BuildData();
peopleListCopy.addAll(peopleList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
AddTxt();
BtnBuildNow();
}
private void BtnBuildNow() {
Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);
btnnuildnow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
startActivity(intent);
}
});
}
private void AddTxt() {
EditText editTxt = (EditText) findViewById(R.id.etSearch);
editTxt.setTextColor(Color.WHITE);
editTxt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
editTxt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() <= 0) {
peopleList.clear();
peopleList.addAll(peopleListCopy);
recyclerView.setAdapter(null);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
recyclerView.setAdapter(buildCustomAdapter);
} else {
buildCustomAdapter.getFilter().filter(s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<People> BuildData() {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (db.open()) {
peopleList = db.getPeople();
}
return peopleList;
}
Model class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
DatabaseHelper.class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
myDataBase = null;
return false;
}
}
public List<People> getPeople(String category_id) {
List<People> peoples = new ArrayList<>();
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);
while (cursor.moveToNext()) {
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
People people = new People();
people.setPeopleName(peopleName);
people.setPeopleImage(peopleImage);
peoples.add(people);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return peoples;
}
public List<Category> getCategory() {
List<Category> categoryList = new ArrayList<>();
try {
String query = " SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));
Category category = new Category();
category.setId(categoryID);
category.setCategoryName(categoryName);
categoryList.add(category);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return categoryList;
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
First you should implement Serializable interface in your Build model class like this :-
public class Build implements Serializable{
//Content will be as it is
}
Change your clickListener like this :-
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("build",build);
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
In the onCreate method of receiving activity write this :-
Build build = (Build) getIntent().getSerializableExtra("build");
Add Intent in below Method,
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("key","value");
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
Huge mistak that you register to the click event on your ViewHolder! you will get diffrent position from the actual because when android use notifyItemMoved the viewBindHolder will not be called and than you got the wrong position.
and in the click listener implementation you should pass Intent with your data

Categories