I have been making an app that will ask a name at the first start of my app and should display it afterwards but whenever I am trying to save either I am Having a NullPointerExceptionor the name
display is empty.
This is my MainActivity
package com.example.sas;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements namedialog.ExampleDialogListenerName {
private ImageView imageView;
public static final int IMAGE_PICK_CODE = 1000;
private SharedPreferences prefs;
public static final int PERMISSION_CODE = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
boolean firststart = preferences.getBoolean("firstStart",true);
if (firststart) {
OpenNameDialog();
}else {
savename();
}
TextView dateview = findViewById(R.id.date);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
String date = dateFormat.format(calendar.getTime());
dateview.setText(date);
imageView = findViewById(R.id.selfpicture);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_DENIED){
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISSION_CODE);
}else {
pickImageFromGallery();
}
}else {
pickImageFromGallery();
}
}
});
}
private void OpenNameDialog(){
namedialog namedialog = new namedialog();
namedialog.show(getSupportFragmentManager(),"name dialog");
SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart",false);
editor.apply();
}
#Override
public void ApplyNameDialog(String name) {
prefs = getSharedPreferences("prefs",MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("susanth",name);
}
public void savename(){
String names = prefs.getString("susanth","");
TextView display = findViewById(R.id.namename);
display.setText(names);
}
public void pickImageFromGallery(){
Intent intent1 = new Intent(Intent.ACTION_PICK);
intent1.setType("image/*");
startActivityForResult(intent1,IMAGE_PICK_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE:{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
pickImageFromGallery();
}else {
Toast.makeText(getApplicationContext(),"Permission Denied",Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
imageView.setImageURI(data.getData());
}
}
}
This is my namedialog
package com.example.sas;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import java.util.Objects;
public class namedialog extends AppCompatDialogFragment {
private EditText name ;
private ExampleDialogListenerName listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = Objects.requireNonNull(getActivity()).getLayoutInflater();
View view = inflater.inflate(R.layout.namedialog,null);
builder.setView(view)
.setTitle("Welcome Fill your details")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String namef = name.getText().toString();
listener.ApplyNameDialog(namef);
}
});
name = view.findViewById(R.id.etname);
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
context = getActivity();
super.onAttach(context);
try {
listener = (ExampleDialogListenerName) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()+
"must implement ExampleDialogListenerName");
}
}
public interface ExampleDialogListenerName{
void ApplyNameDialog (String name);
}
}
Can you tell me what should I use for storing the name permanently.
Please Help Me Fast Thank You :)
#Override
public void ApplyNameDialog(String name) {
prefs = getSharedPreferences("prefs",MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("susanth",name);
}
It seems like the string is never saved. You should call editor.commit() or editor.apply()
Related
I have made an android application using java, and I have made a click listener interface but nothing seems to happen and I can't figure out what is wrong with my code. Please help.
Following is the code of my recyclerViewAdapter:
package com.example.ashwamedh.adapter;
import android.content.Context;
import android.util.Log;
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.ashwamedh.R;
import com.example.ashwamedh.model.AdminConfirmation;
import com.example.ashwamedh.model.Attendance;
import com.example.ashwamedh.model.Confirmation;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
import java.util.Objects;
public class ManageAttendanceRecyclerViewAdapter extends RecyclerView.Adapter<ManageAttendanceRecyclerViewAdapter.ViewHolder> {
private List<Confirmation> practiceList;
private Context context;
private OnAttendanceClickListener onAttendanceClickListener;
private CollectionReference collectionReference = FirebaseFirestore.getInstance().collection("Users");
public ManageAttendanceRecyclerViewAdapter(List<Confirmation> practiceList, Context context, OnAttendanceClickListener onAttendanceClickListener) {
this.practiceList = practiceList;
this.context = context;
this.onAttendanceClickListener = onAttendanceClickListener;
}
#NonNull
#Override
public ManageAttendanceRecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context)
.inflate(R.layout.manage_attendance_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull ManageAttendanceRecyclerViewAdapter.ViewHolder holder, int position) {
Confirmation confirmation = practiceList.get(position);
holder.nameTextView.setText(confirmation.getUsername());
if (confirmation.getRemarkOrReason() == "") {
holder.remarkOrReasonTextView.setText("null");
}else {
holder.remarkOrReasonTextView.setText(confirmation.getRemarkOrReason());
}
if (Objects.equals(confirmation.getConfirmation(), "present")) {
holder.confirmation.setImageResource(R.drawable.ic_baseline_check_24);
} else if (Objects.equals(confirmation.getConfirmation(), "absent")){
holder.confirmation.setImageResource(R.drawable.ic_baseline_close_24);
}
}
#Override
public int getItemCount() {
return practiceList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView nameTextView;
private ImageView confirmation;
private TextView remarkOrReasonTextView;
OnAttendanceClickListener onAttendanceClickListener;
public ViewHolder(#NonNull View itemView, Context ctx) {
super(itemView);
this.onAttendanceClickListener = ManageAttendanceRecyclerViewAdapter.this.onAttendanceClickListener;
context = ctx;
nameTextView = itemView.findViewById(R.id.manage_attendance_name_textview);
confirmation = itemView.findViewById(R.id.manage_attendance_confirmation);
remarkOrReasonTextView = itemView.findViewById(R.id.manage_attendance_remark_reason_textview);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.manage_attendance_row:
Log.d("from recycler view", "onClick: " + "row clicked");
Confirmation confirmation = practiceList.get(getAdapterPosition());
String userId = confirmation.getUserId();
onAttendanceClickListener.OnAttendanceClick(userId);
}
}
}
}
Following is the code of OnAttendanceClickListener:
package com.example.ashwamedh.adapter;
public interface OnAttendanceClickListener {
void OnAttendanceClick(String userId);
}
Following is the code of the activity where the recycler view is used and the interface implemented:
package com.example.ashwamedh;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ashwamedh.adapter.ManageAttendanceRecyclerViewAdapter;
import com.example.ashwamedh.adapter.OnAttendanceClickListener;
import com.example.ashwamedh.model.Confirmation;
import com.example.ashwamedh.util.UserApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class ManagePracticeConfirmationActivity extends AppCompatActivity implements OnAttendanceClickListener {
private static final String TAG = "PRACTICE_CONFIRMATION";
private RecyclerView recyclerView;
private BottomNavigationView bottomNavigationView;
private CardView markAttendanceCardView;
private FloatingActionButton presentFab;
private FloatingActionButton absentFab;
private Button updateButton;
private TextView noPracticeTextView;
private ImageButton signOut;
private Boolean isAdmin;
private String attendance;
private ManageAttendanceRecyclerViewAdapter manageAttendanceRecyclerViewAdapter;
private String practiceDate;
private List<Confirmation> practiceList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference collectionReference = db.collection("Confirmations");
private CollectionReference userCollection = db.collection("Users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_practice_confirmation);
Objects.requireNonNull(getSupportActionBar()).hide();
practiceList = new ArrayList<>();
recyclerView = findViewById(R.id.manage_attendance_recycler_view);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
markAttendanceCardView = findViewById(R.id.mark_attendance_cardView);
presentFab = findViewById(R.id.present_fab);
absentFab = findViewById(R.id.absent_fab);
updateButton = findViewById(R.id.update_attendance_button);
noPracticeTextView = findViewById(R.id.no_practice_textView);
signOut = findViewById(R.id.signOut_manage_attendance);
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
bottomNavigationView.setSelectedItemId(R.id.manage_practice_confirmation_button);
markAttendanceCardView.setVisibility(View.INVISIBLE);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
attendance = "";
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
Log.d(TAG, "onCreate: " + Calendar.DAY_OF_WEEK);
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
recyclerView.setVisibility(View.INVISIBLE);
noPracticeTextView.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
noPracticeTextView.setVisibility(View.INVISIBLE);
}
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.council_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, CouncilActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.attendance_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, BatchmateAttendance.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.manage_practice_confirmation_button) {
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
collectionReference.whereEqualTo("practiceDate", practiceDate)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {
Confirmation confirmation = snapshot.toObject(Confirmation.class);
practiceList.add(confirmation);
}
manageAttendanceRecyclerViewAdapter = new ManageAttendanceRecyclerViewAdapter(practiceList,
ManagePracticeConfirmationActivity.this,
ManagePracticeConfirmationActivity.this);
recyclerView.setAdapter(manageAttendanceRecyclerViewAdapter);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
#Override
public void OnAttendanceClick(String userId) {
Log.d(TAG, "OnAttendanceClick: "+ isAdmin);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
if (isAdmin) {
markAttendanceCardView.setVisibility(View.VISIBLE);
presentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "present";
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
}
});
absentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "absent";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Confirmation confirmation = new Confirmation();
confirmation.setUserId(userId);
confirmation.setConfirmation(attendance);
confirmation.setPracticeDate(practiceDate);
if (Objects.equals(attendance, "present")) {
confirmation.setRemarkOrReason("PRESENT ON PRACTICE");
} else if (Objects.equals(attendance, "absent")){
confirmation.setRemarkOrReason("ABSENT ON PRACTICE");
}
SimpleDateFormat documentDateFormat = new SimpleDateFormat("dd_MM_yyyy");
String docDate = documentDateFormat.format(practiceDate);
String docAddress = userId+"_"+docDate;
collectionReference.document(docAddress)
.set(confirmation)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Attendance marked!", Toast.LENGTH_SHORT)
.show();
}
});
attendance = "";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
markAttendanceCardView.setVisibility(View.INVISIBLE);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
});
} else {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Only admins can mark attendance!", Toast.LENGTH_SHORT)
.show();
}
}
}
Please help me I am clueless of where is the error
RecyclerView clicks doesn't work like that.
Firstly you should write click event in onBindViewHolder
holder.itemView.setOnClickListener(view -> onAttendanceClickListener.OnAttendanceClick(userId));
Put this code in your onBindViewHolder and you are good to go!
You will receive click events in Activity.
I am trying to filter my RecyclerView using SearchView by following this guide: https://www.geeksforgeeks.org/searchview-in-android-with-recyclerview/
However, I am getting an IndexOutOfBoundsException when making one Arraylist equal to another, which I believe is happening at this portion of the code here:
public void filterList(ArrayList filteredlist) {
// below line is to add our filtered
// list in our course array list.
book_title = filteredlist;
// below line is to notify our adapter
// as change in recycler view data.
notifyDataSetChanged();
}
Here is the full code for my adapter class:
package com.benjamin.kwok.recipertracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
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.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList book_id, book_title, book_author, book_pages;
CustomAdapter(Activity activity, Context context, ArrayList book_id, ArrayList book_title, ArrayList book_author,
ArrayList book_pages){
this.activity = activity;
this.context = context;
this.book_id = book_id;
this.book_title = book_title;
this.book_author = book_author;
this.book_pages = book_pages;
}
public void filterList(ArrayList filteredlist) {
// below line is to add our filtered
// list in our course array list.
book_title = filteredlist;
// below line is to notify our adapter
// as change in recycler view data.
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.book_title_txt.setText(String.valueOf(book_title.get(position)));
holder.book_author_txt.setText(String.valueOf(book_author.get(position)));
holder.book_pages_txt.setText(String.valueOf(book_pages.get(position)));
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(book_id.get(position)));
intent.putExtra("title", String.valueOf(book_title.get(position)));
intent.putExtra("author", String.valueOf(book_author.get(position)));
intent.putExtra("pages", String.valueOf(book_pages.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return book_id.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView book_id_txt, book_title_txt, book_author_txt, book_pages_txt;
LinearLayout mainLayout;
MyViewHolder(#NonNull View itemView) {
super(itemView);
book_title_txt = itemView.findViewById(R.id.recipe_title_txt);
book_author_txt = itemView.findViewById(R.id.book_description_txt);
book_pages_txt = itemView.findViewById(R.id.recipe_pages_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
}
And the full code for my MainActivity:
package com.benjamin.kwok.recipertracker;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
FloatingActionButton camera_button;
ImageView empty_imageview;
ImageView imageView;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> recipe_id, recipe_title, recipe_description, recipe_minutes;
CustomAdapter customAdapter;
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
private static final String TAG = "CapturePicture";
static final int REQUEST_PICTURE_CAPTURE = 1;
private String pictureFilePath;
private String deviceIdentifier;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
// SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(this);
// SharedPreferences.Editor editor = mSharedPreference.edit();
// String text= mSharedPreference.getString(getString(R.string.name), "");
//// name_output.setText(text);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
camera_button = findViewById(R.id.camera_button);
empty_imageview = findViewById(R.id.empty_imageview);
imageView = findViewById(R.id.imageView);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
camera_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 100);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
recipe_id = new ArrayList<>();
recipe_title = new ArrayList<>(10);
recipe_description = new ArrayList<>();
recipe_minutes = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(MainActivity.this,this, recipe_id, recipe_title, recipe_description,
recipe_minutes);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
loadData();
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
Bundle bundle = data.getExtras();
Bitmap captureImage = (Bitmap) bundle.get("data");
imageView.setImageBitmap(captureImage);
saveToGallery();
}
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image added to Gallery", Toast.LENGTH_LONG);
}
}
private void saveToGallery(){
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/RecipeImages");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
MediaScannerConnection.scanFile(this, new String[] { outFile.getPath() }, new String[] { "image/jpeg" }, null);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
recipe_id.add(cursor.getString(0));
recipe_title.add(cursor.getString(1));
recipe_description.add(cursor.getString(2));
recipe_minutes.add(cursor.getString(3));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
public void loadData() {
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = mPreferences.getString("name","");
setTitle(name+"'s" + " Recipe Tracker");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
// return super.onCreateOptionsMenu(menu);
MenuItem searchItem = menu.findItem(R.id.actionSearch);
// getting search view of our item.
SearchView searchView = (SearchView) searchItem.getActionView();
// below line is to call set on query text listener method.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// inside on query text change method we are
// calling a method to filter our recycler view.
filter(newText);
return false;
}
});
return true;
}
private void filter(String text) {
// creating a new array list to filter our data.
ArrayList filteredlist = new ArrayList<>();
// running a for loop to compare elements.
for (String item : recipe_title) {
// checking if the entered string matched with any item of our recycler view.
if (item.toLowerCase().contains(text.toLowerCase())) {
// if the item is matched we are
// adding it to our filtered list.
filteredlist.add(item);
}
}
if (filteredlist.isEmpty()) {
// if no item is added in filtered list we are
// displaying a toast message as no data found.
Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
} else {
// at last we are passing that filtered
// list to our adapter class.
customAdapter.filterList(filteredlist);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(MainActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
As soon as I start typing in a new search query, this error seems to get thrown.
I have something weird in my fragment, when the activity is restarted or paused, fragments are not responding to my onClick events and this is my code , what should i do to not face this problem again
hint this is a sign up fragment that returns an model object to the activity throw communicator, i hove any one can help me
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.gahez.gahez.Constants;
import com.gahez.gahez.Definer;
import com.gahez.gahez.R;
import com.gahez.gahez.activities.UserSignUpActivity;
import com.gahez.gahez.data_wrappers.Courier;
import com.gahez.gahez.fragments.interfaces.SignUpCommunicator;
import com.gahez.gahez.utilities.Utilities;
import java.io.File;
import java.io.IOException;
public class SignUpFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private ImageView profilePicImageView;
private ImageView showPasswordIMageView;
private EditText passwordEditText;
private EditText emailEditText;
private EditText userNameEditText;
private EditText phoneEditText;
private EditText confirmPasswordEditText;
private EditText nationalIdEditText;
private Button signUpButton;
private TextView addImageTextView;
private CheckBox maleCheckBox;
private CheckBox femaleCheckBox;
private ConstraintLayout backgroundConstraintLayout;
public Activity context;
private Intent outComingIntent;
private SignUpCommunicator communicator;
private File userPhotoFile;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.signup_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setContext();
setCommunicator();
defineViews();
setListeners();
Definer.setupUI(backgroundConstraintLayout,context);
}
//my methods
//---------------------------------------------------------------------------------------------
public void setListeners(){
signUpButton.setOnClickListener(this);
maleCheckBox.setOnCheckedChangeListener(this);
femaleCheckBox.setOnCheckedChangeListener(this);
profilePicImageView.setOnClickListener(this);
}
public void defineViews() {
profilePicImageView = context.findViewById(R.id.profile_pic);
showPasswordIMageView = context.findViewById(R.id.password_show);
passwordEditText =context.findViewById(R.id.password);
signUpButton=context.findViewById(R.id.next);
emailEditText= context.findViewById(R.id.email);
userNameEditText= context.findViewById(R.id.username);
phoneEditText= context.findViewById(R.id.phone_number);
confirmPasswordEditText= context.findViewById(R.id.conferim_password);
backgroundConstraintLayout=context.findViewById(R.id.background_constraint_layout);
addImageTextView = context.findViewById(R.id.add_image_text);
maleCheckBox=context.findViewById(R.id.male_check_box);
femaleCheckBox=context.findViewById(R.id.female_check_box);
nationalIdEditText= context.findViewById(R.id.national_id_edit_text);
}
public void setContext(){
context=getActivity();
}
public void setCommunicator(){
this.communicator =(SignUpCommunicator) getActivity();
}
public Courier getCourier(){
Courier courier = null;
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmationPassword = confirmPasswordEditText.getText().toString();
String phoneNumber = phoneEditText.getText().toString();
String userName = userNameEditText.getText().toString();
String nationalId = nationalIdEditText.getText().toString();
String gender = getGender();
if(!email.equals("")&&!password.equals("")&&!confirmationPassword.equals("")&&
!phoneNumber.equals("")&&!userName.equals("")&&!gender.equals("")&&!nationalId.equals(""))
courier = new Courier("carrier",userName,email,password,phoneNumber,
gender,nationalId);
return courier; //it returns null if any field is empty
}
public String getGender() {
String gender="male";
if(femaleCheckBox.isChecked())
gender="female";
return gender;
}
public String validatePasswords(){
String password = passwordEditText.getText().toString();
String confirmationPassword = confirmPasswordEditText.getText().toString();
if(password.equals(confirmationPassword)){
if(password.length()>=8)
return Constants.VALID_PASSWORD;
else
return Constants.SHORT_PASSWORD;
}else
return Constants.NOT_MATCHING_PASSWORDS;
}
public boolean isValidDataEntry(Courier courier){
if(courier==null) { //if courier is null then the fun getCourier find one or more field empty
Toast.makeText(context, getString(R.string.complete_your_data), Toast.LENGTH_SHORT).show();
return false;
}else {
if(!Definer.validateEmailAddress(emailEditText.getText().toString())) {
Toast.makeText(context, getString(R.string.invaild_email_address), Toast.LENGTH_SHORT).show();
return false;
}
else {
String passwordValidationResult = validatePasswords();
if(passwordValidationResult.equals(Constants.SHORT_PASSWORD)) {
Toast.makeText(context, getString(R.string.password_must_be_eight_chars_at_least)
, Toast.LENGTH_SHORT).show();
return false;
}
else if(passwordValidationResult.equals(Constants.NOT_MATCHING_PASSWORDS)) {
Toast.makeText(context,
getString(R.string.passwords_are_not_matching),
Toast.LENGTH_SHORT).show();
return false;
}
else return true;
}
}
}
public boolean checkStoragePermissions(){
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(Constants.STORAGE_PERMISSIONS,Constants.EXTERNAL_STORAGE_PERMISSIONS_REQUEST_CODE);
Log.d(Constants.LOG_TAG,"hello");
return false;
}else
{
return true;
}
}
private void getImageFromDevice() {
if(checkStoragePermissions()) {
outComingIntent = new Intent(Intent.ACTION_GET_CONTENT);
outComingIntent.setType("image/*");
startActivityForResult(outComingIntent, Constants.PROFILE_IMAGE_REQUEST_CODE);
}
}
//override methods
//----------------------------------------------------------------------------------------------
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.next:
Courier courier = getCourier();
if(isValidDataEntry(courier))
communicator.onSignUpDataConfirmed(courier);
break;
case R.id.profile_pic:
getImageFromDevice();
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==context.RESULT_OK){
if(data!=null){
if(requestCode==Constants.PROFILE_IMAGE_REQUEST_CODE) {
Uri imageUri = data.getData();
try {
Bitmap profileImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(),imageUri);
this.userPhotoFile = new File(Utilities.getRealPathFromURI(imageUri,context));
profilePicImageView.setImageBitmap(Utilities.resizeBigImages(profileImage));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Constants.EXTERNAL_STORAGE_PERMISSIONS_REQUEST_CODE:
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(Constants.STORAGE_PERMISSIONS[0])) {
Log.d(Constants.LOG_TAG, "noo");
Utilities.showBasicAlertDialog(
context,
R.drawable.ic_baseline_warning_24,
getString(R.string.permission_alert),
getString(R.string.go_to_settings_grant_the_storage_permissions_to_use_this_feature),
getString(R.string.ok),
null,
(dialog, which) -> {
dialog.dismiss();
},
null
);
}
else
Utilities.showBasicAlertDialog(
context,
R.drawable.ic_baseline_warning_24,
getString(R.string.permission_alert),
getString(R.string.you_need_to_grant_storage_permissions),
getString(R.string.yes),
getString(R.string.not_now),
(dialog, which) -> {
getImageFromDevice();
},
(dialog, which) -> {
dialog.dismiss();
}
);
break;
}
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()){
case R.id.male_check_box:
if(isChecked)
femaleCheckBox.setChecked(false);
break;
case R.id.female_check_box:
if(isChecked)
maleCheckBox.setChecked(false);
break;
default:
break;
}
}
}```
I would try changing where you call defineViews(); and setListeners();
onCreateView() is the ideal place to do this since it is a method used by the Fragment itself and not by the activity lifecycle.
Whereas onActivityCreated() is only called when the fragment is created or reattached but not when it is restarted.
I developed a word app that contains English vocabularies and users can add their favorite word by clicking on a floating button. Every time my favorite list has at list one item it is updated but when it's empty it doesn't show anything but when I run app again list updates.
if you need any code let me know to send it .
UPDATE:
Inner page :
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
Update 2:
package farmani.com.essentialwordsforielts.mainPage;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import farmani.com.essentialwordsforielts.R;
public class PageFragment extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
RecyclerView recyclerView;
AdapterFav adapterFav;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
if (mPage == 1) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
AdapterList adapter = new AdapterList(MainActivity.context);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
if (mPage == 2) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
adapterFav = new AdapterFav(MainActivity.context);
recyclerView.setAdapter(adapterFav);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
return view;
}
#Override
public void onResume() {
super.onResume();
if (adapterFav != null){
adapterFav.notifyDataSetChanged();
}
}
}
Update 3 :AdapterFav
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
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.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
Update 4: MainActivity
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.nabinbhandari.android.permissions.PermissionHandler;
import com.nabinbhandari.android.permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
import farmani.com.essentialwordsforielts.setting.ActivitySetting;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
Permissions.check(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
" storage permissions are required to copy database", new Permissions.Options()
.setSettingsDialogTitle("Warning!").setRationaleDialogTitle("Info"),
new PermissionHandler() {
#Override
public void onGranted() {
setupDB();
selectList();
selectFavorite();
}
});
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}else if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this, ActivitySearch.class);
MainActivity.this.startActivity(intent);
} else if (id == R.id.setting) {
Intent intent = new Intent(MainActivity.this, ActivitySetting.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
if (!list.isEmpty()){
list.clear();
selectList();
} if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
}
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
Update 5 innerpage activity
package farmani.com.essentialwordsforielts.innerpage;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.lang.reflect.Field;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.mainPage.AdapterFav;
public class ActivityInnerPage extends AppCompatActivity {
private TextView contentDescriptione;
private TextView moreDescriptione;
private ImageView avatar;
private ImageView imgCopy;
private ImageView imgShare;
private ImageView imgSms;
private ImageView imgGmail;
private FloatingActionButton favorite;
private CollapsingToolbarLayout collapsingToolbarLayout;
public String word;
public String definition;
public String trans;
public String img;
public int id;
private String destpath;
private SQLiteDatabase database;
private String favoriteState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_page);
final android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
int layoutId = Integer.parseInt(extras.getString("id"));
String pageName = extras.getString("name");
assert pageName != null;
if (pageName.equals("list")) {
id = MainActivity.list.get(layoutId).getId();
word = MainActivity.list.get(layoutId).getWord();
definition = MainActivity.list.get(layoutId).getDefinition();
trans = MainActivity.list.get(layoutId).getTrans();
img = MainActivity.list.get(layoutId).getImg();
} else if (pageName.equals("favorite")) {
id = MainActivity.favorite.get(layoutId).getId();
word = MainActivity.favorite.get(layoutId).getWord();
definition = MainActivity.favorite.get(layoutId).getDefinition();
trans = MainActivity.favorite.get(layoutId).getTrans();
img = MainActivity.favorite.get(layoutId).getImg();
}
}
contentDescriptione = findViewById(R.id.content_description);
moreDescriptione = findViewById(R.id.more_description);
imgCopy = findViewById(R.id.img_copy);
imgShare = findViewById(R.id.img_share);
imgSms = findViewById(R.id.img_sms);
imgGmail = findViewById(R.id.img_gmail);
avatar = findViewById(R.id.avatar);
favorite = findViewById(R.id.favorite);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.getExpandedTitleMarginStart();
collapsingToolbarLayout.setTitle(word);
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.holo_red_light));
contentDescriptione.setText(definition);
moreDescriptione.setText(trans);
int imgageId = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
avatar.setImageResource(imgageId);
SharedPreferences prefes = getSharedPreferences("font_size", MODE_PRIVATE);
int value = prefes.getInt("fontsize", 16);
contentDescriptione.setTextSize(value);
moreDescriptione.setTextSize(value);
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
imgCopy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ClipboardManager clipboardManager =
(ClipboardManager)ActivityInnerPage.this.getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newPlainText(word, trans+definition);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clip);
Snackbar.make(view,"متن کپی شد ",Snackbar.LENGTH_SHORT).show();
}
});
imgShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, definition+trans);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, word);
startActivity(Intent.createChooser(shareIntent, "Share"));
}
});
imgGmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO
, Uri.fromParts("mailto", "", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, word);
emailIntent.putExtra(Intent.EXTRA_TEXT, definition);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال ایمیل یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
imgSms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent sendSms = new Intent(Intent.ACTION_VIEW);
sendSms.putExtra("sms_body", definition + trans);
sendSms.setType("vnd.android-dir/mms-sms");
startActivity(sendSms);
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال پیام یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
}
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
}
In your FloatingActionButton onClick method after you save the new item in your database, insert your new item into your recyclerview datasource list and call notifyDatasetChanged() on the adapter.
Choice 1: in onResume() stub of MainActivity, call selectList() and selectFavorite() and then load the PageFragment again so that the new list is loaded properly.
This is the shortest wayout but this approach is very much unoptimized and is not recommended.
Choice 2: You will have to insert the new item in database as well as add it to the List and then call notifyDatasetChanged
In MainActivity within methods selectList() and selectFavorite() after you perform list.add(struct) and favourite.add(struct) respectively, you will have to call notifyDatasetChanged() for the Adapter.
But the problem is your RecyclerView is in the PageFragment whereas you're populating the list in MainActivity.
So move your selectList() and selectFavorite() to PageFragment where you first initialize the RecylerView then, set the Adapter and then populate the list and finally call notifyDatasetChanged() on your adapters.
I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
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 android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}