I make an application, with CRUD function in Android using Room Database.
When i checked the checkbox like this, Error Pictures 1 i want that application show textview & edittext. But, after i press next button, it won't show textview & edittext based on checked in the checkbox Error Pictures 2 or textview & edittext showed up but that's not based by checkbox isChecked
This is the code :
AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterTargetIbadah extends RecyclerView.Adapter<AdapterTargetIbadah.ViewHolder>{
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterTargetIbadah(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_target;
EditText et_Target;
ViewHolder(View itemView) {
super(itemView);
tv_target = itemView.findViewById(R.id.tv_target);
et_Target = itemView.findViewById(R.id.et_Target);
}
}
#Override
public AdapterTargetIbadah.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_target, parent, false);
AdapterTargetIbadah.ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull AdapterTargetIbadah.ViewHolder holder, int position) {
Ibadah iba = targetIbadah.get(position);
if (iba.getTargetIbadah()!=null) {
holder.tv_target.setText(iba.getTargetIbadah());
iba.setEtTarget(holder.et_Target.getText().toString());
} else {
targetIbadah.remove(position);
}
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
AdapterCheckboxTarget.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterCheckboxTarget extends RecyclerView.Adapter<AdapterCheckboxTarget.ViewHolder> {
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterCheckboxTarget(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckBox cbTarget;
ViewHolder(View itemView) {
super(itemView);
cbTarget = itemView.findViewById(R.id.cbTarget);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_targethome, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final String name = targetIbadah.get(position).getNamaIbadah();
holder.cbTarget.setText(name);
holder.cbTarget.setChecked(targetIbadah.get(position).getStatus());
holder.cbTarget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.cbTarget.isChecked()) {
targetIbadah.get(position).setStatus(true);
targetIbadah.get(position).setTargetIbadah(targetIbadah.get(position).getNamaIbadah());
Toast.makeText(context, "checklist", Toast.LENGTH_SHORT).show();
} else {
targetIbadah.get(position).setStatus(false);
Toast.makeText(context, "unchecklist", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
TargetHome.java ==> Activity using AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.adapter.AdapterTargetIbadah;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class TargetHome extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvTarget;
Button btSimpan;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_ibadah);
setTitle("Target Ibadah");
btSimpan = (Button)findViewById(R.id.btSimpanTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvTarget = findViewById(R.id.rvTar);
rvTarget.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvTarget.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterTargetIbadah(targetIbadah, this);
rvTarget.setAdapter(adapter);
Ibadah ib = new Ibadah();
if (ib.getTargetIbadah()!=null) {
ib.setTvTarget(ib.getTargetIbadah());
ib.setEtTarget("");
db.ibadahDAO().insertCapai(ib);
}
btSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(MainActivity.getActIntent(TargetHome.this));
}
});
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, TargetHome.class);
}
}
CheckboxTarget.java ==> Activity using AdapterCheckboxTarget
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.adapter.AdapterCatatIbadah;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class CheckboxTarget extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvCb;
Button btNext;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_home);
setTitle("Target Ibadah");
btNext = (Button) findViewById(R.id.btNextTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvCb = findViewById(R.id.rvTarHome);
rvCb.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvCb.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterCheckboxTarget(targetIbadah, this);
rvCb.setAdapter(adapter);
final Ibadah ibadah = (Ibadah) getIntent().getSerializableExtra("data");
if (ibadah != null) {
Ibadah ib = new Ibadah();
ib.setStatus(ib.status);
db.ibadahDAO().insertTarget(ib);
}
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, CheckboxTarget.class);
}
}
Ibadah.java ==> Model
package skripsi.com.ggr.managementibadah.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
#Entity(tableName = "tibadah")
public class Ibadah implements Serializable {
#PrimaryKey(autoGenerate = true)
public int idIbadah;
#ColumnInfo(name = "nama_ibadah")
public String namaIbadah;
#ColumnInfo(name = "deskripsi_ibadah")
public String deskripsiIbadah;
#ColumnInfo(name = "target_ibadah")
public String targetIbadah;
#ColumnInfo(name = "tv_target")
public String tvTarget;
#ColumnInfo(name = "et_target")
public String etTarget;
#ColumnInfo(name = "et_capaian")
public String etCapaian;
#ColumnInfo(name = "status")
public boolean status;
public String getTvTarget() {
return tvTarget;
}
public void setTvTarget(String tvTarget) {
this.tvTarget = tvTarget;
}
public String getTargetIbadah() {
return targetIbadah;
}
public void setTargetIbadah(String targetIbadah) {
this.targetIbadah = targetIbadah;
}
public String getEtTarget() {
return etTarget;
}
public void setEtTarget(String etTarget) {
this.etTarget = etTarget;
}
public String getEtCapaian() {
return etCapaian;
}
public void setEtCapaian(String etCapaian) {
this.etCapaian = etCapaian;
}
public String getDeskripsiIbadah() {
return deskripsiIbadah;
}
public void setDeskripsiIbadah(String deskripsiIbadah) {
this.deskripsiIbadah = deskripsiIbadah;
}
public int getIdIbadah() {
return idIbadah;
}
public void setIdIbadah(int idIbadah) {
this.idIbadah = idIbadah;
}
public String getNamaIbadah() {
return namaIbadah;
}
public void setNamaIbadah(String namaIbadah) {
this.namaIbadah = namaIbadah;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
I hope, you can help me. Thank you very much & sorry for my bad english.
First you have to set your TextView and EditText invisible in your XML, by adding android:visibility="invisible" to the XML of your TextView and EditText.
Then you have to use setVisibility(View.VISIBLE) after you have set the checkbox, like this:
yourcheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
//if checkbox is checked (b == true)
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
if (!b) {
//if checkbox is not checked (b == false)
yourTextView.setVisibility(View.INVISIBLE);
yourEditText.setVisibility(View.INVISIBLE);
}
}
});
If you first want to click a button and then check weather checkbox is checked, add this to your OnClickListenter:
if (yourcheckbox.isChecked) {
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
Related
I'm trying to retrieve array of images from firestore. I uploaded the images to firebase storage and have added the url to firestore. I can see the card of images in the recycler view but the images are not visible. In Logcat, I get the links of the images which redirect to the images saved in firebase storage. I have attached the adapter class.
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class imageAdapter extends RecyclerView.Adapter<imageAdapter.holder>
{
ArrayList<String> imageUrl;
public imageAdapter(ArrayList<String> imageUrl)
{
this.imageUrl = imageUrl;
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_image_item,parent,false);
return new holder(v).linkAdapter(this) ;
}
#Override
public void onBindViewHolder(#NonNull holder holder, int position)
{
Glide.with(holder.imageView.getContext()).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount()
{
return imageUrl.size();
}
class holder extends RecyclerView.ViewHolder
{
ImageButton imageButton;
ImageView imageView;
private imageAdapter imageAdapter;
public holder(#NonNull View itemView)
{
super(itemView);
imageButton=itemView.findViewById(R.id.imageBtn);
imageView=itemView.findViewById(R.id.imageView);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
imageAdapter.imageUrl.remove(getAdapterPosition());
imageAdapter.notifyItemRemoved(getAdapterPosition());
}
});
}
public holder linkAdapter(imageAdapter imageAdapter)
{
this.imageAdapter = imageAdapter;
return this;
}
}
}
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.darsh.multipleimageselect.activities.AlbumSelectActivity;
import com.darsh.multipleimageselect.helpers.Constants;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.button.MaterialButton;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.marquedo.marquedo.ui.Prod_n_Cat.Product.AboutModelClass;
import com.marquedo.marquedo.ui.Prod_n_Cat.Product.ProductListAdapter1;
import com.marquedo.marquedo.ui.Prod_n_Cat.Product.ProductModelClass;
import java.util.ArrayList;
import java.util.List;
public class update_product extends AppCompatActivity
{
private String position;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private EditText category, name, details;
private RecyclerView recyclerView;
private AboutModelClass aboutModelClass;
private MaterialButton add_images_button;
private imageAdapter imageAdapter;
private ActivityResultLauncher<Intent> getResult;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_product);
Intent preview = new Intent(this, preview_product.class);
Button preview_prod = findViewById(R.id.show_preview);
preview_prod.setOnClickListener(view ->
{
startActivity(preview);
});
category = findViewById(R.id.prodCategory);
name = findViewById(R.id.productName);
details = findViewById(R.id.prodDetails);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(null);
Bundle intent = getIntent().getExtras();
position = intent.get("key").toString();
//Getting data from firestore and displaying it on the fields
db.collection("Store").document("TFTVHvZaHOIxjYLnHvwc").collection("products").document(position).collection("about").document("product_id").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(#NonNull DocumentSnapshot documentSnapshot)
{
aboutModelClass = documentSnapshot.toObject(AboutModelClass.class);
String Category = aboutModelClass.getCategory();
String Name = aboutModelClass.getName();
String Details = aboutModelClass.getDetails();
ArrayList<String> Urls = (ArrayList<String>) documentSnapshot.get("Images");
Log.i("showlist", Urls.toString());
imageAdapter = new imageAdapter(Urls);
recyclerView.setAdapter(imageAdapter2);
category.setText(Category);
name.setText(Name);
details.setText(Details);
}
});
}
}
ModelClass.java
import java.util.List;
public class AboutModelClass
{
String Category, Details, Name;
List<String> urls;
public AboutModelClass()
{
}
public AboutModelClass(String category, String details, String name, List<String> urls) {
Category = category;
Details = details;
Name = name;
this.urls = urls;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getDetails() {
return Details;
}
public void setDetails(String details) {
Details = details;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public List<String> getUrls() {
return urls;
}
public void setUrls(List<String> urls) {
this.urls = urls;
}
}
im trying to retrieve data from firebase to detail activity. On the listview, it show perfectly. But when i click, the detail activity opened but still empty. All it says "W/ClassMapper: No setter/field for url found on class com.example.scheduletask.model.Task". I thought the setter on model task wasn't used, but i don't know... im sorry, i don't understand, i don't know what i missed:( any help is appreciated, thank youuu
TaskActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.scheduletask.adapter.MatkulAdapter;
import com.example.scheduletask.adapter.TaskAdapter;
import com.example.scheduletask.adapter.TaskDetailAdapter;
import com.example.scheduletask.database.FirebaseTaskHelper;
import com.example.scheduletask.model.Matkul;
import com.example.scheduletask.model.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.ValueEventListener;
import java.util.ArrayList;
import java.util.Iterator;
public class TaskActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ListView listViewTask;
FloatingActionButton fabAddTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
listViewTask = findViewById(R.id.tasklist);
showData();
fabAddTask = findViewById(R.id.fab_addtask);
fabAddTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TaskActivity.this, CreateTaskActivity.class);
startActivity(intent);
}
});
listViewTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String subjectTask = ((TextView)view.findViewById(R.id.txt_subjectlisttask)).getTag().toString();
Intent taskDetail = new Intent(TaskActivity.this, TaskDetailActivity.class);
taskDetail.putExtra("subjectTask", subjectTask);
startActivity(taskDetail);
}
});
}
private void showData() {
final ArrayList<String> subjectTask = new ArrayList<>();
final ArrayList<String> taskDueDate = new ArrayList<>();
final ArrayList<String> taskDescription = new ArrayList<>();
final ArrayList<String> imageURL = new ArrayList<>();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterable.iterator();
while (iterator.hasNext()){
Task value = iterator.next().getValue(Task.class);
assert value != null;
subjectTask.add(value.getSubjectTask());
taskDescription.add(value.getTaskDescription());
taskDueDate.add(value.getTaskDueDate());
imageURL.add(value.getImageURL());
((TaskAdapter)listViewTask.getAdapter()).notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
listViewTask.setAdapter(new TaskAdapter(subjectTask, taskDescription, taskDueDate, imageURL, this));
}
#Override
protected void onResume() {
super.onResume();
showData();
}
}
Task.java (this is the model)
package com.example.scheduletask.model;
public class Task {
private String taskDueDate;
public String getTaskDueDate() {
return taskDueDate;
}
public void setTaskDueDate(String taskDueDate) {
this.taskDueDate = taskDueDate;
}
private String subjectTask;
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
private String taskDescription;
private String imageURL;
public String getSubjectTask() {
return subjectTask;
}
public void setSubjectTask(String subjectTask) {
this.subjectTask = subjectTask;
}
}
TaskDetailActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.scheduletask.model.Task;
import com.github.barteksc.pdfviewer.PDFView;
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 com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class TaskDetailActivity extends AppCompatActivity {
EditText edtSubject, edtDueDate, edtDescription;
ImageView filePhoto;
ProgressBar progressBarDetail;
Button btnEdit, btnDelete;
DatabaseReference databaseReference;
private String photoURL, subjectTask;
Button btnViewPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_detail);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
subjectTask = getIntent().getExtras().getString("subjectTask");
progressBarDetail = findViewById(R.id.progressbardetail);
progressBarDetail.setVisibility(View.INVISIBLE);
readData();
findAllViewsID();
}
private void readData() {
progressBarDetail.setVisibility(View.VISIBLE);
Query findQuery = databaseReference.orderByKey().equalTo(subjectTask);
findQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getSnapshot : dataSnapshot.getChildren()){
edtSubject.setText(getSnapshot.child("subjectTask").getValue().toString());
edtDescription.setText(getSnapshot.child("taskDescription").getValue().toString());
edtDueDate.setText(getSnapshot.child("taskDueDate").getValue().toString());
photoURL = getSnapshot.child("imageURL").getValue().toString();
Picasso.get().load(photoURL).fit().into(filePhoto);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressBarDetail.setVisibility(View.INVISIBLE);
}
});
progressBarDetail.setVisibility(View.INVISIBLE);
}
private void findAllViewsID() {
edtSubject = findViewById(R.id.edt_updatetasksubject);
edtDescription = findViewById(R.id.edt_updatetaskdescription);
edtDueDate = findViewById(R.id.edt_updateduedatetime);
filePhoto = findViewById(R.id.iv_taskphotoinput);
btnViewPDF = findViewById(R.id.btn_viewpdf);
btnDelete = findViewById(R.id.btn_deletetask);
btnEdit = findViewById(R.id.btn_edittask);
}
}
TaskAdapter.java
package com.example.scheduletask.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.scheduletask.R;
import com.example.scheduletask.TaskActivity;
import com.example.scheduletask.TaskDetailActivity;
import com.example.scheduletask.model.Task;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class TaskAdapter extends BaseAdapter {
private ArrayList<String> subjectTask;
private ArrayList<String> taskDescription;
private ArrayList<String> taskDueDate;
private ArrayList<String> imageURL;
private AppCompatActivity activity;
public TaskAdapter(ArrayList<String> subjectTask, ArrayList<String> taskDescription, ArrayList<String> taskDueDate, ArrayList<String> imageURL, AppCompatActivity activity) {
this.subjectTask = subjectTask;
this.taskDescription = taskDescription;
this.taskDueDate = taskDueDate;
this.imageURL = imageURL;
this.activity = activity;
}
Context ctx;
ArrayList<Task> tasks;
#Override
public int getCount() {
return subjectTask.size();
}
#Override
public Object getItem(int position) {
return subjectTask.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public TaskAdapter(#NonNull Context ctx, ArrayList<Task> tasks) {
this.ctx = ctx;
this.tasks = tasks;
}
public View getView(int position, View view, ViewGroup parent) {
view = LayoutInflater.from(activity.getApplicationContext())
.inflate(R.layout.list_task, parent, false);
view.findViewById(R.id.txt_subjectlisttask).setTag(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_subjectlisttask)).setText(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_duedatetasklist)).setText(String.valueOf(taskDueDate.get(position)));
return view; }
}
Here is the logcat when i click the task listview
And this is my database
I want to store my data in realm database, then retrieve and show it in a recyclerview. All my code is correct in my point of view but it gives me an error about null pointer exception. Despite my efforts I was unable to solve it.
Main Activty Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Adapter.AdapterClass;
import com.deitel.realmrecyclerviewspinnerpriority.Database.RelmHelper;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
ImageButton btn_ascending,btn_descending;
RecyclerView rv;
Spinner spinner;
TextView text_data;
Button btn_save,btn_view;
ArrayList<String> itemslist;
AdapterClass addapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
text_data=findViewById(R.id.text_data);
btn_save=findViewById(R.id.btn_show);
btn_view=findViewById(R.id.btn_view);
btn_save = findViewById(R.id.btn_show);
rv = findViewById(R.id.recyclerview);
btn_ascending=findViewById(R.id.btn_ascending);
btn_descending=findViewById(R.id.btn_descneding);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
final RelmHelper helper=new RelmHelper(realm);
itemslist=helper.retrievedata();
addapter = new AdapterClass(MainActivity.this,itemslist);
rv.setAdapter(addapter);
spinner = findViewById(R.id.spinner);
final ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
arrayList.add(6);
arrayList.add(7);
arrayList.add(8);
arrayList.add(9);
arrayList.add(10);
arrayList.add(11);
arrayList.add(12);
arrayList.add(13);
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelClass md=new ModelClass();
md.setName(text_name.getText().toString());
md.setDetails(text_details.getText().toString());
/*save data*/
RelmHelper helper=new RelmHelper(realm);
helper.savedata(md);
}
});
}
}
```
MY REALM HELPER CLASS
```
package com.deitel.realmrecyclerviewspinnerpriority.Database;
import android.view.Display;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmResults;
public class RelmHelper {
Realm realm;
public RelmHelper(Realm realm) {
this.realm = realm;
}
public void savedata(final ModelClass modelClass){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ModelClass md=realm.copyToRealm(modelClass);
}
});
}
public ArrayList<String> retrievedata(){
ArrayList<String> modelclassdata=new ArrayList<>();
RealmResults<ModelClass> modelClass=realm.where(ModelClass.class).findAll();
for (ModelClass MD:modelClass){
modelclassdata.add(MD.getName());
modelclassdata.add(MD.getDetails());
// modelclassdata.add(MD.getPriority());
}
return modelclassdata;
}
}
```
Model Class
```
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
public class ModelClass extends RealmObject {
private String name;
private String details;
// private int priority;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
// public int getPriority() {
// return priority;
// }
//
// public void setPriority(int priority) {
// this.priority = priority;
// }
}
```
Adapter Class
```[![enter image description here][1]][1]
package com.deitel.realmrecyclerviewspinnerpriority.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import com.deitel.realmrecyclerviewspinnerpriority.R;
import java.util.ArrayList;
import java.util.List;
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.Viewholder> {
ArrayList<String> modelClassList;
Context context;
public AdapterClass(#NonNull Context context,ArrayList<String> modelClassList){
this.modelClassList=modelClassList;
this.context=context;
}
#NonNull
#Override
public AdapterClass.Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_cardview_layout, viewGroup, false);
Viewholder holder = new Viewholder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull AdapterClass.Viewholder holder, final int position) {
holder.textView_name.setText("Name :" + modelClassList.get(position));
holder.textView_details.setText("Details : " + modelClassList.get(position));
// holder.textView_priority.setText("Priority : " + modelClassList.get(position));
// holder.btn_delete.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// modelClassList.remove(position);
// notifyItemRemoved(position);
// notifyItemRangeChanged(position,modelClassList.size());
// notifyDataSetChanged();
// }
// });
}
#Override
public int getItemCount() {
return modelClassList.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView textView_name;
TextView textView_details;
TextView textView_priority;
ImageButton btn_delete;
public Viewholder(#NonNull View view) {
super(view);
textView_name = view.findViewById(R.id.textview_name);
textView_details = view.findViewById(R.id.textview_details);
textView_priority = view.findViewById(R.id.textview_priotity);
btn_delete=view.findViewById(R.id.btn_delete);
}
}
}
I have implemented a expandable nested RecyclerView . Now I want to display an AlertDialog when an item of RecyclerView is clicked. I tried many ways and none of them worked. Here is my adapter class,
**Parent Adopter class code**'
$ package com.pscripto.mxmoviehub;
import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList; import java.util.List;
public class ParentAdopter extends RecyclerView.Adapter<ParentAdopter.ParentAdopterViewHolder> { private List<Movie_Model> movieModelList; private List<Child_Model> child_modelList; private ChildAdopter childAdopter; private Context context;
public ParentAdopter(#NonNull List<Movie_Model> movieModelList) {
this.movieModelList = movieModelList;
}
#NonNull
#Override
public ParentAdopterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootview = LayoutInflater.from(parent.getContext()).inflate(R.layout.vertical_rv,parent,false);
return new ParentAdopterViewHolder(rootview);
}
#SuppressLint("WrongConstant")
#Override
public void onBindViewHolder(#NonNull ParentAdopterViewHolder holder, int position) { Movie_Model movie_model = movieModelList.get(position); holder.tvSection.setText(movie_model.getHeaderTitle()); if (movie_model.getHeaderTitle().contains("Latest Movies")){ childAdopter= new ChildAdopter(getLatestMovie(),context);
} else if (movie_model.getHeaderTitle().contains("Action Movies")){
childAdopter= new ChildAdopter(getActionMovies(),context);
} else if (movie_model.getHeaderTitle().contains("Romantic Movies")){
childAdopter = new ChildAdopter(getRomanticMovies(),context); } holder.childRecyclerview.setHasFixedSize(true); holder.childRecyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayout.HORIZONTAL,false)); holder.childRecyclerview.setAdapter(childAdopter); //customClicl();
} private void customClicl(){
childAdopter.setCustomClickListener(new ChildAdopter.CustomClickListener() {
#Override
public void onItemClick(int position) {
Toast.makeText(context, "hi", Toast.LENGTH_SHORT).show();
}
}); }
private List<Child_Model> getLatestMovie(){ child_modelList = new ArrayList<>(); child_modelList.add(new Child_Model(R.drawable.salmankhanmovieone,"Bajrangi Bhaijaan"));
child_modelList.add(new Child_Model(R.drawable.pati,"Pati Patni Aur Woh"));
child_modelList.add(new Child_Model(R.drawable.blackmail,"Blackmail 2019"));
child_modelList.add(new Child_Model(R.drawable.bharat,"Bharat 2019"));
child_modelList.add(new Child_Model(R.drawable.gang,"Gangster 3"));
return child_modelList;
}
private List<Child_Model> getActionMovies(){
child_modelList = new ArrayList<>();
child_modelList.add(new Child_Model(R.drawable.salmankhanmovieone,"Bajrangi Bhaijaan"));
child_modelList.add(new Child_Model(R.drawable.blackmail,"Blackmail 2019"));
child_modelList.add(new Child_Model(R.drawable.bharat,"Bharat 2019"));
child_modelList.add(new Child_Model(R.drawable.gang,"Gangster 3"));
return child_modelList;
}
private List<Child_Model> getRomanticMovies(){
child_modelList = new ArrayList<>();
child_modelList.add(new Child_Model(R.drawable.star,"Love Star"));
child_modelList.add(new Child_Model(R.drawable.bestofme,"The Best Of Me"));
child_modelList.add(new Child_Model(R.drawable.trailer,"After Trailer"));
child_modelList.add(new Child_Model(R.drawable.buylove,"Cant Buy Love"));
return child_modelList;
}
#Override
public int getItemCount() {
return movieModelList.size();
}
class ParentAdopterViewHolder extends RecyclerView.ViewHolder { TextView tvSection; RecyclerView childRecyclerview;
public ParentAdopterViewHolder(#NonNull View itemView) {
super(itemView);
tvSection = itemView.findViewById(R.id.tvsection);
childRecyclerview = itemView.findViewById(R.id.child_rv);
}
}
}'$'
**Child adopter class**
package com.pscripto.mxmoviehub;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
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 android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class ChildAdopter extends RecyclerView.Adapter<ChildAdopter.ChildAdopterViewHolder> {
private List<Child_Model> child_modelList;
private ChildAdopter childAdopter ;
private Context context;
private CustomClickListener customClickListener;
public void setCustomClickListener(CustomClickListener customClickListener) {
this.customClickListener = customClickListener;
}
interface CustomClickListener{
void onItemClick (int position);
}
public ChildAdopter(List<Child_Model> child_modelList, Context context) {
this.child_modelList = child_modelList;
this.context = context;
}
#NonNull
#Override
public ChildAdopterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootview = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizental_layout, parent, false);
return new ChildAdopterViewHolder(rootview);
}
#Override
public void onBindViewHolder(#NonNull ChildAdopterViewHolder holder, int position) {
Child_Model child_model = child_modelList.get(position);
holder.movieImg.setImageResource(child_model.getImgResId());
holder.movieTitle.setText(child_model.getTitle());
Boolean isExpanded = child_modelList.get(position).getExpanded();
holder.expandidLayout.setVisibility(isExpanded ? View.VISIBLE : View.INVISIBLE);
}
#Override
public int getItemCount() {
return child_modelList.size();
}
class ChildAdopterViewHolder extends RecyclerView.ViewHolder {
private ImageView movieImg ,ivEdit,ivDel;
private TextView movieTitle;
LinearLayout expandidLayout;
public ChildAdopterViewHolder(#NonNull View itemView) {
super(itemView);
movieImg = itemView.findViewById(R.id.movie_img);
movieTitle = itemView.findViewById(R.id.movie_name);
expandidLayout = itemView.findViewById(R.id.expandable_layout);
ivEdit = itemView.findViewById(R.id.iv_Edit);
ivDel = itemView.findViewById(R.id.del_img);
movieTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Child_Model child_model = child_modelList.get(position);
child_model.setExpanded(!child_model.getExpanded());
notifyItemChanged(getAdapterPosition());
}
});
ivEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position= getAdapterPosition();
if (customClickListener != null){
customClickListener.onItemClick(position);
}
}
});
}
}
}
I have list of Categories of Subjects in my firestore database and i want it to be displayed in my app ( which i thought can be done by recyclerView).But my RecyclerView is not populating any data.You can see my code below:
Question_list.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
public class Question_list extends AppCompatActivity {
private static final String TAG ="Firelog" ;
private RecyclerView mMainList;
private FirebaseFirestore mFirestore;
private CategoryAdapter categoryAdapter;
private List<Categories> list_category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_list);
mMainList = (RecyclerView)findViewById(R.id.main_list_id);
//mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(this));
mMainList.setAdapter(categoryAdapter);
mFirestore = FirebaseFirestore.getInstance();
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
mFirestore.collection("Questions").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(e!=null){
Log.d(TAG, "Error: "+ e.getMessage());
}
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if(doc.getType() == DocumentChange.Type.MODIFIED){
//String document = doc.getDocument().getString("Category");
Categories categories = doc.getDocument().toObject(Categories.class);
list_category.add(categories);
Log.d(TAG, "Category: "+ categories);
categoryAdapter.notifyDataSetChanged();
}
}
}
});
}
}
CategoryAdapter.java
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CategoryAdapter extends
RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
public List<Categories> list_categorie;
public CategoryAdapter(List<Categories> list_categorie){
this.list_categorie = list_categorie;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_list,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mCategoryText.setText(list_categorie.get(position).getCategory());
}
#Override
public int getItemCount() {
return list_categorie.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mview;
public TextView mCategoryText;
public ViewHolder(View itemView) {
super(itemView);
mview = itemView;
mCategoryText = (TextView)mview.findViewById(R.id.category_text_id);
}
}
}
Categories.java
public class Categories {
String category;
public Categories(){}
public Categories(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
}
Above are my all java classes. I haven't uploaded my XML file as i think the problem is in the java class.
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
list_category should be initialized before passing it to the adapter
list_category = new ArrayList<>();
categoryAdapter = new CategoryAdapter(list_category);