before down voting please consider this i have searched everywhere and not found the solution please help..
from the above structure i want to access the values inside Results -> examId> total_marks, marks_scored but i am not being able to get inside Result node
i want the values to be feed inside recyclerview
This is my adapter
public class MarksListAdapter extends RecyclerView.Adapter<MarksListAdapter.MyViewHolder> {
Context context;
ArrayList<MarksList> marksListArrayList;
public MarksListAdapter(Context c, ArrayList<MarksList> p) {
context = c;
marksListArrayList = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.marks_list, viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.tvStudentName.setText(marksListArrayList.get(i).getName());
myViewHolder.tvOutOf_List.setText(marksListArrayList.get(i).getResults().getTotal_marks());
myViewHolder.etEnterMarks.setText(marksListArrayList.get(i).getResults().getMarks_scored());
POJO class
public class MarksList {
String name;
public MarksList() {
}
public MarksList(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private Results Results;
public com.hitech.hitechacademy.POJO.Results getResults() {
return Results;
}
}
public class Results {
String marks_scored;
String total_marks;
public Results() {
}
public Results(String marks_scored, String total_marks) {
this.marks_scored = marks_scored;
this.total_marks = total_marks;
}
public String getMarks_scored() {
return marks_scored;
}
public void setMarks_scored(String marks_scored) {
this.marks_scored = marks_scored;
}
public String getTotal_marks() {
return total_marks;
}
public void setTotal_marks(String total_marks) {
this.total_marks = total_marks;
}
}
both are seperate java classes
This is the recyclerview activity
DatabaseReference examRef = firebaseDatabase.getReference().child("Batches").child(batchNameValue);
examRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String examTitle;
String studentName;
specificStudent.clear();
resultsArrayList.clear();
for (DataSnapshot studentResult : dataSnapshot.getChildren()) {
examTitle = (String) studentResult.child("Results").child(examKeyValue).child("exam_name").getValue();
Log.d("TAG_Full", examTitle + "" + examFullName);
if (examTitle != null && examTitle.equals(examFullName)) {
MarksList marksList = studentResult.getValue(MarksList.class);
//studentName = (String) studentResult.child("name").getValue();
specificStudent.add(marksList);
Log.d("SpecificStudent", specificStudent.toString() + resultsArrayList.toString());
} else {
//code for 1 exam and no students
}
}
specificStudent.toString();
marksListAdapter = new MarksListAdapter(LoadedExam.this,specificStudent);
marksRecyclerView.setAdapter(marksListAdapter);
marksListAdapter.notifyDataSetChanged();
}
I am not getting any errors but only the name of the student is getting fetched Please help
Related
I'm recently learning about firebase database. Now I'm trying to put the records to RecyclerView
Here is what I do
BiodataModel value;
DatabaseReference mdatabase;
private List<BiodataModel> mBiodata;
BiodataAdapter dAdapter;
List<BiodataModel> userlist = new ArrayList<>();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Biodata");
mdatabase.keepSynced(true);
mdatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
userlist = new ArrayList<>();
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
BiodataModel bioModel = postSnapshot.getValue(BiodataModel.class); // The problem is here
userlist.add(bioModel);
}
} catch (Exception ex) {
Log.e("MYERROR", ex.getMessage());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("MYERROR", databaseError.getMessage());
}
});
Here is my adapter
public class BiodataAdapter extends RecyclerView.Adapter<BiodataAdapter.MyViewHolder>{
private List<BiodataModel> bioList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView fullname;
public MyViewHolder(View view) {
super(view);
fullname = (TextView) view.findViewById(R.id.fullname);
}
}
public BiodataAdapter(){
}
public BiodataAdapter(List<BiodataModel> bioList) {
this.bioList = bioList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.biodata_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
BiodataModel bio = bioList.get(position);
holder.fullname.setText(bio.getFullname());
}
#Override
public int getItemCount() {
return bioList.size();
}
}
and this is my Model
public class BiodataModel {
public String fullname,email,noTelp,alamat;
public BiodataModel(String fullname, String email, String noTelp,String alamat){
this.fullname = fullname;
this.email = email;
this.noTelp = noTelp;
this.alamat = alamat;
}
public String getFullname() {
return fullname;
}
public String getEmail() {
return email;
}
public String getNoTelp() {
return noTelp;
}
public String getAlamat() {
return alamat;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public void setEmail(String email) {
this.email = email;
}
public void setNoTelp(String noTelp) {
this.noTelp = noTelp;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
}
and i get this error
Can't convert object of type java.lang.String to type
ZZZZ.BiodataModel
how can i fix it ?
Your reference is this:
mdatabase = FirebaseDatabase.getInstance().getReference().child("Biodata");
so at child Biodata, then you are iterating inside it's direct child for (DataSnapshot postSnapshot : dataSnapshot.getChildren()), thus retrieving the Strings Alamat,Email.
To solve this, you need to remove the for loop and try the following:
mdatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
userlist = new ArrayList<>();
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try {
BiodataModel bioModel = dataSnapshot.getValue(BiodataModel.class);
userlist.add(bioModel);
} catch (Exception ex) {
Log.e("MYERROR", ex.getMessage());
}
}
}
I am new in Android and working on an Android app which can retrieve data from firebase. There is a weird problem. I already successfully implemented the retrieving function for one data model of my program, and I used same codes just changed the variables but it doesn't work for another data model. I did many tests and I think the problem is in FirebaseHelper cuz there is no any data returned from the data snapshot. The error is
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
The codes are shown below:
The Activity that shows the retrieved data in a listview.
public class TimeTableActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper firebasehelper;
TimeTableAdapter adapter;
ListView lv_CourseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_table);
//GET INTENT
Intent intent = this.getIntent();
String majorID = intent.getStringExtra("MAJOR_ID");
lv_CourseList = (ListView) findViewById(R.id.lv_CourseList);
//INITIALIZE FIREBASE DB
db= FirebaseDatabase.getInstance().getReference();
firebasehelper=new FirebaseHelper(db);
//ADAPTER
adapter = new TimeTableAdapter(getApplicationContext(),firebasehelper.retrieveCourse(majorID, new CourseCallbacks() {
#Override
public void onCourseCallback(ArrayList<CourseInfo> courseInfos) {
lv_CourseList.setAdapter(adapter);
}
}));
lv_CourseList.setAdapter(adapter);
}
}
FirebaseHelper:
public class FirebaseHelper{
private DatabaseReference db;
private ArrayList<Major> majors = new ArrayList<>();
private ArrayList<CourseInfo> courseInfos = new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//Save the Major info. into db
public Boolean saveMajor(Major major)
{
Boolean saved = null;
if(major==null)
{
saved =false;
}else
{
try
{
db.child("Major").push().setValue(major);
saved =true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved =false;
}
}
return saved;
}
//Save the Course info. into db
public Boolean saveCourse(CourseInfo courseInfo)
{
Boolean saved = null;
if(courseInfo==null)
{
saved =false;
}else
{
try
{
db.child("CourseInfo").push().setValue(courseInfo);
saved =true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved =false;
}
}
return saved;
}
public ArrayList<Major> retrieveMajor(final MajorCallbacks majorCallbacks){
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Major major = ds.getValue(Major.class);
if (major != null && major.getMajor_id() != null) {
majors.add(major);
}
}
majorCallbacks.onMajorCallback(majors);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Major major = ds.getValue(Major.class);
if (major != null && major.getMajor_id() != null) {
majors.add(major);
}
}
majorCallbacks.onMajorCallback(majors);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
db.addChildEventListener(childEventListener);
if (!majors.isEmpty()){
db.removeEventListener(childEventListener);
}
return majors;
}
public ArrayList<CourseInfo> retrieveCourse(String majorID, final CourseCallbacks courseCallbacks){
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CourseInfo courseInfo = ds.getValue(CourseInfo.class);
if (courseInfo != null && courseInfo.getCourse_id() != null) {
courseInfos.add(courseInfo);
}
}
courseCallbacks.onCourseCallback(courseInfos);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CourseInfo courseInfo = ds.getValue(CourseInfo.class);
if (courseInfo != null && courseInfo.getCourse_id() != null) {
courseInfos.add(courseInfo);
}
}
courseCallbacks.onCourseCallback(courseInfos);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
db.child("CourseInfo").orderByChild("major_id").equalTo(majorID).addChildEventListener(childEventListener);
return courseInfos;
}
}
The retrieveMajor method works well even though it returns many null data and repetitive data, and I used the codes of retrieveMajor in retrieveCourse. It doesn't work, the courseInfos is always null. Even though I changed db.child("CourseInfo").orderByChild("major_id").equalTo(majorID).addChildEventListener(childEventListener);
to
db.addChildEventListener(childEventListener);
,still nothing is retrieved which means the problem is not the query (Probably the query is also wrong).
Adapter:
public class TimeTableAdapter extends BaseAdapter {
Context context;
ArrayList<CourseInfo> courseInfos;
public TimeTableAdapter(Context context, ArrayList<CourseInfo> courseInfos) {
this.context = context;
this.courseInfos = courseInfos;
}
#Override
public int getCount() {
return courseInfos.size();
}
#Override
public Object getItem(int pos) {
return courseInfos.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = LayoutInflater.from(context);
if(convertView == null)
{
convertView= LayoutInflater.from(context).inflate(R.layout.model_timetable,viewGroup,false);
}
TextView tv_courseid= (TextView) convertView.findViewById(R.id.tv_courseid);
TextView tv_coursename= (TextView) convertView.findViewById(R.id.tv_coursename);
TextView tv_courseinstructor= (TextView) convertView.findViewById(R.id.tv_courseinstructor);
TextView tv_courseavailable= (TextView) convertView.findViewById(R.id.tv_courseavailable);
final CourseInfo courseInfo= (CourseInfo) this.getItem(position);
tv_courseid.setText(courseInfo.getCourse_id());
tv_coursename.setText(courseInfo.getCourse_name());
tv_courseinstructor.setText(courseInfo.getCourse_instructor());
tv_courseavailable.setText(courseInfo.getCourse_available());
return convertView;
}
}
Data model:
#IgnoreExtraProperties
public class CourseInfo {
public String course_id;
public String course_name;
public int course_section;
public String course_type;
public double course_crdhrs;
public String course_days;
public String course_times;
public String course_location;
public int course_max;
public int course_cur;
public int course_available;
public int course_wl;
public double course_per;
public String course_instructor;
public String course_description;
public String course_prerequire;
public String major_id;
public CourseInfo() {
}
public CourseInfo(String course_id, String course_name, int course_section, String course_type, double course_crdhrs, String course_days, String course_times, String course_location, int course_max, int course_cur, int course_available, int course_wl, double course_per, String course_instructor, String course_description, String course_prerequire, String major_id) {
this.course_id = course_id;
this.course_name = course_name;
this.course_section = course_section;
this.course_type = course_type;
this.course_crdhrs = course_crdhrs;
this.course_days = course_days;
this.course_times = course_times;
this.course_location = course_location;
this.course_max = course_max;
this.course_cur = course_cur;
this.course_available = course_available;
this.course_wl = course_wl;
this.course_per = course_per;
this.course_instructor = course_instructor;
this.course_description = course_description;
this.course_prerequire = course_prerequire;
this.major_id = major_id;
}
public String getCourse_id() {
return course_id;
}
public String getCourse_name() {
return course_name;
}
public int getCourse_section() {
return course_section;
}
public String getCourse_type() {
return course_type;
}
public double getCourse_crdhrs() {
return course_crdhrs;
}
public String getCourse_days() {
return course_days;
}
public String getCourse_times() {
return course_times;
}
public String getCourse_location() {
return course_location;
}
public int getCourse_max() {
return course_max;
}
public int getCourse_cur() {
return course_cur;
}
public int getCourse_available() {
return course_available;
}
public int getCourse_wl() {
return course_wl;
}
public double getCourse_per() {
return course_per;
}
public String getCourse_instructor() {
return course_instructor;
}
public String getCourse_description() {
return course_description;
}
public String getCourse_prerequire() {
return course_prerequire;
}
public String getMajor_id() {
return major_id;
}
}
If you need more codes or information, please comment and let me know. I will really appreciate if you can also help me solve the null data and repetitive data problem cuz it makes the listview show many blank and repetitive items.
You cannot return something now that hasn't been loaded yet. With other words, you cannot just simply create a method that as a return type, an ArrayList<Major> and in the same time return that object. This is happening because those methods, onChildAdded(), onChildChanged() and so on, have an asynchronous behaviour, which means that are called even before you are getting/updating the data from/in the database. To solve this, you can move the declaration of that ArrayList inside one method and do what you need to do with it or dive into asynchronous world and use the last part of my answer from this post. You can take also a look at this video for a better understanding.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Getting Error
FATAL EXCEPTION: main
Process: com.example.wuntu.tv_bucket, PID: 3895
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at com.example.wuntu.tv_bucket.Models.Cast.writeToParcel(Cast.java:136)
at android.os.Parcel.writeParcelable(Parcel.java:1437)
at android.os.Parcel.writeValue(Parcel.java:1343)
at android.os.Parcel.writeList(Parcel.java:759)
at android.os.Parcel.writeValue(Parcel.java:1365)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:686)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1330)
at android.os.Bundle.writeToParcel(Bundle.java:1079)
at android.os.Parcel.writeBundle(Parcel.java:711)
at android.content.Intent.writeToParcel(Intent.java:8790)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3112)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1541)
at android.app.Activity.startActivityForResult(Activity.java:4284)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4231)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4568)
at android.app.Activity.startActivity(Activity.java:4536)
at com.example.wuntu.tv_bucket.Adapters.CastDetailAdapter$1.onClick(CastDetailAdapter.java:124)
at android.view.View.performClick(View.java:5698)
at android.widget.TextView.performClick(TextView.java:10908)
at android.view.View$PerformClick.run(View.java:22557)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7231)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Getting error in sending arraylist of object from adapter to other activity. I wanna send my arraylist from onBindViewHolder method of Adapter to another activity but its is showing null exception error on the Cast Class in writetoParcel Method. How to send arraylist properly?
Cast Class
public class Cast implements Parcelable {
#SerializedName("cast_id")
#Expose
private Integer castId;
#SerializedName("character")
#Expose
private String character;
#SerializedName("credit_id")
#Expose
private String creditId;
#SerializedName("gender")
#Expose
private Integer gender;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("order")
#Expose
private Integer order;
#SerializedName("profile_path")
#Expose
private String profilePath;
public Cast(){
}
protected Cast(Parcel in) {
character = in.readString();
id = in.readInt();
name = in.readString();
profilePath = in.readString();
}
public static final Creator<Cast> CREATOR = new Creator<Cast>() {
#Override
public Cast createFromParcel(Parcel in) {
return new Cast(in);
}
#Override
public Cast[] newArray(int size) {
return new Cast[size];
}
};
public Integer getCastId() {
return castId;
}
public void setCastId(Integer castId) {
this.castId = castId;
}
public String getCharacter() {
return character;
}
public void setCharacter(String character) {
this.character = character;
}
public String getCreditId() {
return creditId;
}
public void setCreditId(String creditId) {
this.creditId = creditId;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public String getProfilePath() {
return profilePath;
}
public void setProfilePath(String profilePath) {
this.profilePath = profilePath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i)
{
parcel.writeString(name);
parcel.writeString(profilePath);
parcel.writeString(character);
parcel.writeInt(id);
}
}
CastDetailAdapter Class
public class CastDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Cast> detailArrayList = new ArrayList<>() ;
private UrlConstants urlConstants = UrlConstants.getSingletonRef();
private Cast cast;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private Context context;
MovieView a;
ArrayList<Cast> FullArrayList = new ArrayList<>();
public CastDetailAdapter(MovieView movieView, ArrayList<Cast> detailArrayList,ArrayList<Cast> subCastArrayList)
{
a = movieView;
this.detailArrayList = subCastArrayList;
this.FullArrayList = detailArrayList;
}
public class MyViewHolder1 extends RecyclerView.ViewHolder
{
ImageView cast_profile_picture;
TextView cast_name,cast_character_name;
public MyViewHolder1(View view)
{
super(view);
cast_profile_picture = (ImageView) view.findViewById(R.id.thumbnail);
cast_name = (TextView) view.findViewById(R.id.title);
cast_character_name = (TextView) view.findViewById(R.id.count);
}
}
public class FooterViewHolder1 extends RecyclerView.ViewHolder
{
TextView view_more;
public FooterViewHolder1(View itemView) {
super(itemView);
view_more = (TextView) itemView.findViewById(R.id.view_more);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount() -1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
context = parent.getContext();
if (viewType == VIEW_ITEM)
{
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cast_details, parent, false);
return new MyViewHolder1(v);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.footer_layout_movie_details, parent, false);
return new FooterViewHolder1(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if(holder instanceof MyViewHolder1)
{
cast = detailArrayList.get(position);
((MyViewHolder1)holder).cast_character_name.setText(cast.getCharacter());
((MyViewHolder1)holder).cast_name.setText(cast.getName());
String url3 = urlConstants.URL_Image + cast.getProfilePath();
Picasso.with(context)
.load(url3)
.into(((MyViewHolder1)holder).cast_profile_picture);
}
else if (holder instanceof FooterViewHolder1)
{
((FooterViewHolder1)holder).view_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent intent = new Intent(context,CastViewActivity.class);
intent.putParcelableArrayListExtra("LIST",FullArrayList);
context.startActivity(intent);
}
});
}
}
#Override
public int getItemCount() {
return this.detailArrayList.size();
}
}
In your writeToParcel() method, you have
parcel.writeInt(id);
Since id is Integer, this is going to auto-unbox id. If id is null, this auto-unboxing will throw a NullPointerException.
Since there is no Parcel.writeInteger() method, you're going to have to record whether or not id is null in a separate write. Something like:
if (id == null) {
dest.writeInt(0);
}
else {
dest.writeInt(1);
dest.writeInt(id);
}
And to read it back out:
int hasId = in.readInt();
if (hasId == 1) {
id = in.readInt();
}
else {
id = null;
}
The order in which you read the values from the parcel has to be the same as the order it was written to it.
Try:
protected Cast(Parcel in) {
name = in.readString();
profilePath = in.readString();
character = in.readString();
id = in.readInt();
}
I have an autocompletetextview. I am getting results from an API and sending to the adapter on textchanged.
Here is the adapter.
public class ProductSearchAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<ProductListModel> originalList;
private ArrayList<ProductListModel> suggestions = new ArrayList<>();
private Filter filter = new CustomFilter();
public ProductSearchAdapter(Context context, ArrayList<ProductListModel> originalList) {
this.context = context;
this.originalList = originalList;
}
#Override
public int getCount() {
return suggestions.size(); // Return the size of the suggestions list.
}
#Override
public Object getItem(int position) {
return originalList.get(position).getName();
}
#Override
public long getItemId(int position) {
return 0;
}
/**
* This is where you inflate the layout and also where you set what you want to display.
* Here we also implement a View Holder in order to recycle the views.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.product_search_row, parent, false);
holder = new ViewHolder();
holder.textViewProductName = (TextView) convertView.findViewById(R.id.textViewProductName);
holder.imageViewProductImage = (ImageView) convertView.findViewById(R.id.imageViewProductImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewProductName.setText(originalList.get(position).getName());
Picasso.with(context)
.load(originalList.get(position).getImagesSmall().get(0).getSrc())
.into(holder.imageViewProductImage);
return convertView;
}
#Override
public Filter getFilter() {
return filter;
}
private static class ViewHolder {
ImageView imageViewProductImage;
TextView textViewProductName;
}
/**
* Our Custom Filter Class.
*/
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
for (int i = 0; i < originalList.size(); i++) {
if (originalList.get(i).getName().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.
suggestions.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
}
FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;
results.values = suggestions;
results.count = suggestions.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
Now the problem is the dropdown is not showing up. Whereas if I try the same autocompletetextview with array adapter, its showing up.
Here is the activity part I am calling the api from:
autoCompleteTextViewSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().length() > 0) {
hitSearchAPI(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
On API response:
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
productList = gson.fromJson(responseString, ProductListModel[].class);
arrayListProducts = new ArrayList<ProductListModel>(Arrays.asList(productList));
productsSearchAdapter = new ProductSearchAdapter(MainActivity.this, arrayListProducts);
autoCompleteTextViewSearch.setThreshold(1);
autoCompleteTextViewSearch.setAdapter(productsSearchAdapter);
Same textview working with array adapter but not with custom adapter.
ProductListModel:
public class ProductListModel {
String _id;
String name;
String color;
String description;
int credits;
ProductItemModel category;
ArrayList<ProductItemModel> subcategories;
ProductItemModel fit;
ProductBrandModel brand;
ArrayList<ProductItemModel> rules;
ProductBrandModel condition;
ArrayList<ProductImagesModel> images;
ArrayList<ProductItemModel> size;
ArrayList<ProductImagesModel> imagesSmall;
String userId;
long time_created;
long time_approved;
long time_featured;
long time_rejected;
boolean approved;
boolean rejected;
boolean featured;
int status;
ProductUserProfileModel user_profile;
String rejected_reason_id;
String categoryId;
int likes;
boolean likedBy;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
public ProductItemModel getCategory() {
return category;
}
public void setCategory(ProductItemModel category) {
this.category = category;
}
public ArrayList<ProductItemModel> getSubcategories() {
return subcategories;
}
public void setSubcategories(ArrayList<ProductItemModel> subcategories) {
this.subcategories = subcategories;
}
public ProductItemModel getFit() {
return fit;
}
public void setFit(ProductItemModel fit) {
this.fit = fit;
}
public ProductBrandModel getBrand() {
return brand;
}
public void setBrand(ProductBrandModel brand) {
this.brand = brand;
}
public ArrayList<ProductItemModel> getRules() {
return rules;
}
public void setRules(ArrayList<ProductItemModel> rules) {
this.rules = rules;
}
public ProductBrandModel getCondition() {
return condition;
}
public void setCondition(ProductBrandModel condition) {
this.condition = condition;
}
public ArrayList<ProductImagesModel> getImages() {
return images;
}
public void setImages(ArrayList<ProductImagesModel> images) {
this.images = images;
}
public ArrayList<ProductItemModel> getSize() {
return size;
}
public void setSize(ArrayList<ProductItemModel> size) {
this.size = size;
}
public ArrayList<ProductImagesModel> getImagesSmall() {
return imagesSmall;
}
public void setImagesSmall(ArrayList<ProductImagesModel> imagesSmall) {
this.imagesSmall = imagesSmall;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public long getTime_created() {
return time_created;
}
public void setTime_created(long time_created) {
this.time_created = time_created;
}
public long getTime_approved() {
return time_approved;
}
public void setTime_approved(long time_approved) {
this.time_approved = time_approved;
}
public long getTime_featured() {
return time_featured;
}
public void setTime_featured(long time_featured) {
this.time_featured = time_featured;
}
public long getTime_rejected() {
return time_rejected;
}
public void setTime_rejected(long time_rejected) {
this.time_rejected = time_rejected;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public boolean isRejected() {
return rejected;
}
public void setRejected(boolean rejected) {
this.rejected = rejected;
}
public boolean isFeatured() {
return featured;
}
public void setFeatured(boolean featured) {
this.featured = featured;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public ProductUserProfileModel getUser_profile() {
return user_profile;
}
public void setUser_profile(ProductUserProfileModel user_profile) {
this.user_profile = user_profile;
}
public String getRejected_reason_id() {
return rejected_reason_id;
}
public void setRejected_reason_id(String rejected_reason_id) {
this.rejected_reason_id = rejected_reason_id;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public boolean isLikedBy() {
return likedBy;
}
public void setLikedBy(boolean likedBy) {
this.likedBy = likedBy;
}
}
You need to add toString() method to your model so the AutoCompleteTextView can compare between the typed String and the returned value.
if you are looking by name the toString() needs to return it :
#Override
public String toString() {
return name ;
}
}
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()
on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!
MyBlog Adapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogResponse> postsList;
Context context;
public static String blog_Id, blogID;
private LayoutInflater inflater;
public MyBlogAdapter(Context context, List<BlogResponse> postsList){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.postsList = postsList;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_view,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
final BlogResponse posts= postsList.get(position);
holder.summary.setText(posts.getBlogExcerpt().trim().toString());
holder.title.setText(posts.getBlogTitle().trim().toString());
// Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);
holder.blogHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AnotherSingleView.class);
blog_Id = posts.getBlogId();
intent.putExtra(blogID,blog_Id);
Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
Log.d("MyBlogAdapter,","getItemCount"+postsList.size());
return postsList == null ? (0) : postsList.size();
}
}
SecondActivity:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
SingleBlogPost singleBlogPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_single_view);
Intent intent = getIntent();
Bundle showBlogId = intent.getExtras();
postID = showBlogId.getString(blogID);
Log.d("AnotherSingleView","Please check blog Id: "+postID);
singleBlogPosts = new ArrayList<>();
blogContent = (TextView)findViewById(R.id.blog_content);
blogSub = (TextView) findViewById(R.id.blog_subtitle);
blogTitle =(TextView) findViewById(R.id.blog_title);
blogPic =(ImageView) findViewById(R.id.blog_pix);
singlePostDisplay();
}
private void singlePostDisplay() {
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse(postID);
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
for (SingleBlogPost posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
else{
Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
} }
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface:
public interface BlogaPI {
#GET("blog")
Call<BlogList> response();
#GET("post/{blog_id}")
Call<List<SingleBlogPost>> postResponse(#Path("blog_id") String blog_id);
//Call<List<SingleBlogPost>> postResponse();
}
SingleBlogPost:
public class SingleBlogPost {
#SerializedName("blog_id")
#Expose
private String blogId;
#SerializedName("blog_title")
#Expose
private String blogTitle;
#SerializedName("blog_subtitle")
#Expose
private String blogSubtitle;
#SerializedName("blog_excerpt")
#Expose
private String blogExcerpt;
#SerializedName("blog_content")
#Expose
private String blogContent;
#SerializedName("blog_thumbnail")
#Expose
private String blogThumbnail;
#SerializedName("blog_medimg")
#Expose
private String blogMedimg;
#SerializedName("category_title")
#Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogSubtitle = blogSubtitle;
this.blogExcerpt = blogExcerpt;
this.blogContent = blogContent;
this.blogThumbnail = blogThumbnail;
this.blogMedimg = blogMedimg;
this.categoryTitle = categoryTitle;
}
public String getBlogId() {
return blogId;
}
public void setBlogId(String blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogSubtitle() {
return blogSubtitle;
}
public void setBlogSubtitle(String blogSubtitle) {
this.blogSubtitle = blogSubtitle;
}
public String getBlogExcerpt() {
return blogExcerpt;
}
public void setBlogExcerpt(String blogExcerpt) {
this.blogExcerpt = blogExcerpt;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getBlogThumbnail() {
return blogThumbnail;
}
public void setBlogThumbnail(String blogThumbnail) {
this.blogThumbnail = blogThumbnail;
}
public String getBlogMedimg() {
return blogMedimg;
}
public void setBlogMedimg(String blogMedimg) {
this.blogMedimg = blogMedimg;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
}
Check if the server response is different then null before you do a enhanced for like this:
if(singleBlogPosts!= null) {
for (SingleBlogPosts posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.