How to save button state in shared preference? - java

I am new to android development and I have custom ListView which have favourite and removefavourite button now i want save this button state in SharedPreferences please tell me how i can save this button state in shared preference when user click on favourite button, the button change into favourite and when click on favourite the button change into removefavourite here is my code?
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
}
});
holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=false;
holder.addfavoruite.setVisibility(View.VISIBLE);
holder.removefavoruite.setVisibility(View.GONE);
}
});
My custom ListView whole code
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean ischeckd;
String My_PREF="MY_PREF";
SharedPreferences sharedPreferences;
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ImageView)convertView.findViewById(R.id.adbookmark);
holder.removefavoruite=(ImageView)convertView.findViewById(R.id.removebookmark);
try {
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
}
});
holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=false;
holder.addfavoruite.setVisibility(View.VISIBLE);
holder.removefavoruite.setVisibility(View.GONE);
}
});
}catch (Exception e){
Toast.makeText(activity, ""+e, Toast.LENGTH_SHORT).show();
}
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ImageView addfavoruite;
private ImageView removefavoruite;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
addfavoruite=(ImageView)v.findViewById(R.id.adbookmark);
removefavoruite=(ImageView)v.findViewById(R.id.removebookmark);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
}

you just need to create an AppPreference class :-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean isButtonCLicked(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("button_clicked", true);
}
public static void setButtonCLicked(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("button_clicked", value);
mPrefsEditor.commit();
}
}
and set this method in your button click:-
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
AppPreference.setButtonCLicked(activity, ture);
}
});
and get your button state like this :-
boolean isButtonClicked = AppPreference.isButtonCLicked(activity);

I have a few suggestions. First, I'd recommend you use a ToggleButton for your favourite button. Second, I'd recommend you use a RecyclerView instead of a ListView (which is essentially deprecated). Third, I'd recommend you create a data class (ideally with AutoValue):
class Verse {
private final int number;
private final String list;
private final String ref;
private final String id;
private final boolean isFavourite;
//Constructor and getters...
}
And replace this:
List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid
with this:
List<Verse> verses
With respect to persisting which verses are checked and which aren't, then I'd recommend you favour an SQLiteDatabase over SharedPreferences. However, if you use shared preferences, you'll need a way to link your verse to its checked state. I'm assuming your id value is unique, so you can use that:
class VersePreferences {
private static final String VERSE_KEY = "com.my.packagename.VERSE_KEY";
private final SharedPreferences prefs;
private VersePreferences(SharedPreferences prefs) {
this.prefs = prefs;
}
static VersePreferences from(Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
return new VersePreferences(prefs);
}
void save(List<Verse> verses) {
final Set<String> set = new HashSet<>(verses.size());
for(Verse verse : verses) {
final String serialized = String.format("%s:%s", verse.id(), Boolean.toString(verse.isFavourite()));
}
prefs.edit().putStringSet(VERSE_KEY, set).apply();
}
Map<String, Boolean> load() {
final Set<String> set = prefs.getStringSet(VERSE_KEY, new HashSet<>());
final Map<String, Boolean> map = new HashMap<>();
for(String serialized : set) {
final String[] parts = serialized.split(":");
map.put(parts[0], Boolean.parseBoolean(parts[1]);
}
return map;
}
}
You can identify which verse is an isn't a favourite by comparing the String id value in the map against the Boolean value
Example usage...
//OnClick
VersePreferences.from(Context).save(verses); //save all verses
//To load
final Map<String, Boolean> checkedStates = VersePreferences.from(context).load();
for(int i = 0; i < verses.size(); i++) {
final Verse current = verses.get(i);
final boolean checkedState = checkedState.get(current.id());
final Verse checked = current.toBuilder().setChecked(checkedState).build(); //Example using builder pattern
verses.set(i, checked);
}

Related

CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder' Error

I have a android studio project and use 'com.timehop.stickyheadersrecyclerview:library:0.4.3#aar'
library it works fine but when I create a new project using same code It show me the following error in line 26 StickyRecyclerHeadersAdapter<CustomAdapter.MyHeadingViewHolder> { of CustomAdapter class:
Type parameter 'com.vatexpress.service.CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder'
and also show me following error in line 75 recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(customAdapter));of ManinActivity class:
Type parameter 'com.vatexpress.service.CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder'
Here is my CustomAdapter class:
package com.vatexpress.service;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyChildViewHolder>
implements Filterable,
StickyRecyclerHeadersAdapter<CustomAdapter.MyHeadingViewHolder> {
private Context context;
private Activity activity;
private ArrayList<Model> dataholder;
ArrayList<Model> backup;
MyDatabaseHelper obj = null;
String code, nature, name, sd, vat, vds, vat_ref, vds_ref, about;
public static final int CHILD_LIST = 1;
public static final int HEADER = 2;
CustomAdapter(Activity activity, Context context, ArrayList<Model> dataholder){
this.activity = activity;
this.context = context;
this.dataholder = dataholder;
backup=new ArrayList<>(dataholder);
}
#NonNull
#Override
public MyChildViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyChildViewHolder holder, final int position) {
// if (holder instanceof MyChildViewHolder) {
final Model temp=dataholder.get(position);
holder.service_code.setText(dataholder.get(position).getService_code());
holder.service_name.setText(dataholder.get(position).getService_name());
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, DetailActivity.class);
obj = new MyDatabaseHelper(context);
Cursor cursor = obj.getData(temp.id);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
code = cursor.getString(0);
nature = cursor.getString(2);
name = cursor.getString(1);
sd = cursor.getString(3);
vat = cursor.getString(4);
vds = cursor.getString(5);
vat_ref = cursor.getString(6);
vds_ref = cursor.getString(7);
about = cursor.getString(8);
} while (cursor.moveToNext());
}
}
intent.putExtra("code", code);
intent.putExtra("nature", nature);
intent.putExtra("servicename", name);
intent.putExtra("sd", sd);
intent.putExtra("vat", vat);
intent.putExtra("vds", vds);
intent.putExtra("vat_ref", vat_ref);
intent.putExtra("vds_ref", vds_ref);
intent.putExtra("about", about);
activity.startActivityForResult(intent, 1);
}
});
// }
// else if(holder instanceof MyHeadingViewHolder) {
// MyHeadingViewHolder myHeadingViewHolder = (MyHeadingViewHolder) holder;
// myHeadingViewHolder.heading.setText(dataholder.get(position).service_heading);
// }
}
#Override
public long getHeaderId(int position) {
return dataholder.get(position).getSection();
}
#Override
public MyHeadingViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.heading_layout, parent, false);
return new MyHeadingViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(MyHeadingViewHolder myHeadingViewHolder, int i) {
myHeadingViewHolder.heading.setText(dataholder.get(i).getService_heading());
}
#Override
public int getItemCount() {
return dataholder.size();
}
#Override
public Filter getFilter() {
return filter;
}
Filter filter=new Filter() {
#Override
// background thread
protected FilterResults performFiltering(CharSequence keyword)
{
ArrayList<Model> filtereddata=new ArrayList<>();
if(keyword.toString().isEmpty())
filtereddata.addAll(backup);
else
{
for(Model obj : backup)
{
if(obj.getService_name().toString().toLowerCase().contains(keyword.toString().toLowerCase()))
filtereddata.add(obj);
}
}
FilterResults results=new FilterResults();
results.values=filtereddata;
return results;
}
#Override // main UI thread
protected void publishResults(CharSequence constraint, FilterResults results)
{
dataholder.clear();
dataholder.addAll((ArrayList<Model>)results.values);
notifyDataSetChanged();
}
};
// #Override
// public int getItemViewType(int position) {
// if (dataholder.get(position).typeHeading)
// {
// return HEADER;
// }
// else {
// return CHILD_LIST;
// }
// }
class MyChildViewHolder extends RecyclerView.ViewHolder {
TextView service_code, service_name;
LinearLayout mainLayout;
MyChildViewHolder(#NonNull View itemView) {
super(itemView);
service_code = itemView.findViewById(R.id.service_code);
service_name = itemView.findViewById(R.id.service_name);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
class MyHeadingViewHolder extends RecyclerView.ViewHolder {
TextView heading;
public MyHeadingViewHolder(#NonNull View itemView) {
super(itemView);
heading = itemView.findViewById(R.id.heading_name);
}
}
}
Here is my MainActivity class:
package com.vatexpress.service;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public final class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT =1000 ;
RecyclerView recyclerView;
TextView noSearchResultsFoundText;
EditText editText;
ImageView clearQueryImageView ;
ImageView voiceSearchImageView;
MyDatabaseHelper myDB;
ArrayList<Model> dataholder;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.search_list);
noSearchResultsFoundText = findViewById(R.id.no_search_results_found_text);
myDB = new MyDatabaseHelper(MainActivity.this);
try {
myDB.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDB.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
storeDataInArrays();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customAdapter = new CustomAdapter(MainActivity.this,this, dataholder);
recyclerView.setAdapter(customAdapter);
recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(customAdapter));
editText = (EditText) findViewById(R.id.search_edit_text);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
customAdapter.getFilter().filter(s.toString());
if (editText.getText().toString().isEmpty()){
clearQueryImageView.setVisibility(View.GONE);
voiceSearchImageView.setVisibility(View.VISIBLE);
}else{
clearQueryImageView.setVisibility(View.VISIBLE);
voiceSearchImageView.setVisibility(View.GONE);
}
}
});
voiceSearchImageView = findViewById(R.id.voice_search_query);
//button clic to show speech to text dilog
voiceSearchImageView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
} );
clearQueryImageView = findViewById(R.id.clear_search_query);
clearQueryImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText.setText("");
}
});
}
private void speak() {
//intent is show speech to text dialog
Intent intent= new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH );
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault() );
intent.putExtra( RecognizerIntent.EXTRA_PROMPT, "HI speak something" );
// Start intent
try {
//in there was no errror
//show dilog
startActivityForResult( intent, REQUEST_CODE_SPEECH_INPUT);
}
catch(Exception e){
//show messageof error and show
Toast.makeText( this,""+e.getMessage(), Toast.LENGTH_SHORT ).show();
}
}
//recive voice input and handle it
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult( requestCode, resultCode, data );
switch (requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if(resultCode==RESULT_OK && null!=data){
//get text arry form voice intent
ArrayList<String> result=data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS );
//set to text view
editText.setText( result.get( 0 ) );
}
break;
}
}
}
public void storeDataInArrays(){
dataholder = new ArrayList<>();
String code = "";
boolean firstTime = true;
int section = 0, count = 0;
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
noSearchResultsFoundText.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
if (firstTime) {
code = cursor.getString(1);
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), true, section);
firstTime = false;
dataholder.add(obj);
}
else
{
if (!code.equals(cursor.getString(1))) {
section = count;
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), true, section);
dataholder.add(obj);
code = cursor.getString(1);
}
else
{
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), false, section);
dataholder.add(obj);
}
}
count++;
}
noSearchResultsFoundText.setVisibility(View.GONE);
}
}
}
Please gives me solution how can I solve this!

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));

How to change the rows color in Listview on specific data from Sqlite database

I have custom list view and my data is coming from sqlite database. Now I want to change specific listview item's background color according to the id. First, I check the id if exist in database, then change particular item row background color according to the id.
My problem is that it checks successfully, but when I tried to change background color it changes whole listview background color. Here is picture and code of my data. Then you'll get my point, what actually I want to say you!
My db:
Whole listview color change:
My code:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean highlight=false;
LinearLayout linearLayout;
public String ex="switch";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
//check if id is exits in db
if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
{
holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
}
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();
/* ColorPicker colorPicker = new ColorPicker(activity);
ArrayList<String>colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
// holder.linearLayout.setBackgroundColor(color);
}
#Override
public void onCancel() {
}
}).show();*/
return false;
}
});
/*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
return false;
}
});*/
//verselist highlight
/*holder.verselist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*/
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
/* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
*/
//My toggle button
/* holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
private LinearLayout linearLayout;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
/*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)v.findViewById(R.id.layout);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public void opecolorpicker(){
}
}
Assuming you store the IDs in private List<String>verseid;, you can use it to check the ID of current ListView item.
The current item position is passed to you in final int position parameter.
So to check and apply color:
Remove
if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
{
holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
}
from if (convertView == null) {
Then add this code right outside that if:
if("1001001".equals(verseid.get(position))) {
//change the color
} else {
//set the color to default
}
Note that due to the way the ListView works (recycling items) you have to set the default color inside else.

Can't access ArrayAdapter from AlertDialog

TL;DR
I don't understand how to change my ArrayList dataset from a dialog so that it updates my listview. My current solution crashes because the ListView doesn't update. Need to know where my code is going wrong.
The Problem
I have one activity that has a ListView of items with an ArrayAdapter that connects it to my data (ArrayList). When a user clicks on an item in that list I load an AlertDialog that allows the user to delete that item. Debugging shows that the item does get removed from the data, the dialog closes as expected but the ListView doesn't update and subsequent clicks cause the app to crash.
The problem seems to be tied to the itemsList.notifyDataSetChanged();. I've tried hitting the adapter instead but then the Adapter itself can't be resolved.
I know this is due to an error on my part but I can't find where I'm going wrong.
The Code
ScannerActivity.java
import android.content.Intent;
import android.graphics.pdf.PdfDocument;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class ScannerActivity extends AppCompatActivity {
Button delete, deleteAll, manual, export, newPull;
EditText input_main;
static int pulls = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
//Load some items for testing
final PullSheet pullSheet = new PullSheet();
pullSheet.createSheet(nameText, roleText, storeText, runitText);
pullSheet.addItem("12543", 5);
pullSheet.addItem("3526", 1);
pullSheet.addItem("00045", 3);
pullSheet.addItem("95462", 18);
pullSheet.addItem("1181", 53);
pullSheet.addItem("6543", 1);
final ArrayAdapter<PullItem> itemAdapter =
new ArrayAdapter<PullItem>(this, 0, pullSheet.SheetItems) {
#Override
public View getView(int position,
View convertView,
ViewGroup parent){
PullItem currentItem = getItem(position);//
if(convertView == null) {
convertView = getLayoutInflater()
.inflate(R.layout.item, null, false);
}
TextView itemSku =
(TextView)convertView.findViewById(R.id.item_sku);
TextView itemQty =
(TextView)convertView.findViewById(R.id.item_qty);
itemSku.setText(currentItem.sku);
itemQty.setText(String.valueOf(currentItem.qty));
return convertView;
}
};
final ListView itemsList = (ListView) findViewById(R.id.itemsList);
itemsList.setAdapter(itemAdapter);
itemsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> itemAdapter,
View view, int position, long rowId) {
final PullItem item = pullSheet.SheetItems.get(position);
final PullSheet sheet = pullSheet;
//load dialog
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ScannerActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.dialog_interact, null);
//Declare dialog ui elements
Button mYes = (Button) mView.findViewById(R.id.btnYes);
Button mNo = (Button) mView.findViewById(R.id.btnNo);
TextView skuData = (TextView) mView.findViewById(R.id.skuData);
TextView qtyData = (TextView) mView.findViewById(R.id.qtyData);
skuData.setText(item.sku);
qtyData.setText(item.qty.toString());
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
itemsList.notifyDataSetChanged();// This isn't working, "Cannot resolve method notifyDataSetChanged()"
dialog.dismiss();
}
});
mNo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
public void deletePullItem(PullSheet sheet, PullItem item)
{
sheet.removeItem(item);
}
}
PullSheet.java
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
public class PullSheet extends Application{
protected String pullerName;
protected String role;
protected String store;
protected String sheetId;
protected String runItId;
protected Long startTime = System.currentTimeMillis();
protected ArrayList<PullItem> SheetItems = new ArrayList<PullItem>();
public void createSheet(String _pullerName, String _role, String _store, String _runItId){
setPullerName(_pullerName);
setRole(_role);
setStore(_store);
setRunItId(_runItId);
setSheetId();
}
protected void addItem(String sku, Integer qty){
SheetItems.add(new PullItem(sku, qty));
}
protected void removeItem(PullItem item){
this.SheetItems.remove(item);
}
//Getters and setters
public String getPullerName(){ return pullerName; }
public String getRole(){
return role;
}
public String getStore(){
return store;
}
public String getRunItId(){
return runItId;
}
public String getSheetId(){
return sheetId;
}
public Long getStartTime(){
return startTime;
}
private void setPullerName(String _pullerName){ pullerName = _pullerName; }
private void setRole(String _role){ pullerName = _role; }
private void setStore(String _store){ store = _store; }
private void setRunItId(String _runItId){ runItId = _runItId; }
private void setSheetId(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String dateString = formatter.format(new Date(startTime));
UUID uuid = UUID.randomUUID();
String randUUID = uuid.toString();
sheetId = dateString + "-" + this.pullerName + "-" + randUUID + "-" + runItId;
}
}
PullItem.java
public class PullItem {
protected String sku;
protected Integer qty;
public PullItem(String sku, Integer qty) {
setSku(sku);
this.qty = 1;
}
String getSku(){ return sku; }
Integer getQty(){ return qty; }
void setSku(String _sku){ sku = _sku; }
void setQty(Integer _qty){ qty = _qty; }
void incrementQty(){ qty += 1; }
}
The Solution
I need to be told where I'm going wrong. I know it has to do with the ArrayAdapter and the ListView, but Everything I've tried just moves the "Can't resolve" to another part of the expression.
Thanks in advance for any help
notifyDatasetChanged() is an Adapter method, so you can't use it with ListView
But this should work:
Make your Adapter a member variable (instantiate it the way you did) so you can access it everywhere in the Activity:
private ArrayAdapter<PullItem> itemAdapter;
Simply call deletePullItem() if the user clicks the OK-Button:
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
dialog.dismiss();
}
});
And call notifyDatasetChanged() when really deleting the item:
public void deletePullItem(PullSheet sheet, PullItem item)
{
sheet.removeItem(item);
itemAdapter.notifyDatasetChanged();
}
Try this:
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
itemsList.getAdapter().notifyDataSetChanged();
dialog.dismiss();
}
});

Categories

Resources