I wanna ask regarding this recycleview issues, my code doesnt show any problem,but why my recycleview output became like this RecycleView Output. I had tried by change switch case() to if else() but it will give error if I write throw new IllegalStateException("Unexpected value:" + data.getItem()); at the end of else. The app will crash and stop running if I did not commend the exception. When I still using switch case, it will came out an error of NullException
This is my code:
MainActivity() code
package com.example.assignment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button AddBtn;
private Button signOutBtn;
private RecyclerView recyclerView;
private FirebaseAuth auth;
private DatabaseReference ref;
private String userID = "";
private ProgressDialog progressDialog;
private ItemsAdapter itemsAdapter;
private ArrayList<Data> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
textView=findViewById(R.id.totalAmount);
AddBtn = findViewById(R.id.add_new);
auth = FirebaseAuth.getInstance();
userID = auth.getCurrentUser().getUid();
ref = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
progressDialog = new ProgressDialog(this);
AddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addItem();
}
});
recyclerView =findViewById(R.id.recycleView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
dataList = new ArrayList<>();
itemsAdapter = new ItemsAdapter(MainActivity.this, dataList);
recyclerView.setAdapter(itemsAdapter);
readItems();
// signOutBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// FirebaseAuth.getInstance().signOut();
// }
// });
}
private void readItems(){
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
Query query = databaseReference.orderByChild("date").equalTo(date);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
dataList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Data data = snapshot.getValue(Data.class);
dataList.add(data);
}
itemsAdapter.notifyDataSetChanged();
int totalAmount = 0;
for(DataSnapshot ds : snapshot.getChildren()){
Map<String, Object> map = (Map<String, Object>) ds.getValue();
Object total = map.get("amount");
int getTotal = Integer.parseInt(String.valueOf(total));
totalAmount+=getTotal;
textView.setText("Total Spending : RM" + totalAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void addItem() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//LayoutInflater layout = LayoutInflater.from(this);
LayoutInflater layout = getLayoutInflater();
View view = layout.inflate(R.layout.input_layout, (ViewGroup)findViewById(R.id.inputLayout));
setContentView(view);
final AlertDialog dialog = alert.create();
dialog.setCancelable(false);
final Spinner spinnerItem = view.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.category));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerItem.setAdapter(adapter);
final EditText amount = view.findViewById(R.id.insert_amount);
final EditText notes = view.findViewById(R.id.insert_note);
final Button saveButton = view.findViewById(R.id.add_button);
final Button cancelButton = view.findViewById(R.id.cancel_button);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountGet = amount.getText().toString();
String notesGet = notes.getText().toString();
String categoryGet = spinnerItem.getSelectedItem().toString();
Drawable icon = getResources().getDrawable(R.drawable.error);
if(amountGet.isEmpty()){
amount.setError("Please enter an amount!!!", icon );
return;
}
if(notesGet.isEmpty()){
notes.setError("Please enter a notes!!!", icon );
return;
}
if(categoryGet.equals("Select a Category")){
Toast.makeText(MainActivity.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Had added the information into database");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
String id = ref.push().getKey();
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
Data inform = new Data(categoryGet, date, id, notesGet, Integer.parseInt(amountGet));
ref.child(id).setValue(inform).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Information added successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Fail to add the information", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
});
}
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
dialog.dismiss();
}
});
}
}
ItemsAdapter() code
package com.example.assignment;
import android.content.Context;
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 java.util.List;
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.viewHolder> {
private Context context;
private List<Data> dataList;
public ItemsAdapter(Context context, List<Data> data) {
this.context = context;
this.dataList = data;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.output_layout, parent, false);
//return new ItemsAdapter.viewHolder(view);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
final Data data = dataList.get(position);
holder.category.setText("Category :" + data.getItem());
holder.amount.setText("Amount :" + data.getAmount());
holder.date.setText("Date :" + data.getDate());
holder.notes.setText("Note :" + data.getNotes());
// switch(data.getItem()){
//
// case "Petrol Spend":
// holder.imageView.setImageResource(R.drawable.petrol);
// break;
//
// case "Groceries Spend":
// holder.imageView.setImageResource(R.drawable.grocery);
// break;
//
// case "eWallet Transaction":
// holder.imageView.setImageResource(R.drawable.wallet);
// break;
//
// case "Other Eligible Spend":
// holder.imageView.setImageResource(R.drawable.spend);
// break;
//
// default:
// throw new IllegalStateException("Unexpected value:" + data.getItem());
// }
if(data.getItem() == "Petrol Spend"){
holder.imageView.setImageResource(R.drawable.petrol);
}else if(data.getItem() == "Groceries Spend"){
holder.imageView.setImageResource(R.drawable.grocery);
}else if(data.getItem() == "eWallet Transaction"){
holder.imageView.setImageResource(R.drawable.wallet);
}else if(data.getItem() == "Other Eligible Spend"){
holder.imageView.setImageResource(R.drawable.spend);
}
//else throw new IllegalStateException("Unexpected value:" + data.getItem());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
public TextView category, amount, date, notes;
public ImageView imageView;
public viewHolder(#NonNull View itemView) {
super(itemView);
category = itemView.findViewById(R.id.category);
amount = itemView.findViewById(R.id.amount);
date = itemView.findViewById(R.id.date);
notes = itemView.findViewById(R.id.note);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
Instead of :
dataList.add(data);
itemsAdapter.notifyDataSetChanged();
Try this:
// add this in the place of dataList.add(data)
adapter.setDataList(data);
// Add this setter inside the adapter;
setDataList(List<Data> datalist){
this.dataList = dataList;
notifyItemChanged(0,dataList);
}
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 encountered this error and tried to find some solutions but no clue yet. The problem is I am trying to search the item on my phone, once find it, I will click on the item and then update it.
However I got "com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.projects.inputData" error.
BEFORE I click update, my firebase looks like:
AFTER I updated item, it looks like this and all the old data has been automatically removed:
Can someone help me out? Please.
package com.example.projects;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.concurrent.TimeUnit;
public class mainActivity extends AppCompatActivity implements View.OnClickListener {
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
private FloatingActionButton main_fab;
private TextView total_amount, total_buy_price;
private RecyclerView mainRecyclerView;
private String post_key = "";
private String staff_name ="";
private String size = "";
private String material = "";
private String colour = "";
private String notes = "";
private String type = "";
private int money = 0;
private int number = 0;
public int soldNumber = 0;
public int soldPrice = 0;
ArrayList<inputData> dataList;
SearchView searchView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
firebaseDatabase = FirebaseDatabase.getInstance("https://stuff-management-app-default-rtdb.asia-southeast1.firebasedatabase.app");
mainRecyclerView = findViewById(R.id.main_recyclerview);
searchView = findViewById(R.id.searchView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
mainRecyclerView.setHasFixedSize(true);
mainRecyclerView.setLayoutManager(linearLayoutManager);
total_buy_price = findViewById(R.id.totalBuyPrice);
total_amount = findViewById(R.id.main_total_records);
myRef = firebaseDatabase.getReference("stuff records");
myRef.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
int totalRecord = 0;
int totalBuyPrice = 0;
dataList = new ArrayList<>();
for(DataSnapshot snap: snapshot.getChildren()){
inputData data = snap.getValue(inputData.class);
totalRecord += data.getNumber();
total_amount.setText( totalRecord);
totalBuyPrice += data.getMoney();
total_buy_price.setText( totalBuyPrice);
dataList.add(snap.getValue(inputData.class));
}
AdapterClass adapterClass = new AdapterClass(dataList);
mainRecyclerView.setAdapter(adapterClass);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str) {
ArrayList<inputData> myList = new ArrayList<>();
for(inputData object : dataList){
if (object.getStaff_name().toLowerCase().contains(str.toLowerCase())){
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(myList);
mainRecyclerView.setAdapter(adapterClass);
adapterClass.notifyDataSetChanged();
}
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
private void updateInfo() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View mView = inflater.inflate(R.layout.update_page, null);
myDialog.setView(mView);
final AlertDialog dialog = myDialog.create();
final Spinner itemSpinner = mView.findViewById(R.id.input_size_spinner);
final TextView input_name = mView.findViewById(R.id.input_record);
final EditText input_price = mView.findViewById(R.id.input_price);
final EditText input_number = mView.findViewById(R.id.input_number);
final EditText input_description = mView.findViewById(R.id.input_description);
final EditText input_material = mView.findViewById(R.id.input_material);
final Spinner colourSpinner = mView.findViewById(R.id.input_colour_spinner);
final EditText input_types = mView.findViewById(R.id.input_type);
final Button delBtn = mView.findViewById(R.id.input_cancel);
final Button updateBtn = mView.findViewById(R.id.input_save);
final Button sellBtn = mView.findViewById(R.id.button2);
input_price.setText(String.valueOf(money));
input_description.setText(notes);
input_name.setText(staff_name);
input_material.setText(material);
colourSpinner.setSelection(getIndex(colourSpinner, colour));
input_types.setText(type);
input_number.setText(String.valueOf(number));
itemSpinner.setSelection(getIndex(itemSpinner, size));
//sold
final EditText sellNum = mView.findViewById(R.id.sellAmount);
final EditText sellPrice = mView.findViewById(R.id.sellMoney);
sellNum.setText(String.valueOf(number - 1));
sellPrice.setText(String.valueOf(soldPrice));
String sellNumber = sellNum.getText().toString();
String sellPri = sellPrice.getText().toString();
String[] colourr = new String[]{};
final List<String> colourList = new ArrayList<String>(Arrays.asList(colourr));
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, R.layout.spinner_item, colourList);
myRef = firebaseDatabase.getReference("user_define_colour");
// Attach a listener to read the data at our posts reference
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
colourList.clear();
for (DataSnapshot child : dataSnapshot.getChildren()) {
GenericTypeIndicator<ArrayList<String>> t = new GenericTypeIndicator<ArrayList<String>>() {
};
ArrayList<String> value = child.getValue(t);
colourList.addAll(value);
spinnerArrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
colourSpinner.setAdapter(spinnerArrayAdapter);
// ----- retrieve colour from firebase
myRef = firebaseDatabase.getReference("stuff records");
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
number = Integer.parseInt(input_number.getText().toString());
notes = input_description.getText().toString();
money = Integer.parseInt(input_price.getText().toString());
staff_name = input_name.getText().toString();
material = input_material.getText().toString();
colour = colourSpinner.getSelectedItem().toString();
type = input_types.getText().toString();
size = itemSpinner.getSelectedItem().toString();
if ( number == 0) {
Toast.makeText(mainActivity.this, "Finished", Toast.LENGTH_SHORT).show();
return;
}
inputData data = new inputData(staff_name, size, material, colour, notes, Integer.parseInt(String.valueOf(money)), Integer.parseInt(String.valueOf(number)), post_key, type);
myRef.child(post_key).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(mainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}
});
}
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.myViewHolder> {
ArrayList<inputData> dataList;
public AdapterClass(ArrayList<inputData> dataList) {
this.dataList = dataList;
}
#NonNull
#Override
public AdapterClass.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_retrieve, parent, false);
return new AdapterClass.myViewHolder(view);
}
FirebaseRecyclerOptions<inputData> options = new FirebaseRecyclerOptions.Builder<inputData>()
.setQuery(myRef,inputData.class)
.build();
#Override
public void onBindViewHolder(#NonNull AdapterClass.myViewHolder holder, int position) {
holder.description.setText(dataList.get(position).getNotes());
holder.name.setText(dataList.get(position).getStaff_name());
holder.money.setText(String.valueOf(dataList.get(position).getMoney()));
holder.material.setText(dataList.get(position).getMaterial());
holder.size.setText(dataList.get(position).getSize());
holder.colour.setText(dataList.get(position).getColour());
holder.type.setText(dataList.get(position).getTypes());
holder.number.setText(String.valueOf(dataList.get(position).getNumber()));
holder.main_mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateInfo();
}
});
}
#Override
public int getItemCount() {
return dataList.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
View main_mView;
TextView name, number, money, material, size, colour, description, type;
public myViewHolder(#NonNull View itemView) {
super(itemView);
main_mView = itemView;
description = itemView.findViewById(R.id.notes);
name = itemView.findViewById(R.id.staff_name);
money = itemView.findViewById(R.id.money);
number = itemView.findViewById(R.id.number);
colour = itemView.findViewById(R.id.colour);
material = itemView.findViewById(R.id.material);
size = itemView.findViewById(R.id.size);
type = itemView.findViewById(R.id.types);
}
}
}
}
The problem is shown
inputData data = snap.getValue(inputData.class);
whenever new expense data comes in add it to main expense data list and notify adapter.
expenseArrayList.add(new Data(new_item, new_notes, new_amount, new_date));
if (adapter == null) {
expense_recyclerView.setAdapter(adapter);
} else{
adapter.notifyItemInserted(expense_data_list.size()+1)
}
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 am creating an application for School Students so that they do not miss their huge BOOKS. In this project, the student clicks “RecylerView”, immediately downloads the book “Pdf” and saves it to external storage. "like whatsapp" without database
At the moment, I have a problem in that it only sees the file, but does not save!
I am using AsyscTask "My PDF Viewer" activity which bottom
please help!!!
My Main Activity
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.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
> public class MainActivity extends AppCompatActivity {
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_about_card_show);
RelativeLayout relativeLayout = findViewById(R.id.rl);
relativeLayout.startAnimation(animation);
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//adding some items to our list
productList.add(
new Product(
1,
"TEst 11111 \n",
60000,
R.drawable.android,
"link1"
));
productList.add(
new Product(
1,
" More types, Methods, Conditionals \n",
60000,
R.drawable.android,
"link2"
));
productList.add(
new Product(
1,
"Loops, Arrays ",
60000,
R.drawable.android,
"lin3"
));
productList.add(
new Product(
1,
"Strings",
60000,
R.drawable.android,
"https://firebasestorage.googleapis.com/v0/b/firepdf-4c1d6.appspot.com/o/2.intro.pdf?alt=media&token=75731b04-c1e7-42c4-b988-e50a8f7e5f6b "
));
//creating recyclerview adapter
ProductAdapter adapter = new ProductAdapter(this, productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
> public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
//this context we will use to inflate the layout
private Context mCtx;
//we are storing all the products in a list
private List<Product> productList;
//getting the context and product list with constructor
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, final int position) {
//getting the product of the specified position
final Product product = productList.get(position);
//binding the data with the viewholder views
holder.textViewTitle.setText(product.getTitle());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), pdf.class);
i.putExtra("title",productList.get(position).getTitle());
i.putExtra("product",productList.get(position).getTitle());
i.putExtra("link",productList.get(position).getLink());
mCtx.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
ImageView imageView;
CardView cardView;
public ProductViewHolder(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);// card intial
textViewTitle = itemView.findViewById(R.id.textViewTitle);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
My Pdf Viewer
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class pdf extends AppCompatActivity {
String link="",productList="",product="";
PDFView pdfView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
product =getIntent().getStringExtra("title");
productList=getIntent().getStringExtra("productList");
link=getIntent().getStringExtra("link");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(productList);
pdfView=findViewById(R.id.pdfv);
//pdfView.fromAsset(link).load();
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(pdf.this);
builder.setTitle("NoInternet Connection Alert")
.setMessage("GO to Setting ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(pdf.this,"Go Back TO HomePage!",Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
link = getIntent().getStringExtra("link");
}
new pdf.RetrievePDFStream().execute(link);
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
class RetrievePDFStream extends AsyncTask<String, Void, InputStream> {
ProgressDialog progressDialog;
protected void onPreExecute()
{
progressDialog = new ProgressDialog(pdf.this);
progressDialog.setTitle("getting the book content...");
progressDialog.setMessage("Please wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL urlx = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
progressDialog.dismiss();
}
}
#Override public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)//means home default hai kya yesok
{
onBackPressed();
return true;
}
return false;
}
}
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.