how to get values from sqlite in view holder - java

product Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder>{
private Context context;
private List<Product> listProducts;
private SqliteDatabase mDatabase;
public ProductAdapter(Context context, List<Product> listProducts) {
this.context = context;
this.listProducts = listProducts;
mDatabase = new SqliteDatabase(context);
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_list_layout, parent, false);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
final Product singleProduct = listProducts.get(position);
holder.name.setText(singleProduct.getName());
// holder.quantity.setText(singleProduct.getQuantity());
//when i call quantity(the ABOVE value) the application crashes and when i call only name the field the values gets displayed
holder.editProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTaskDialog(singleProduct);
}
});
holder.deleteProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.deleteProduct(singleProduct.getId());
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
});
}
#Override
public int getItemCount() {
return listProducts.size();
}
private void editTaskDialog(final Product product){
LayoutInflater inflater = LayoutInflater.from(context);
View subView = inflater.inflate(R.layout.add_product_layout, null);
final EditText nameField = (EditText)subView.findViewById(R.id.enter_name);
final EditText quantityField = (EditText)subView.findViewById(R.id.enter_quantity);
if(product != null){
nameField.setText(product.getName());
quantityField.setText(String.valueOf(product.getQuantity()));
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit product");
builder.setView(subView);
builder.create();
builder.setPositiveButton("EDIT PRODUCT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String name = nameField.getText().toString();
final String quantityStr = quantityField.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(quantityStr))
{
Toast.makeText(context, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
}
else
{
final int quantity = Integer.parseInt(quantityStr);
if(quantity<=0)
{
Toast.makeText(context,"input is less than or equal to zero",Toast.LENGTH_LONG).show();
}
else {
mDatabase.updateProduct(new Product(product.getId(), name, quantity));
//refresh the activity
((Activity)context).finish();
context.startActivity(((Activity)context).getIntent());
}
}
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Task cancelled", Toast.LENGTH_LONG).show();
}
});
builder.show();
}
}
product viewHolder
public class ProductViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView quantity;
public ImageView deleteProduct;
public ImageView editProduct;
public ProductViewHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.product_name);
deleteProduct = (ImageView)itemView.findViewById(R.id.delete_product);
editProduct = (ImageView)itemView.findViewById(R.id.edit_product);
quantity=(TextView)itemView.findViewById(R.id.product_name2);
}
}
Now the issue here is when is use holder.quantity.setText(singleProduct.getQuantity()) the application crashes.
I also wanted to add date picker dialog and want to display it in the recycler view so for date the code is same like holder.object.setText or something else and can we use a form for alert dialog like
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_dark);
dialog.setCancelable(true);
I have created the database file but the issue is mainly related to recycler view contents and if i wanted multiple holder is it possible to get the contents?

getQuantity() returns a int. So, Android is trying to search for a resource with id == getQuantity() leading to the crash (since you probably any resource with that id.
In other words, you are invoking TextView.setText(int resourceId) and not TextView.setText(String text)).
To fix, change this:
holder.quantity.setText(singleProduct.getQuantity());
To this:
holder.quantity.setText(String.valueOf(singleProduct.getQuantity()));

Related

How can I fix Recyclerview item deletion display error

I have a recyclerview. There are city names in the recyclerview and when I long click, I want to delete it from the recyclerview. I wrote some code in adapter class. When I click on the city names, I can delete them, but when I view the recyclerview again, the city names I deleted appear again. How can I fix this ?
My adapter class
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
ArrayList<City> arrayList;
Context context;
public Adapter(ArrayList<City> arrayList ,Context context ){
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerviewRowBinding recyclerviewRowBinding = RecyclerviewRowBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
return new MyViewHolder(recyclerviewRowBinding);
}
#Override
public void onBindViewHolder(#NonNull Adapter.MyViewHolder holder, int position) {
holder.binding.MytxtCities.setText(arrayList.get(position).cityName);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.warningicon);
builder.setMessage("Are you sure that you want to delete "+arrayList.get(position).cityName);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,arrayList.size());
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
return true;
}
});
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(holder.itemView.getContext(),MainActivity.class);
intent.putExtra("citId",arrayList.get(position).id);
holder.itemView.getContext().startActivity(intent);
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView Mytxt_cities;
private RecyclerviewRowBinding binding;
public MyViewHolder(#NonNull RecyclerviewRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
Mytxt_cities = itemView.findViewById(R.id.Mytxt_cities);
}
}
}
My recyclerview class is cities class
public class cities extends AppCompatActivity {
RecyclerView recyclerView ;
ArrayList<City> cityArrayList;
Adapter cityadapter;
ImageView cities_back_icon;
public void init(){
cities_back_icon = findViewById(R.id.Id_cities_back_icon);
cities_back_icon_click_register();
cityArrayList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerview_id);
SQLGet_Data();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cities);
init();
}
private void cities_back_icon_click_register(){
cities_back_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(cities.this, MainActivity.class);
startActivity(intent);
}
});
}
private void SQLGet_Data(){
try {
SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("City",MODE_PRIVATE,null);
Cursor cursor = sqLiteDatabase.rawQuery("SELECT*FROM city",null);
int idIx = cursor.getColumnIndex("id");
int nameIx = cursor.getColumnIndex("cityname");
while(cursor.moveToNext()){
String cityname = cursor.getString(nameIx);
int id = cursor.getInt(idIx);
City city = new City(cityname,id);
cityArrayList.add(city);
}
cityadapter.notifyDataSetChanged();
cursor.close();
}
catch (Exception e ){
e.printStackTrace();
}
/*---------------------- set recyclerview-----------------------------*/
recyclerView.setLayoutManager(new LinearLayoutManager(cities.this));
cityadapter = new Adapter(cityArrayList,this);
recyclerView.setAdapter(cityadapter);
/*--------------------------We drew a line between the data in the recyclerview------------------------------------*/
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.custom_divider);
dividerItemDecoration.setDrawable(drawable);
recyclerView.addItemDecoration(dividerItemDecoration);
}
}
The problem is that you are only deleting the cities from your ArrayList that is inside your adapter. But those cities still remain in your SQL database. Then when you restart the Activity your ArrayList will be created with the data of your SQL database, where those deleted cities still exist.
To delete cities consistently you need to delete the cities not only in your adapter but also in your SQL database.

Recycler view show updated list only after launching activity once again

I have populated recyclerview from sqlite .when clicking delete button, row will delete from sqlite and when click on edit button value updated from sqlite but recyclerview not showing updated list after delete or edit. Recycler view show updated list only after launching activity once again. My question is how to update the recycler view soon after deleting or updating an item from the recylcerview without refresh.
Fragment code where i use recyclerview:
List<Product> productList = new ArrayList<>();
RecyclerView recyclerView;
SQLiteDatabase mDatabase;
public static ProductAdapter adapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
saveViewModel = ViewModelProviders.of(this).get(SaveViewModel.class);
View root = inflater.inflate(R.layout.fragment_save, container, false);
/* final TextView textView = root.findViewById(R.id.text_gallery);*/
recyclerView = root.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDatabase = getActivity().openOrCreateDatabase(Add_Activity.DATABASE_NAME, MODE_PRIVATE, null);
showDataFromDatabase();
saveViewModel.getText().observe(getActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
/* textView.setText(s);*/
}
});
return root;
}
private void showDataFromDatabase() {
//we used rawQuery(sql, selectionargs) for fetching all the fields
Cursor cursorproduct = mDatabase.rawQuery(" SELECT * FROM items", null);
//if the cursor has some data
if (cursorproduct.moveToFirst()) {
//looping through all the records
do {
//pushing each record in the field list
productList.add(new Product(
cursorproduct.getInt(0),
cursorproduct.getString(1),
cursorproduct.getString(2),
cursorproduct.getString(3),
cursorproduct.getString(4),
cursorproduct.getString(5),
));
} while (cursorproduct.moveToNext());
}
if (productList.isEmpty()) {
Toast.makeText(getActivity(), "No items Found in database", Toast.LENGTH_SHORT).show();
}
//closing the cursor
cursorproduct.close();
//creating the adapter object
adapter = new ProductAdapter(getActivity(), R.layout.show_field_items, productList, mDatabase);
//adding the adapter to listview
recyclerView.setAdapter(adapter);
adapter.reloadEmployeesFromDatabase(); //this method is in prdouctadapter
adapter.notifyDataSetChanged();
}
}
View model class:
public class Product {
private int id;
private String date;
private String category;
private String fsub_category;
private String fname;
private String fphone;
public Product(int id, String date, String category, String fsub_category, String fname, String fphone) {
this.id = id;
this.date = date;
this.category = category;
this.fsub_category =fsub_category;
this.fname = fname;
this.fphone = fphone;
}
public int getId() {
return id;
}
public String getFname() {
return fname;
}
public String getFcategory() {
return category;
}
public String getFsub_category() {
return fsub_category;
}
public String getFphone() {
return fphone;
}
public String getFdate() {
return date;
}
}
Product Adapter class:
public ProductAdapter(Context mCtx, int custom_list_item, List<Product> productList, SQLiteDatabase mDatabase) {
this.mCtx = mCtx;
this.custom_list_item = custom_list_item;
this.mDatabase = mDatabase;
this.productList = productList;
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.show_field_items, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
final Product product = productList.get(position);
//binding the data with the viewholder views
holder.Category.setText(product.getFcategory());
holder.Date.setText(product.getFdate());
holder.Area.setText(product.getFcategoty());
holder.editbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateEmployee(product);
}
});
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String sql = "DELETE FROM items WHERE id = ?";
mDatabase.execSQL(sql, new Integer[]{product.getId()});
Snackbar.make(view, "Deleted" + product.getFcategory(), Snackbar.LENGTH_SHORT).show();
Toast.makeText(mCtx, "Deleted successfully!", Toast.LENGTH_SHORT).show();
reloadEmployeesFromDatabase(); //Reload List
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
public void reloadEmployeesFromDatabase() {
Cursor cursorproduct1 = mDatabase.rawQuery("SELECT * FROM items", null);
if (cursorproduct1.moveToFirst()) {
productList.clear();
do {
productList.add(new Product(
cursorproduct1.getInt(0),
cursorproduct1.getString(1),
cursorproduct1.getString(2),
cursorproduct1.getString(3),
cursorproduct1.getString(4),
cursorproduct1.getString(5)
));
} while (cursorproduct1.moveToNext());
}
cursorproduct1.close();
notifyDataSetChanged();
}
private void updateEmployee(final Product product) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.update_form, null);
builder.setView(view);
category = view.findViewById(R.id.spiner);
final EditText editsubcat= view.findViewById(R.id.editsubcategory);
final EditText editFname = view.findViewById(R.id.editFarmerName);
final EditText editphno = view.findViewById(R.id.editFarmerphno);
String cat = category.getSelectedItem().toString().trim();
editsubcat.setText(product.getFsub_category());
editFname.setText(product.getFname());
editphno.setText(product.getFphone());
final AlertDialog dialog = builder.create();
dialog.show();
// CREATE METHOD FOR EDIT THE FORM
view.findViewById(R.id.buttonUpdateEmployee).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Crop = category.getSelectedItem().toString().trim();
String Sub_Category = editsubcat.getText().toString().trim();
String Farmer_Name = editFname.getText().toString().trim();
String Farmer_phone_No = editphno.getText().toString().trim();
/* if (Crop.isEmpty()) {
editTextName.setError("Name can't be blank");
editTextName.requestFocus();
return;
}
if (Sub_Category.isEmpty()) {
editUsername.setError("Salary can't be blank");
editUsername.requestFocus();
return;
}//Name, Email, UserName, PhoneNo*/
String sql = "UPDATE items \n" +
"SET Category = ?, \n" +
"Sub_Category = ?,\n" +
"Farmer_Name = ?,\n" +
"Farmer_phone_No= ? \n" +
"WHERE id = ?;\n";
mDatabase.execSQL(sql, new String[]{Crop,Sub_Category, Farmer_Name, Farmer_phone_No, String.valueOf(product.getId())});
Toast.makeText(mCtx, "data Updated", Toast.LENGTH_SHORT).show();
dialog.dismiss();
List<Product> pro = productList;
productList.clear();
productList.addAll(pro);
}
});
notifyDataSetChanged();
/* notifyItemRangeChanged(0, productList.size());*/
}
/* public void updateList(List<Product> itemList)
{
this.productList.clear();
this.productList.addAll(itemList);
notifyDataSetChanged();
}*/
/* private void updateList(List<Product> products) {
this.productList.clear();
this.productList.addAll(products);
productAdapter.notifyDataSetChanged();
}
*/
#Override
public int getItemCount() {
return productList.size();
}
public void setData(List<Product> items) {
productList = items;
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView Date, Category, Area;
Button editbtn, deletebtn;
public ProductViewHolder(View itemView) {
super(itemView);
Category = itemView.findViewById(R.id.f_category);
Date = itemView.findViewById(R.id.f_date);
Area = itemView.findViewById(R.id.f_area);
}
}
}
After delete for update you need to update productList as well like :
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String sql = "DELETE FROM items WHERE id = ?";
mDatabase.execSQL(sql, new Integer[]{product.getId()});
Snackbar.make(view, "Deleted" + product.getFcategory(), Snackbar.LENGTH_SHORT).show();
Toast.makeText(mCtx, "Deleted successfully!", Toast.LENGTH_SHORT).show();
//reloadEmployeesFromDatabase(); //Reload List
productList.remove(product); //like that after notify adapter
notifyDataSetchanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
in update you need to update product obj in productList :
String Crop = category.getSelectedItem().toString().trim();
String Sub_Category = editsubcat.getText().toString().trim();
String Farmer_Name = editFname.getText().toString().trim();
String Farmer_phone_No = editphno.getText().toString().trim();
// afer updating in sqlite db and also need to create setter in model
productList.get(position).setFcategory(Crop);
..........
//after pudating all feild like that just notify data set
notifyDataSetchanged();

Android RecyclerView item selection issue

I am designing a live quiz app that fetches data from server and question are displayed in a RecyclerView that contains a question and four options. Now when I select one option for a given question, it is selected properly but at the same time, the corresponding option for other question is selected automatically.
Screenshot of the item selection issue is the following.
Here is the adapter class of my RecyclerView
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder>{
private int mItemSelected=-1;
private List<DmLiveQuiz> questionList;
DmLiveQuiz questionsList; // DmLiveQuiz questionsList
private Context context; //context
final DataHolder dh=new DataHolder();
public List<Integer> myResponse= new ArrayList<Integer>();
public int qno;
public String myQno;
public int afterSub;
DataHolder dataHolder;
public LiveTestAdapter(List<DmLiveQuiz> questionList, Context context) {
this.questionList = questionList;
this.context = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.live_quiz_display_format,parent,false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
questionsList=questionList.get(holder.getAdapterPosition());
holder.tvQNo.setText(questionsList.getQuestionId()+"");
holder.tvquestion.getLayoutParams().width= LinearLayout.LayoutParams.WRAP_CONTENT;
holder.tvquestion.setText(questionsList.getQuestion());
holder.optA.setText(questionsList.getOptA());
holder.optB.setText(questionsList.getOptB());
holder.optC.setText(questionsList.getOptC());
holder.optD.setText(questionsList.getOptD());
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_border);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_border);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_border);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
}
});
}
#Override
public int getItemCount() {
return questionList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder{
TextView tvquestion, tvClear,tvQNo;
Button optA,optB,optC,optD;
public CustomViewHolder(View itemView) {
super(itemView);
tvQNo=(TextView)itemView.findViewById(R.id.tvLiveQuizQuestionNo);
tvquestion=(TextView)itemView.findViewById(R.id.tvLiveQuizQuestion);
optA=(Button)itemView.findViewById(R.id.buttonOptionA);
optB=(Button)itemView.findViewById(R.id.buttonOptionB);
optC=(Button)itemView.findViewById(R.id.buttonOptionC);
optD=(Button)itemView.findViewById(R.id.buttonOptionD);
tvClear=(TextView)itemView.findViewById(R.id.tvClearSelection);
}
}
}
The only problem I am facing is the auto selection of unanswered options.
Please help me out in selecting the selected option only not the ones which are not selected. Thanks in advance.
The views will be reused in your RecyclerView and hence you are having such a problem. In your case, you might consider having another array which stores the answers of your quizzes and can keep track of every item in your RecyclerView.
I would like to suggest modifying your adapter like the following. I have commented in some places. Hope that helps you to understand your problem.
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder> {
private int mItemSelected = -1;
private List<DmLiveQuiz> questionList;
private int[] answerList; // Get a list of your answers here.
private DmLiveQuiz questionsList;
private Context context;
final DataHolder dh = new DataHolder();
public List<Integer> myResponse = new ArrayList<Integer>();
public int qno;
public String myQno;
public int afterSub;
DataHolder dataHolder;
public LiveTestAdapter(List<DmLiveQuiz> questionList, Context context) {
this.questionList = questionList;
this.context = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_quiz_display_format, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
questionsList = questionList.get(holder.getAdapterPosition());
holder.tvQNo.setText(questionsList.getQuestionId() + "");
holder.tvquestion.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
holder.tvquestion.setText(questionsList.getQuestion());
holder.optA.setText(questionsList.getOptA());
holder.optB.setText(questionsList.getOptB());
holder.optC.setText(questionsList.getOptC());
holder.optD.setText(questionsList.getOptD());
// Now you need to modify the backgrounds of your option buttons like the following.
if (answerList[position] == 1) holder.optA.setBackgroundResource(R.drawable.button_border);
else holder.optA.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 2) holder.optB.setBackgroundResource(R.drawable.button_border);
else holder.optB.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 3) holder.optC.setBackgroundResource(R.drawable.button_border);
else holder.optC.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 4) holder.optD.setBackgroundResource(R.drawable.button_border);
else holder.optD.setBackgroundResource(R.drawable.button_question_style);
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
answerList[position] = 1; // Selected first option which is A
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optB.setBackgroundResource(R.drawable.button_border);
answerList[position] = 2; // Selected second option which is B
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optC.setBackgroundResource(R.drawable.button_border);
answerList[position] = 3; // Selected third option which is C
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optD.setBackgroundResource(R.drawable.button_border);
answerList[position] = 4; // Selected fourth option which is D
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
answerList[position] = 0; // Clear the value in the answerList
}
});
}
// Use this function to set the question list in the adapter
public void setQuestionList(List<DmLiveQuiz> questionList) {
this.questionList = questionList;
this.answerList = new int[questionList.size()]; // This initializes the answer list having the same size as the question list
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return questionList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
TextView tvquestion, tvClear, tvQNo;
Button optA, optB, optC, optD;
public CustomViewHolder(View itemView) {
super(itemView);
tvQNo = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestionNo);
tvquestion = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestion);
optA = (Button) itemView.findViewById(R.id.buttonOptionA);
optB = (Button) itemView.findViewById(R.id.buttonOptionB);
optC = (Button) itemView.findViewById(R.id.buttonOptionC);
optD = (Button) itemView.findViewById(R.id.buttonOptionD);
tvClear = (TextView) itemView.findViewById(R.id.tvClearSelection);
}
}
}
Update - Please check that I have added setQuestionList function in the adapter. Please use this function to set your question list. Because, I think while initializing your adapter, the question list which is being passed is having a size of zero.

Alert Dialog.Builder(??)

I am trying to make an alertdialog for when the user presses the cardview to delete it. This is in my ProductAdapter code
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(????);
what would I put in the brackets where I have the ????
I have looked at examples on this site and the ones I have seen have used ActivityName.this inside the brackets. However this code is in the ProductAdapter code and I can't use ProductAdapter.this. (my main activity is called create.java fyi)
So what would go in there? Thanks
update
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
//this context we will use to inflate the layout
private Context mCtx;
private SearchableSpinner spinner;
//we are storing all the products in a list
private List<Product> productList;
private Activity create;
public ProductAdapter(Activity activity){
create = activity;
}
//getting the context and product list with constructor
public ProductAdapter(Activity activity, List<Product> productList) {
this.mCtx = mCtx;
create = activity;
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
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(mCtx, R.layout.item_spinner_layout,
Product.getSpinnerItemsList());
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(spinnerArrayAdapter);
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
mSpinnerSelectedItem.put(position, mPosition);
TextView mTextView = view.findViewById(R.id.mSpinnerText);
Toast.makeText(mCtx, "Selected Item: " + mTextView.getText().toString(), Toast.LENGTH_LONG).show();
Log.e("***************", "Selected Item: " + mTextView.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//binding the data with the viewholder views
if (mSpinnerSelectedItem.containsKey(position)) {
holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
}
holder.getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
productList.remove(position);
notifyItemRemoved(position);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
SearchableSpinner spinner;
EditText editText;
TextView textView5;
CheckBox checkBox;
LinearLayout linearLayout;
View rootView;
public ProductViewHolder(View itemView) {
super(itemView);
spinner = itemView.findViewById(R.id.spinner);
editText = itemView.findViewById(R.id.editText);
textView5 = itemView.findViewById(R.id.textView5);
checkBox = itemView.findViewById(R.id.checkBox);
rootView = itemView.findViewById(R.id.linearLayout);
}
public View getView() {
return rootView;
}
}
}
Although AlertDialog.Builder() accepts a Context reference in its argument, it is better to pass an Activity reference to it, not applicationContext because of potential theme and window attachment problems. So, pass an Activity reference to your adapter and use it to build an AlertDialog.
public class ProductAdapter extends SomeAdapter {
private Activity create;
public ProductAdapter(Activity activity, List<Product> productList) {
create = activity;
this.productList = productList;
}
private void showAlertDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// ...
alertDialogBuilder.create().show();
}
}
You must pass context of ther activity there, check this link for more understanding.
Only pass the context of calling activity to your ProductAdapter class and use this

AlertDialog in recycler view on button click

My application crash when i hit the btnSubmit. and give this Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference.
code Written Below;
public class RecycleAdoptor extends RecyclerView.Adapter{
Context cont;
DataSource ds;
Double lon = 0.0;
Double lat = 0.0;
RecycleAdoptor(Context paramContext)
{
this.cont = paramContext;
}
private List<Employee> mDocs;
#Override
public RecycleAdoptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("jarvis", "RecylerAdoptor");
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.activity_list_items, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public RecycleAdoptor(List<Employee> myDataset, Context context) {
mDocs = myDataset;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final Employee emp = mDocs.get(position);
holder.empID.setText(emp.getID());
holder.empName.setText(emp.getEmpName());
holder.empDesignation.setText(emp.getDesignation());
holder.empSpeciality.setText(emp.getSpeciality());
holder.empAddress.setText(emp.getAddress());
}
#Override
public int getItemCount() {
return mDocs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView empID;
public TextView docID;
public TextView empName;
public TextView empAddress;
public TextView empDesignation;
public TextView empSpeciality;
public TextView empStatus;
public Button btnSaveAttd;
public Spinner spinner;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
empID = (TextView) v.findViewById(R.id.emp_id);
empName = (TextView) v.findViewById(R.id.empName);
empDesignation = (TextView) v.findViewById(R.id.empDesignation);
empSpeciality = (TextView) v.findViewById(R.id.empSpecialist);
empAddress = (TextView) v.findViewById(R.id.empAddress);
spinner = (Spinner) v.findViewById(R.id.spinner1);
btnSaveAttd = (Button) v.findViewById(R.id.btnSaveAttd);
btnSaveAttd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Date currentTime = Calendar.getInstance().getTime();
double lon = ProfileActivity.Lon;
double lat = ProfileActivity.Lat;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
cont);
alertDialog.setTitle("Leave application?");
alertDialog.setMessage("Are you sure you want to leave the application?");
alertDialog.setIcon(R.drawable.ic_menu_camera);
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
});
}
}
}
Sorry For bad English.but Need serious help...
I upload my answer. and its work Fine and i mention my prob where i did wrong.
Context cont;
DataSource ds;
Double lon = 0.0;
Double lat = 0.0;
RecycleAdoptor(Context paramContext)
{
this.cont = paramContext;
}
private List<Employee> mDocs;
#Override
public RecycleAdoptor.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("jarvis", "RecylerAdoptor");
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.activity_list_items, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public RecycleAdoptor(List<Employee> myDataset, Context context) {
mDocs = myDataset;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final Employee emp = mDocs.get(position);
holder.empID.setText(emp.getID());
holder.empName.setText(emp.getEmpName());
holder.empDesignation.setText(emp.getDesignation());
holder.empSpeciality.setText(emp.getSpeciality());
holder.empAddress.setText(emp.getAddress());
}
#Override
public int getItemCount() {
return mDocs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView empID;
public TextView docID;
public TextView empName;
public TextView empAddress;
public TextView empDesignation;
public TextView empSpeciality;
public TextView empStatus;
public Button btnSaveAttd;
public Spinner spinner;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
empID = (TextView) v.findViewById(R.id.emp_id);
empName = (TextView) v.findViewById(R.id.empName);
empDesignation = (TextView) v.findViewById(R.id.empDesignation);
empSpeciality = (TextView) v.findViewById(R.id.empSpecialist);
empAddress = (TextView) v.findViewById(R.id.empAddress);
spinner = (Spinner) v.findViewById(R.id.spinner1);
btnSaveAttd = (Button) v.findViewById(R.id.btnSaveAttd);
btnSaveAttd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Date currentTime = Calendar.getInstance().getTime();
double lon = ProfileActivity.Lon;
double lat = ProfileActivity.Lat;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());//Here I have to use v.getContext() istead of just cont.
alertDialog.setTitle("Leave application?");
alertDialog.setMessage("Are you sure you want to leave the application?");
alertDialog.setIcon(R.drawable.ic_menu_camera);
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
});
}
}

Categories

Resources