Access a function from another class - java

i have 4 classes in my app cardclick.java , DatabaseHelper.java , homeframgment.java and recyclerAdapterhomesubjectList.java
I have a function populateArrayList(); in homefragment in which i want to call every time onclick(){present in recyclerAdapterHomesubjectList} is called. can someone help me in achieving that
homefragment::
package com.example.app100.RecylerAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app100.R;
import com.example.app100.Subject;
import com.example.app100.card_click;
import com.example.app100.ui.home.HomeFragment;
import java.util.ArrayList;
public class RecyclerAdapterHomeSubjectList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Subject> subject;
private Context context;
public RecyclerAdapterHomeSubjectList(ArrayList<Subject> a, Context context){
this.subject = a;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.card_home_subject, parent, false);
return new ViewHolder(view) {
};
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.home_card_subject_imageview);
switch (position % 3) {
case 2:
imageView.setBackgroundResource(R.drawable.back1);
break;
case 1:
imageView.setBackgroundResource(R.drawable.back2);
break;
case 0:
imageView.setBackgroundResource(R.drawable.back3);
break;
}
Subject data = subject.get(position);
String name = data.subject_name;
TextView subject_name = holder.itemView.findViewById(R.id.home_card_subject_name);
subject_name.setText(name);
}
#Override
public int getItemCount() {
return subject.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context , card_click.class);
intent.putExtra("name" , subject.get(getAdapterPosition()).subject_name);
intent.putExtra("class_good" , subject.get(getAdapterPosition()).class_attended);
intent.putExtra("class_missed" , subject.get(getAdapterPosition()).class_missed);
intent.putExtra("credits",subject.get(getAdapterPosition()).credits);
context.startActivity(intent);
}
}
}
DatabaseHelper::
package com.example.app100;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String table_name = "SUBJECT_LIST";
private static final String COL0 = "ID";
private static final String COL1 = "NAME";
private static final String COL2 = "CREDITS";
private static final String COL3 = "CLASS_ATTENDED";
private static final String COL4 = "CLASS_MISSED";
public DatabaseHelper(#Nullable Context context) {
super(context, table_name, null, 6);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + table_name + "("+
COL0+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL1 + " TEXT, " +
COL2 + " INTEGER, "+
COL3 + " INTEGER, "+
COL4 + " INTEGER);";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table_name);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
boolean addData(String name, int credit , int good , int bad){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1 , name);
contentValues.put(COL2 , credit);
contentValues.put(COL3 , good);
contentValues.put(COL4 , bad);
long result = db.insert(table_name , null , contentValues);
return result != -1;
}
public Cursor getdata(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM SUBJECT_LIST;";
return db.rawQuery(query , null);
}
void append_data(String str, String name , int goodbad) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(str, goodbad);
int count = db.update(table_name, contentValues, "NAME = ?", new String[]{name});
Log.d(TAG, "blue button is pressed");
System.out.println(count);
}
}
cardclick:
package com.example.app100;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
public class card_click extends AppCompatActivity {
TextView attendace_info;
ProgressBar progressBar;
TextView credits;
TextView progress_percent;
int bad;
int good;
Button add;
Button minus;
ImageButton performance;
String name;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_click);
databaseHelper = new DatabaseHelper(this);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
performance = findViewById(R.id.card_click_performance_add);
progress_percent = findViewById(R.id.card_click_progress_bar_percent);
attendace_info = findViewById(R.id.card_click_attendance_text);
progressBar = findViewById(R.id.card_click_progress_bar);
credits = findViewById(R.id.card_click_credits_show);
add = findViewById(R.id.card_click_add_button);
minus = findViewById(R.id.card_click_minus_button);
Intent intent = getIntent();
good = intent.getIntExtra("class_good", 0);
bad = intent.getIntExtra("class_missed", 0);
name = intent.getStringExtra("name");
credits.setText(String.valueOf(intent.getIntExtra("credits", 0)));
display();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
good++;
databaseHelper.append_data("CLASS_ATTENDED", name , good);
display();
Cursor data = databaseHelper.getdata();
while(data.moveToNext()){
int a = data.getInt(3);
if( a > 0)
System.out.println("database has been updated");
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bad++;
databaseHelper.append_data("CLASS_MISSED", name, bad);
display();
Cursor data = databaseHelper.getdata();
while(data.moveToNext()){
int b = data.getInt(4);
if( b > 1)
System.out.println("database has been updated");
}
}
});
performance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(card_click.this, add_performace.class);
startActivity(intent1);
}
});
}
void display(){
int per = 100;
if(good+bad != 0)
per = (int)(good*100.0)/(good+bad);
String str = "You have atttended "+ (good) +
" out of " + (good + bad) +
" classes";
attendace_info.setText(str);
progressBar.setProgress(per);
progress_percent.setText(String.valueOf(per));
}
}
RecyclerAdapterHomeSubjectList:
package com.example.app100.RecylerAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.app100.R;
import com.example.app100.Subject;
import com.example.app100.card_click;
import com.example.app100.ui.home.HomeFragment;
import java.util.ArrayList;
public class RecyclerAdapterHomeSubjectList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Subject> subject;
private Context context;
public RecyclerAdapterHomeSubjectList(ArrayList<Subject> a, Context context){
this.subject = a;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from((parent.getContext()));
View view = inflater.inflate(R.layout.card_home_subject, parent, false);
return new ViewHolder(view) {
};
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.home_card_subject_imageview);
switch (position % 3) {
case 2:
imageView.setBackgroundResource(R.drawable.back1);
break;
case 1:
imageView.setBackgroundResource(R.drawable.back2);
break;
case 0:
imageView.setBackgroundResource(R.drawable.back3);
break;
}
Subject data = subject.get(position);
String name = data.subject_name;
TextView subject_name = holder.itemView.findViewById(R.id.home_card_subject_name);
subject_name.setText(name);
}
#Override
public int getItemCount() {
return subject.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context , card_click.class);
intent.putExtra("name" , subject.get(getAdapterPosition()).subject_name);
intent.putExtra("class_good" , subject.get(getAdapterPosition()).class_attended);
intent.putExtra("class_missed" , subject.get(getAdapterPosition()).class_missed);
intent.putExtra("credits",subject.get(getAdapterPosition()).credits);
context.startActivity(intent);
}
}
}

just import the class name and you can use the function from it. (function and the class should be public to use)

Related

How to cast the value of SQLiteDatabase.execSQL to a String?

I'm developing a small android notes app using java. Everything seems to be working fine except that I'm getting an error while trying to cast the instance SQLiteDatabase.execSql obj to a String. The purpose of doing this is that, it will allow user to update their data. In the custom adapter class (obBind method) I've set a tag, which means I've the id of each itemView even in my MainActivity. What I want it to do is when a user left swipes a particular item then his/her data should be set (editText.setText) in the edittext and if he/she clicks on the add button, the data should be updated.
Please refer to the codes for better understand-ability
CustomAdapter Class:
package com.example.myapplication20;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
Context mContext;
Cursor mCursor;
CustomAdapter (Context context, Cursor cursor) {
mContext = context;
mCursor = cursor;
}
#NonNull
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.single_item_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(CustomAdapter.ViewHolder holder, int position) {
if (!mCursor.moveToPosition(position)) {
return;
}
String value = mCursor.getString(mCursor.getColumnIndex(TableDetailsClass.Collection.TABLE_COLUMN));
Long id = mCursor.getLong(mCursor.getColumnIndex(TableDetailsClass.Collection._ID));
holder.mTextView.setText(value);
holder.itemView.setTag(id);
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
TextView uTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.textView);
uTextView = itemView.findViewById(R.id.updateTextView);
}
}
public void swapCursor (Cursor newCursor) {
if (mCursor != null) {
mCursor.close();
}
mCursor = newCursor;
if (newCursor != null) {
notifyDataSetChanged();
}
}
}
MainActivity Class:
package com.example.myapplication20;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.CollapsibleActionView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
private Button addButton;
private RecyclerView mRecyclerView;
private SQLiteDatabase mDataBase;
MyOpenHelperClass myOpenHelperClass;
CustomAdapter mCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOpenHelperClass = new MyOpenHelperClass(this);
mDataBase = myOpenHelperClass.getWritableDatabase();
mEditText = findViewById(R.id.editText);
addButton = findViewById(R.id.button);
mCustomAdapter = new CustomAdapter(this, getAllItems());
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mCustomAdapter);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItems();
}
});
// Swipe delete
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
removeItem( (Long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(mRecyclerView);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
updateItem( (Long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(mRecyclerView);
}
private void addItems () {
if (mEditText.getText().toString().trim().length() == 0) {
return;
}
String textToBeAdded = mEditText.getText().toString();
ContentValues cv = new ContentValues();
cv.put(TableDetailsClass.Collection.TABLE_COLUMN, textToBeAdded);
mDataBase.insert(TableDetailsClass.Collection.TABLE_NAME, null, cv);
mCustomAdapter.swapCursor(getAllItems());
mEditText.getText().clear();
}
public Cursor getAllItems () {
return mDataBase.query(TableDetailsClass.Collection.TABLE_NAME,
null,
null,
null,
null,
null,
TableDetailsClass.Collection.TIMESTAMP + " DESC"
);
}
public void removeItem (Long id) {
mDataBase.delete(TableDetailsClass.Collection.TABLE_NAME,
TableDetailsClass.Collection._ID + "=" + id, null);
mCustomAdapter.swapCursor(getAllItems());
Toast.makeText(this, "Item deleted!", Toast.LENGTH_SHORT).show();
}
public void updateItem (long id) {
String val = mDataBase.execSQL("SELECT * FROM " + TableDetailsClass.Collection.TABLE_NAME + " WHERE " +
TableDetailsClass.Collection._ID + "=" + id);
mEditText.setText(val); // The line I'm getting the error in. Says cannot cast void to string.
ContentValues cv = new ContentValues();
cv.put(TableDetailsClass.Collection.TABLE_COLUMN, mEditText.getText().toString());
mDataBase.update(TableDetailsClass.Collection.TABLE_NAME, cv,
TableDetailsClass.Collection._ID + "=" + id, null);
mCustomAdapter.swapCursor(getAllItems());
}
}
SQLiteOpenHelper Class:
package com.example.myapplication20;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class MyOpenHelperClass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myapp.db";
public static final int DATABASE_VERSION = 1;
public MyOpenHelperClass(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_QUERY = "CREATE TABLE " +
TableDetailsClass.Collection.TABLE_NAME + "(" +
TableDetailsClass.Collection._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TableDetailsClass.Collection.TABLE_COLUMN + " TEXT NOT NULL, " +
TableDetailsClass.Collection.TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" + ");";
db.execSQL(SQL_CREATE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TableDetailsClass.Collection.TABLE_NAME);
onCreate(db);
}
}
Any kind of help will be really appreciated.
public void updateItem (long id) {
Cursor cursor = mDataBase.rawQuery("SELECT * FROM " + TableDetailsClass.Collection.TABLE_NAME + " WHERE " +
TableDetailsClass.Collection._ID + "= ?", new String[]{String.valueOf(id)});
if (cursor != null && cursor.moveToFirst()) {
String val = cursor.getString(cursor.getColumnIndex(TableDetailsClass.Collection.TABLE_COLUMN));
mEditText.setText(val);
cursor.close();
}
...
}

Java: How to update the Recycler View every time I delete an item?

I seem to be stuck with this problem where I want to update the Recycler View in real-time. Meaning I want the recycler view to update its list when a user swipes to delete a row.
As you can see in the code below I have tried to use NotifyDataSetChange() in the DatabaseAdapter java class but I only get the error "RecyclerViewAdapter.notifyDataSetChanged() on a null object reference".
I have both googled the error above and how to update Recycle view in real-time but none of the solutions I found worked. Please help me because I am losing it with this problem.
NamesAdapter.Java
package com.example.myapplication.ui;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.DatabaseAdapter;
import com.example.myapplication.R;
import org.w3c.dom.NameList;
import java.util.ArrayList;
import java.util.List;
public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.ViewHolder> {
Context context;
List<Names> namesList;
RecyclerView rvPrograms;
final View.OnClickListener onClickListener = new MyOnClickListner();
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView rowID;
TextView rowName;
TextView rowAmount;
TextView rowDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Store the item sub-views in member variables
rowID = itemView.findViewById(R.id.idTextView);
rowName = itemView.findViewById(R.id.nameTextView);
rowAmount = itemView.findViewById(R.id.amountEditText);
rowDate = itemView.findViewById(R.id.dateTextView);
}
}
public NamesAdapter(Context context, List<Names> namesList, RecyclerView rvPrograms){
this.context = context;
this.namesList= namesList;
this.rvPrograms = rvPrograms;
}
#NonNull
#Override
public NamesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.recycler_list, viewGroup, false);
view.setOnClickListener(onClickListener);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NamesAdapter.ViewHolder holder, int i) {
Names name = namesList.get(i);
holder.rowID.setText(""+name.getId());
holder.rowName.setText(name.getName());
holder.rowAmount.setText(name.getAmount());
holder.rowDate.setText(name.getDate());
holder.itemView.setTag(name.getId());
}
#Override
public int getItemCount() {
return namesList.size();
}
private class MyOnClickListner implements View.OnClickListener {
#Override
public void onClick(View v) {
int itemPosition = rvPrograms.getChildLayoutPosition(v);
String item = namesList.get(itemPosition).getName();
Toast.makeText(context, item, Toast.LENGTH_SHORT).show();
}
}
}
DatabaseAdapter.Java
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.myapplication.ui.Names;
import com.example.myapplication.ui.NamesAdapter;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
List<Names> namesList = new ArrayList<>();
NamesAdapter na;
public DatabaseAdapter(Context context) {
helper = new DatabaseHelper(context);
db = helper.getWritableDatabase();
}
public int deleteData(String name){
String whereArgs[] = {name};
int count = db.delete(DatabaseHelper.Table_Name, DatabaseHelper.Key_Name+ "=?", whereArgs);
return count;
}
public int removeItem (long id){
int count = db.delete(DatabaseHelper.Table_Name, DatabaseHelper.Key_ID+ "="+ id, null);
//na.notifyDataSetChanged();
return count;
}
public int updateAmount(String name, String amount){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.Key_Amount, amount);
String whereArgs[] = {name};
int count = db.update(DatabaseHelper.Table_Name, contentValues, DatabaseHelper.Key_Name + "=?", whereArgs);
return count;
}
public String searchData(String sname){
String columns[] = {DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount};
String selectionArgs[] = {sname};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, DatabaseHelper.Key_Name + "=?", selectionArgs, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
String name = cursor.getString(index1);
String amount = cursor.getString(index2);
buffer.append(name + " " + amount + "\n");
}
return buffer.toString();
}
// This is for the Toast dispaly
public String getAllData(){
String columns[] = {DatabaseHelper.Key_ID, DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, null, null, null, null, null, null );
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_ID);
int rowid = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
String name = cursor.getString(index2);
int index3 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
int amount = cursor.getInt(index3);
buffer.append(rowid + " " + name + " " + amount + "\n");
}
return buffer.toString();
}
public List<Names> getAllNames(){
String columns[] = {DatabaseHelper.Key_ID, DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount, DatabaseHelper.Key_Date};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, null, null, null, null, DatabaseHelper.Key_ID+" DESC",null );
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_ID);
int rowid = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
String name = cursor.getString(index2);
int index3 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
Double amount = cursor.getDouble(index3);
int index4 = cursor.getColumnIndex(DatabaseHelper.Key_Date);
String date = cursor.getString(index4);
Names names = new Names(rowid, name, amount, date);
namesList.add(names);
}
return namesList;
}
public long insertData (String name, Double amount, String date){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.Key_Name, name);
contentValues.put(DatabaseHelper.Key_Amount, amount);
contentValues.put(DatabaseHelper.Key_Date, date);
long id = db.insert(DatabaseHelper.Table_Name, null ,contentValues);
return id;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String Database_Name = "Demoze.db";
private static final String Table_Name = "salary";
private static final int Database_Version= 10;
private static final String Key_ID = "_id";
private static final String Key_Name = "name";
private static final String Key_Amount = "amount";
private static final String Key_Date = "date";
private static final String Create_table = "create table "+Table_Name+
" ("+Key_ID+" integer primary key autoincrement, "+Key_Name+
" text, "+Key_Amount+ " real, "+Key_Date+" text)";
private static final String Table_Drop = "drop table if exists "+Table_Name;
private Context context;
public DatabaseHelper(#Nullable Context context) {
super(context, Database_Name, null, Database_Version);
this.context = context;
Toast.makeText(context, "Constructor Called", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Create_table);
Toast.makeText(context, "OnCreate Called", Toast.LENGTH_SHORT).show();
} catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Toast.makeText(context, "OnUpgrade Called", Toast.LENGTH_SHORT).show();
db.execSQL(Table_Drop);
onCreate(db);
} catch (SQLException e) {
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}
}
SpendingActivity.Java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.ui.Names;
import com.example.myapplication.ui.NamesAdapter;
import java.util.ArrayList;
import java.util.List;
public class SpendingActivity extends AppCompatActivity {
DatabaseAdapter databaseAdapter;
EditText crud;
RecyclerView rvPrograms;
NamesAdapter namesAdapter;
RecyclerView.LayoutManager layoutManager;
List<Names> namesList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spending_list);
databaseAdapter = new DatabaseAdapter(this);
namesList = databaseAdapter.getAllNames();
rvPrograms = findViewById(R.id.rvDBdata);
rvPrograms.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvPrograms.setLayoutManager(layoutManager);
namesAdapter = new NamesAdapter(this, namesList, rvPrograms);
rvPrograms.setAdapter(namesAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
databaseAdapter.removeItem((long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(rvPrograms);
crud = findViewById(R.id.crudEditText);
String data = databaseAdapter.getAllData();
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}
public void Home (View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void Search (View view){
String name = crud.getText().toString().trim();
String result = databaseAdapter.searchData(name);
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
public void Update (View view) {
String amount = crud.getText().toString().trim();
databaseAdapter.updateAmount("taxi", amount);
}
public void Delete (View view) {
String name = crud.getText().toString().trim();
databaseAdapter.deleteData(name);
}
}
In your NamesAdapter you could expose a method called deleteItem:
public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.ViewHolder> {
...
public void deleteItem(int position){
namesList.remove(position);
notifyItemRemoved(position);
}
}
Inside of onSwiped() method, you need to call NameAdapter' deleteItem method:
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
namesAdapter.deleteItem(position);
databaseAdapter.removeItem((long) viewHolder.itemView.getTag());
}
Recycleview adapterclass
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
ArrayList<String> animalNames
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
animalNames.remove(position);
adapter.notifyItemRemoved(position);
}
}

recycler view does not refresh and show data

in my recycler view , when data get added , recycelr view does not show it until user close the activity and open it another time.
I think it has something to do with notifydataetchanger.
please help me with this
the only thing that worked by now was to creating an Intent .
but it makes app to loob very bad
my adaptor
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Rec_adaptor_aza extends RecyclerView.Adapter<Rec_adaptor_aza.ViewHolder> {
Context context;
public Rec_adaptor_aza(Context context, List<Model_aza> list_aza) {
this.context = context;
this.list_aza = list_aza;
}
List<Model_aza> list_aza;
#NonNull
#Override
public Rec_adaptor_aza.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.rec_row_aza,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Rec_adaptor_aza.ViewHolder holder, int position) {
Model_aza modelAza =list_aza.get(position);
holder.txt_name.setText(modelAza.getName_aza());
holder.txt_semat.setText(modelAza.getSemat_aza());
holder.txt_saat_voood.setText(modelAza.getSaaat_vorood_aza());
holder.txt_saat_khoroo.setText(modelAza.getSaat_khorooj_aza());
}
#Override
public int getItemCount() {
return list_aza.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_name,txt_semat,txt_saat_voood,txt_saat_khoroo;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txt_name=itemView.findViewById(R.id.txt__person__name);
txt_semat=itemView.findViewById(R.id.txt__person__semat);
txt_saat_voood=itemView.findViewById(R.id.txt__person__enter);
txt_saat_khoroo=itemView.findViewById(R.id.txt__person__out);
}
}
}
my model class
package com.example.myapplication;
public class Model_aza {
private String name_aza;
private String semat_aza;
private String saaat_vorood_aza;
public String getName_aza() {
return name_aza;
}
public void setName_aza(String name_aza) {
this.name_aza = name_aza;
}
public String getSemat_aza() {
return semat_aza;
}
public void setSemat_aza(String semat_aza) {
this.semat_aza = semat_aza;
}
public String getSaaat_vorood_aza() {
return saaat_vorood_aza;
}
public void setSaaat_vorood_aza(String saaat_vorood_aza) {
this.saaat_vorood_aza = saaat_vorood_aza;
}
public String getSaat_khorooj_aza() {
return saat_khorooj_aza;
}
public void setSaat_khorooj_aza(String saat_khorooj_aza) {
this.saat_khorooj_aza = saat_khorooj_aza;
}
private String saat_khorooj_aza;
}
My activity
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Activity_Gozaresh_giri extends AppCompatActivity {
private static final String TAG = "gozaresh_activity";
List<Model_aza> list_aza;
Rec_adaptor_aza rec_adaptor_aza;
public static Context context;
SQLiteDatabase sqLiteDatabase;
ImageButton btn__add__field, btn__add__field1;
final DataBase_aza dataBase_aza = new DataBase_aza(this);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
}
my data base
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DataBase_aza extends SQLiteOpenHelper {
public DataBase_aza(#Nullable Context context) {
super(context, "datbase_aza", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table if not exists database_aza (_id integer primary key autoincrement,_name varcher(55) not null,_semat varcher(55) not null, _vorood varcher(6) not null, _khorooj varchar(22) not null, id__item__gozaresh integer(55))");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long insert_info(String name, String semat, String vorood, String khorooj, int id) {
ContentValues cv = new ContentValues();
cv.put("_name", name);
cv.put("_semat", semat);
cv.put("_vorood", vorood);
cv.put("_khorooj", khorooj);
cv.put("id__item__gozaresh", id);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
return sqLiteDatabase.insert("database_aza", null, cv);
}
public Cursor cursor(int id) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery("SELECT * FROM database_aza where id__item__gozaresh="+id, null);
}
}
I want recycler view to show data as soon as user clicks on add button
after adding entry just notify data set changed to adapter like below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
rec_adaptor_aza = new Rec_adaptor_aza(this, list_aza);
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(rec_adaptor_aza);
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
rec_adaptor_aza.notifyDataSetChanged();
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
rec_adaptor_aza.notifyDataSetChanged(); // change here
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
}
Use it like below:-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Rec_adaptor_aza adapter = new Rec_adaptor_aza(this, list_aza); // Add
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(adapter);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Model_aza modelAza = new Model_aza(); // Add
modelAza.setName_aza(name_aza);// Add
modelAza.setSemat_aza(semat_aza);// Add
modelAza.setSaaat_vorood_aza(saat_vorood_aza);// Add
modelAza.setSaat_khorooj_aza(saat_khorooj_aza);// Add
list_aza.add(modelAza);// Add
adapter.notifyDataSetChanged();// Add
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
adapter.notifyDataSetChanged();// Add
}
Just add the below code, in your clickListner, you need to add the same object in your list, and after adding you need to notify the adapter about the inserted item, by using notifyDataSetChanged().
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
/*
* Adding entered data in list*/
Model_aza mm=new Model_aza();
mm.setName_aza(name_aza);
mm.setSemat_aza(semat_aza);
mm.setSaaat_vorood_aza(saat_vorood_aza);
mm.setSaat_khorooj_aza(saat_khorooj_aza);
list_aza.add(mm);
rec_adaptor_aza.notifyDataSetChanged();
}
});
Set layoutmanager before set the adapter to recylerview in your activity, like below
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
// set layout manager before set adapter
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));

Deleting an item from RecyclerView + SQLite

So I'm trying to delete an item on a cross button. Now it is being deleted from RecyclerView, but goes crazy with SQLite. If I delete one item, it's all good. But when I delete several items, it, as I said, goes crazy and gets deleted items back outta nowhere without deleting anything then.
Here's my DataAdapted.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Booking> bookings;
private String time;
DBHelper dbHelper;
SQLiteDatabase dataBase;
DataAdapter(Context context, List<Booking> bookings) {
this.bookings = bookings;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public DataAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DataAdapter.ViewHolder holder, int position) {
Booking booking = bookings.get(position);
holder.nameView.setText(booking.getName());
time = booking.getHours() + ":" + booking.getMinutes();
holder.timeView.setText(time);
}
#Override
public int getItemCount() {
return bookings.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameView;
TextView timeView;
ImageView crossImage;
ViewHolder(View view){
super(view);
timeView = view.findViewById(R.id.time_view);
nameView = view.findViewById(R.id.name_view);
crossImage = view.findViewById(R.id.crossImage);
crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeAt(getAdapterPosition());
}
});
}
}
public void removeAt(int position) {
bookings.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, bookings.size());
DBHelper.delete(position);
}
}
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "bookingsDb";
public static final String TABLE_BOOKINGS = "bookings";
public static final String KEY_ID = "_id";
public static final String KEY_NUMBER = "_numbers";
public static final String KEY_NAME = "_names";
public static final String KEY_HOURS = "_hours";
public static final String KEY_MINUTES = "_minutes";
public static final String KEY_PHONE= "_phones";
Context myContext;
static DBHelper dbHelper;
static SQLiteDatabase database;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_BOOKINGS + "("
+ KEY_ID + " integer primary key,"
+ KEY_NUMBER + " integer,"
+ KEY_NAME + " text,"
+ KEY_HOURS + " text,"
+ KEY_MINUTES + " text,"
+ KEY_PHONE + " text" + ")");
dbHelper = new DBHelper(myContext);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_BOOKINGS);
onCreate(db);
}
public static void delete(int id){
database = dbHelper.getWritableDatabase();
database.delete(TABLE_BOOKINGS, KEY_ID + "=" + id, null);
}
}
And my TableActivity.java if needed
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TableActivity extends AppCompatActivity {
int currentTable;
Button createNewBooking;
List<Booking> bookings;
TextView name;
TextView time;
DataAdapter adapter;
RecyclerView recyclerView;
DBHelper dbHelper;
View.OnClickListener createNewBookingListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TableActivity.this, BookingActivity.class);
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
currentTable = MainActivity.getCurrentTable();
createNewBooking = findViewById(R.id.createNewBooking);
createNewBooking.setOnClickListener(createNewBookingListener);
bookings = new ArrayList<>();
dbHelper = new DBHelper(this);
setInitialData();
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new DataAdapter(this, bookings);
recyclerView.setAdapter(adapter);
}
private void setInitialData() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.query(DBHelper.TABLE_BOOKINGS, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(DBHelper.KEY_NAME);
int hoursIndex = cursor.getColumnIndex(DBHelper.KEY_HOURS);
int minutesIndex = cursor.getColumnIndex(DBHelper.KEY_MINUTES);
int phoneIndex = cursor.getColumnIndex(DBHelper.KEY_PHONE);
do {
bookings.add(new Booking(
currentTable,
cursor.getString(nameIndex),
cursor.getString(hoursIndex),
cursor.getString(minutesIndex),
cursor.getString(phoneIndex)
));
} while (cursor.moveToNext());
} else {
Toast.makeText(this, "Броней нет", Toast.LENGTH_SHORT).show();
}
cursor.close();
dbHelper.close();
}
}
Any ideas, please?
you are giving position for delete, it's not necessary to id will be same as per adapter position.
try this :
crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Booking booking = bookings.get(getAdapterPosition());
datatype id = booking.getId();
removeAt(getAdapterPosition(),id);
}
});
public void removeAt(int position, dataType id) {
bookings.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, bookings.size());
DBHelper.delete(id);
}

Android Sqlite can't get records from Listview

I am writing a program that saves to DB and then get infos from the DB using SQLiteOpenHelper.
Problem is I insert text from the edit text but I got nothing to show.
is the problem from the listview? cuz I extend from ArrayAdapter class not from enter code hereCursor adapter? or there is something wrong with my code. Please take a look at my code this is my main Acitvity
package com.perfectapps.fasaven.dbnews;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import DBHelper.DBContract;
import DBHelper.DBModel;
import newsAdapter.NewsMainMenuAdapter;
public class MainActivity extends AppCompatActivity {
Button submitNews;
ListView newsListView;
ArrayList<DBModel> dbmodel = new ArrayList<DBModel>();
EditText titleEditText;
TextView tvTitle;
TextView tvInfo;
EditText infoEditText;
DBContract dbContract;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTitle =(TextView)findViewById(R.id.tvTitle);
tvInfo =(TextView)findViewById(R.id.tvInfo);
submitNews = (Button)findViewById(R.id.submit_news);
newsListView = (ListView)findViewById(R.id.lvNews);
titleEditText = (EditText)findViewById(R.id.etNews);
infoEditText = (EditText)findViewById(R.id.etNewsInfo);
dbContract = new DBContract(this,null,null,1);
NewsMainMenuAdapter customeAdapter = new NewsMainMenuAdapter(getApplicationContext(), R.layout.row_news_element,dbmodel);
newsListView.setAdapter(customeAdapter);
// printDataBase();
submitNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBModel dbModel = new DBModel();
dbModel.setNewsInfos(infoEditText.getText().toString());
dbModel.setNewsTitle(titleEditText.getText().toString());
dbContract.addNews(dbModel);
Toast.makeText(getApplicationContext(),"saved to DB", Toast.LENGTH_LONG ).show();
titleEditText.setText("");
infoEditText.setText("");
// printDataBase();
}
});
}
public void printDataBase(){
DBModel dbModel = new DBModel();
String dbToStringTitle = dbContract.readNewsTitle();
tvTitle.setText(dbToStringTitle);
titleEditText.setText("");
String dbToStringInfo =dbContract.readNewsInfo();
tvInfo.setText(dbToStringInfo);
infoEditText.setText("");
}
}
This is my custom Adapter
package newsAdapter;
import android.support.annotation.LayoutRes;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import DBHelper.*;
import com.perfectapps.fasaven.dbnews.*;
import java.util.ArrayList;
/**
* Created by Salem on 22/12/2017.
*/
public class NewsMainMenuAdapter extends ArrayAdapter{
Context context;
ArrayList<DBModel> newsData;
int resource;
public NewsMainMenuAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<DBModel> newsData) {
super(context, resource, newsData);
this.context =context;
this.newsData = newsData;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_news_element,null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvInfo = (TextView)convertView.findViewById(R.id.tvInfo);
viewHolder.tvTitle = (TextView)convertView.findViewById(R.id.tvTitle);
viewHolder.tvTitle.setText(newsData.get(position).getNewsTitle());
viewHolder.tvInfo.setText(newsData.get(position).getNewsInfos());
//return super.getView(position, convertView, parent);
return convertView;
}
//#Nullable
// #Override
// public DBModel getItem(int position) {
// return super.getItem(position);
//}
class ViewHolder{
TextView tvTitle;
TextView tvInfo;
}
}
Here is my DB helper
package DBHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Salem on 22/12/2017.
*/
public class DBContract extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "newsDB.db";
public static final String TABLE_NAME = "news";
public static final String COLUMN_ID = "_ID";
public static final String COLUMN_NEWS_TITLE = "newstitle";
public static final String COLUMN_NEWS_IMAGE = "newsimage";
public static final String COLUMN_NEWS_INFO= "newsinfo";
public DBContract(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DB_NAME, factory, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ TABLE_NAME + " ("
+COLUMN_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NEWS_TITLE+ " TEXT ,"
+COLUMN_NEWS_INFO+ " TEXT );";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
public void addNews(DBModel dbModel){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NEWS_TITLE, dbModel.getNewsTitle());
contentValues.put(COLUMN_NEWS_INFO, dbModel.getNewsInfos());
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
}
public String readNewsTitle(){
String readNews = "";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_TITLE+" FROM "+TABLE_NAME +" where 1";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE))!=null);
{
readNews += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE));
readNews +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNews;
}
public String readNewsInfo(){
String readNewsInfo="";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_INFO+" FROM "+TABLE_NAME ;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO))!=null);
{
readNewsInfo += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO));
readNewsInfo +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNewsInfo;
}
}
There is one 4th class that has setters and getters named DBModel
and got XML for main activity which has listview.. but it when I input from edit text it doesn't show there

Categories

Resources