I'm attempting to create a custom adapter to display information from an ArrayList in a list view, but it seems to be rejecting an ArrayList, instead asking for just an array. Here is my faulty code:
ArrayList
public ArrayList<Ing> IngList = new ArrayList<>();
public ArrayList<Ing> get(){
return this.IngList;
}
Object Class
public class Ing {
int init;
double value;
String name;
String unit;
String quantity;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public double getValue(){ return value; }
public void setValue(double value){ this.value = value; }
public int getInit(){ return init; }
public void setInit(int init){ this.init = init; }
public String getUnit(){ return unit; }
public void setUnit(String unit){ this.unit = unit; }
public String getQuantity(){ return quantity; }
public void setQuantity(String quantity){ this.quantity = quantity; }
Ing(String name, double value, int init, String unit, String quantity) {
this.name = name;
this.value = value;
this.init = init;
this.unit = unit;
this.quantity = quantity;
}
}
ListAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<Ing> {
private Context context;
private Ing[] values = null;
public static Kitchen kitchen = new Kitchen();
public ListAdapter(Context context, int textViewResourceId, Ing[] values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
public int getCount(){
return values.length;
}
public Ing getItem(int position){
return values[position];
}
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
TextView unit = (TextView) convertView.findViewById(R.id.unit);
name.setText(kitchen.IngList.get(position).getName());
value.setText(kitchen.IngList.get(position).getQuantity());
unit.setText(kitchen.IngList.get(position).getUnit());
return convertView;
}
}
Assigning adapter
final ListAdapter adapter = new ListAdapter(getContext(),
R.layout.row_layout, IngList);
//error is in line above
final ListView listView = (ListView) root.findViewById(R.id.list);
listView.setAdapter(adapter);
row layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true"
android:ellipsize="end"
android:maxLines="1"
android:layout_marginBottom="2dp"
android:layout_marginLeft="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/value"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true"
android:maxLines="1"
android:layout_toEndOf="#+id/name"
android:layout_toRightOf="#+id/name"
android:text="Value"
android:layout_marginLeft="50dp"
android:layout_marginBottom="2dp"
android:ellipsize="end"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/unit"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true"
android:maxLines="1"
android:layout_toEndOf="#+id/value"
android:layout_toRightOf="#+id/value"
android:text="Unit"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:ellipsize="end"/>
Sorry if I posted more than I needed to. I also apologize in advance for being kind of dumb when it comes to organizing code. Thanks a million to anyone who can find out what's wrong here.
Your Modified ListAdapter
public class ListAdapter extends ArrayAdapter<Ing> {
private Context context;
private ArrayList<Ing> values = new ArrayList<>();
public static Kitchen kitchen = new Kitchen();
public ListAdapter(Context context, int textViewResourceId, ArrayList<Ing> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
public int getCount(){
return values.size();
}
public Ing getItem(int position){
return values.get(position);
}
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_layout, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
TextView unit = (TextView) convertView.findViewById(R.id.unit);
name.setText(kitchen.IngList.get(position).getName());
value.setText(kitchen.IngList.get(position).getQuantity());
unit.setText(kitchen.IngList.get(position).getUnit());
return convertView;
}
}
I also don't understand why you have used kitchen.IngList for getting the ArrayList for populating your list. You can use values instead of kitchen.IngList
Like #mark-keen and #mike-m have say, your adapter constructor is expecting Array but you giving it an ArrayList.
You create the adapter with:
public ArrayList<Ing> IngList = new ArrayList<>();
...
final ListAdapter adapter = new ListAdapter(getContext(), R.layout.row_layout, IngList);
But your Adapter constructor is only accepting Array:
public class ListAdapter extends ArrayAdapter<Ing> {
...
private Ing[] values = null;
public ListAdapter(Context context, int textViewResourceId, Ing[] values) {
...
}
}
So, you need to change your constructor to accept the ArrayList as its parameter. Something like this:
public class ListAdapter extends ArrayAdapter<Ing> {
private Context context;
// don't need to create object for values
// because it depends on the parameter value.
private ArrayList<Ing> values;
...
public ListAdapter(Context context, int textViewResourceId, ArrayList<Ing> values) {
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
...
}
Related
I'm trying to sort my RecyclerView with a Spinner. Every item in the List contains 1 ImageView and 2 TextView components. Would be a pleasure if somebody could implement the Spinner to my code, that I can sort those items.
I tried to implement the spinner twice, but needed to rebuild to recycler view without the spinner, because I failed. Don't know how to set up recycler view and spinner together, even with tutorials... I am stuck.
My Item.xml Layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:background="#color/Green">
<ImageView
android:id="#+id/SupItemIV1"
android:layout_width="150dp"
android:layout_height="75dp"
android:padding="2dp"
android:layout_margin="4dp"/>
<TextView
android:id="#+id/SupItemTV1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="160dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="4dp"
android:text="CREATINE"
android:textColor="#color/Black"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/SupItemTV2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="160dp"
android:layout_marginTop="30dp"
android:text="amino acid"
android:textColor="#color/GreyDark"
android:textSize="15sp"
android:textStyle="bold"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
My MainActivity (Here Supplements.java class):
package com.example.etigym;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class Supplements extends AppCompatActivity{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supplements);
ArrayList<SupplementsItem> supplementsList = new ArrayList<>();
supplementsList.add(new SupplementsItem(R.drawable.creatine, "CREATINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.glutamine, "GLUTAMINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.leucine, "LEUCINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.valine, "VALINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.isoleucine, "ISOLEUCINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.alanine, "ALANINE", "amino acid"));
supplementsList.add(new SupplementsItem(R.drawable.arginine, "ARGININE", "amino acid"));
mRecyclerView = findViewById(R.id.Supplements_RV);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new SupplementsAdapter(supplementsList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
ViewCompat.setNestedScrollingEnabled(mRecyclerView, false);
}
}
My Supplements Layout from the Supplements.java class:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Supplements">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/Supplements_RV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:background="#color/GreyDark"
android:scrollbars="vertical"/>
</RelativeLayout>
My Adapter:
public class SupplementsAdapter extends RecyclerView.Adapter<SupplementsAdapter.SupplementsViewHolder> {
private ArrayList<SupplementsItem> mSupplementsList;
public static class SupplementsViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public SupplementsViewHolder(#NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.SupItemIV1);
mTextView1 = itemView.findViewById(R.id.SupItemTV1);
mTextView2 = itemView.findViewById(R.id.SupItemTV2);
}
}
public SupplementsAdapter(ArrayList<SupplementsItem> supplementsList){
mSupplementsList = supplementsList;
}
#NonNull
#Override
public SupplementsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.supplements_item, parent, false);
SupplementsViewHolder svh = new SupplementsViewHolder(v);
return svh;
}
#Override
public void onBindViewHolder(#NonNull SupplementsViewHolder holder, int position) {
SupplementsItem currentSupplementsItem = mSupplementsList.get(position);
holder.mImageView.setImageResource(currentSupplementsItem.getImageResource());
holder.mTextView1.setText(currentSupplementsItem.getText1());
holder.mTextView2.setText(currentSupplementsItem.getText2());
}
#Override
public int getItemCount() {
return mSupplementsList.size();
}
}
SupplementsItem.java:
package com.example.etigym;
public class SupplementsItem {
private int mImageResource;
private String mText1;
private String mText2;
public SupplementsItem(int imageResource, String text1, String text2){
mImageResource = imageResource;
mText1 = text1;
mText2 = text2;
}
public int getImageResource(){
return mImageResource;
}
public String getText1(){
return mText1;
}
public String getText2(){
return mText2;
}
}
Afterwards we should have a List which we can sort by categories.
First you have to know how to sort the items on the list according to your needs, to do that you have to create a class that implements Comparator usually you want to do this class(es) within your Model Class SupplementsItem, this is how it could look your SupplementsItem, note that I added an extra property expiryDate, the idea is that you understand how to use the comparator to sort your list.
public class SupplementsItem {
private int itemImage;
private String item;
private String category;
private long expiryDate;
public SupplementsItem(int itemImage, String item, String category, long expiryDate) {
this.itemImage = itemImage;
this.item = item;
this.category = category;
this.expiryDate = expiryDate;
}
public int getItemImage() {
return itemImage;
}
public void setItemImage(int itemImage) {
this.itemImage = itemImage;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public long getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(long expiryDate) {
this.expiryDate = expiryDate;
}
// This will sort your list ascending by category
public static class CategoryComparatorUp implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return o1.getCategory().compareToIgnoreCase(o2.getCategory());
}
}
// This will sort your list descending by category
public static class CategoryComparatorDown implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return o2.getCategory().compareToIgnoreCase(o1.getCategory());
}
}
// This will sort your list ascending by expiration date
public static class ExpiryComparatorUp implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return Long.compare(o1.getExpiryDate(), o2.getExpiryDate());
}
}
// This will sort your list descending by expiration date
public static class ExpiryComparatorDown implements Comparator<SupplementsItem> {
#Override
public int compare(SupplementsItem o1, SupplementsItem o2) {
return Long.compare(o2.getExpiryDate(), o1.getExpiryDate());
}
}
}
I have placed 4 comparators but you really need only one by category, or make a more complex comparator.
For example if you want to sort by Expiration date descending you want to use ExpiryComparatorUp and then Collections.reverse(), like this you can use only one comparator by property in your model.
To use it after you populate your list, you call:
Collections.sort(supplementsList, new SupplementsItem.CategoryComparatorDown());
followed by:
mAdapter.notifyDataSetChanged();
or you can create a method for each type of sorting you want to do, i.e.:
private void sortByCategoryDown() {
Collections.sort(supplementsList, new SupplementsItem.CategoryComparatorDown());
mAdapter.notifyDataSetChanged();
}
and then in your onItemSelected of your spinner just call sortByCategoryDown()
From here you only need to work in your spinner logic. Let me know of your doubts in the comments.
I modified your class with the idea of giving you an idea on how to do the Comparator thingy, but you don't need to make it like that.
I need to make an expandable listview but for parent i have to pass arraylist and i am getting class cast exception in getGroupView . Please help me in writing the adapter for the following :
PhraseModel.java :
package in.abc.pdfsearchapp;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class PhraseModel implements Parcelable {
private ArrayList<PhraseList> phraseList;
// constructor
public PhraseModel(ArrayList<PhraseList> phraseList) {
this.phraseList = phraseList;
}
//---------------------------Getter-Setter--------------------------------------------------------------------------------
public ArrayList<PhraseList> getPhraseList() {
return phraseList;
}
public void setPhraseList(ArrayList<PhraseList> phraseList) {
this.phraseList = phraseList;
}
// Parcelling
protected PhraseModel(Parcel in) {
phraseList=in.createTypedArrayList(PhraseList.CREATOR);
}
public static final Creator<PhraseModel> CREATOR = new Creator<PhraseModel>() {
#Override
public PhraseModel createFromParcel(Parcel in) {
return new PhraseModel(in);
}
#Override
public PhraseModel[] newArray(int size) {
return new PhraseModel[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(phraseList);
}
//----------------------------------- //PhraseList // ------------------------------------------------------------------------
public static class PhraseList implements Parcelable {
public int documentId,noOfOccurences;
public String documentName,phrase;
public ArrayList<OccurenceDetails> occurenceDetails;
//constructor
public PhraseList(int documentId, String documentName,String phrase, int noOfOccurences, ArrayList<OccurenceDetails> occurenceDetails) {
this.documentId = documentId;
this.documentName = documentName;
this.phrase = phrase;
this.noOfOccurences = noOfOccurences;
this.occurenceDetails = occurenceDetails;
}
//------------------------------Getter-Setter--------------------------------------------------------------------------------------
public int getDocumentId() {
return documentId;
}
public void setDocumentId(int documentId) {
this.documentId = documentId;
}
public int getNoOfOccurences() {
return noOfOccurences;
}
public void setNoOfOccurences(int noOfOccurences) {
this.noOfOccurences = noOfOccurences;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
public ArrayList<OccurenceDetails> getOccurenceDetails() {
return occurenceDetails;
}
public void setOccurenceDetails(ArrayList<OccurenceDetails> occurenceDetails) {
this.occurenceDetails = occurenceDetails;
}
//Parcelling
protected PhraseList(Parcel in) {
documentId = in.readInt();
noOfOccurences = in.readInt();
documentName = in.readString();
phrase = in.readString();
}
public static final Creator<PhraseList> CREATOR = new Creator<PhraseList>() {
#Override
public PhraseList createFromParcel(Parcel in) {
return new PhraseList(in);
}
#Override
public PhraseList[] newArray(int size) {
return new PhraseList[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(documentId);
dest.writeString(documentName);
dest.writeInt(noOfOccurences);
dest.writeString(phrase);
}
}
//--------------------------------- //OccurrenceDetails // --------------------------------------------------------------------
public static class OccurenceDetails implements Parcelable {
int occurenceId,pageNo;
String fullPhrase;
//constructor
public OccurenceDetails(int occurenceId, int pageNo, String fullPhrase) {
this.occurenceId = occurenceId;
this.pageNo = pageNo;
this.fullPhrase = fullPhrase;
}
//-------------------------------Getter-Setter----------------------------------------------------------------------------------
public int getOccurenceId() {
return occurenceId;
}
public void setOccurenceId(int occurenceId) {
this.occurenceId = occurenceId;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public String getFullPhrase() {
return fullPhrase;
}
public void setFullPhrase(String fullPhrase) {
this.fullPhrase = fullPhrase;
}
//Parcelling
protected OccurenceDetails(Parcel in) {
occurenceId = in.readInt();
pageNo = in.readInt();
fullPhrase = in.readString();
}
public static final Creator<OccurenceDetails> CREATOR = new Creator<OccurenceDetails>() {
#Override
public OccurenceDetails createFromParcel(Parcel in) {
return new OccurenceDetails(in);
}
#Override
public OccurenceDetails[] newArray(int size) {
return new OccurenceDetails[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(occurenceId);
dest.writeInt(pageNo);
dest.writeString(fullPhrase);
}
}
}
ExpandableListAdapter.java :
package in.abc.pdfsearchapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Android on 22-Nov-17.
*/
public class ExpandableListAdapter extends BaseExpandableListAdapter {
Context context;
public ArrayList<PhraseModel.PhraseList> mPhraseList;
private HashMap<Integer,ArrayList<PhraseModel.OccurenceDetails>> occurenceList;
public ExpandableListAdapter(Context context, ArrayList<PhraseModel.PhraseList> mPhraseList, HashMap<Integer, ArrayList<PhraseModel.OccurenceDetails>> occurenceList) {
this.context = context;
this.mPhraseList = mPhraseList;
this.occurenceList = occurenceList;
}
public Object getChild(int groupPosition, int childPosition){
return this.occurenceList.get(this.mPhraseList.get(groupPosition)).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final ArrayList<PhraseModel.OccurenceDetails> childList = (ArrayList<PhraseModel.OccurenceDetails>) getChild(groupPosition, childPosition);
if(convertView==null){
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView occurenceId,fullPhrase,pageNo;
occurenceId=(TextView)convertView.findViewById(R.id.occurenceId);
fullPhrase=(TextView)convertView.findViewById(R.id.fullPhrase);
pageNo=(TextView)convertView.findViewById(R.id.pageNo);
occurenceId.setText(childList.get(groupPosition).getOccurenceId());
fullPhrase.setText(childList.get(groupPosition).getFullPhrase());
pageNo.setText(childList.get(groupPosition).getPageNo());
return convertView;
}
public int getChildrenCount(int groupPosition) {
return this.occurenceList.get(this.mPhraseList.get(groupPosition))
.size();
}
public Object getGroup(int groupPosition) {
return this.mPhraseList.get(groupPosition);
}
public int getGroupCount() {
return this.mPhraseList.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ArrayList<PhraseModel.PhraseList> parentList = (ArrayList<PhraseModel.PhraseList>) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView docName,totalOccurences;
docName=(TextView)convertView.findViewById(R.id.docName);
totalOccurences=(TextView)convertView.findViewById(R.id.totalOccurences);
docName.setText(parentList.get(groupPosition).getDocumentName());
totalOccurences.setText(parentList.get(groupPosition).getNoOfOccurences());
return convertView;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
LandingActivity.java :
package in.abc.pdfsearchapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class LandingActivity extends AppCompatActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
ArrayList<PhraseModel.PhraseList> phraseLists;
HashMap<Integer, ArrayList<PhraseModel.OccurenceDetails>> occurenceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
expListView = (ExpandableListView) findViewById(R.id.phraseList);
// preparing list data
phraseLists=new ArrayList<PhraseModel.PhraseList>();
occurenceList=new HashMap<Integer,ArrayList<PhraseModel.OccurenceDetails>>();
phraseLists.addAll(getmphraseset());
for (PhraseModel.PhraseList pl: phraseLists){
ArrayList<PhraseModel.OccurenceDetails>occurenceDetailses=pl.getOccurenceDetails();
occurenceList.put(pl.getDocumentId(),occurenceDetailses);
}
listAdapter = new ExpandableListAdapter(this, phraseLists,occurenceList);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
phraseLists.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
phraseLists.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
phraseLists.get(groupPosition)
+ " : "
+ occurenceList.get(
phraseLists.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
private ArrayList<PhraseModel.PhraseList> getmphraseset() {
try{
ArrayList<PhraseModel.PhraseList>phrase_Lists = new ArrayList<PhraseModel.PhraseList>();
ArrayList<PhraseModel.OccurenceDetails>occurenceDetailsArrayList=new ArrayList<PhraseModel.OccurenceDetails>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray phraseArray = jsonObject.getJSONArray("phraseList");
Log.d("getmphraseset", "phrase count: "+phraseArray.length());
for (int i = 0; i < phraseArray.length(); i++)
{
JSONObject job = phraseArray.getJSONObject(i);
int documentId =job.getInt("documentId");
int noOfOccurences=job.getInt("noOfOccurences");
String documentName=job.getString("documentName");
String phrase=job.getString("phrase");
//This i for Occurences array
ArrayList<PhraseModel.OccurenceDetails> occurencesList = new ArrayList<>();
JSONArray occurencesArray = job.getJSONArray("occurenceDetails");
for (int j = 0; j < occurencesArray.length(); j++) {
JSONObject jobIn = occurencesArray.getJSONObject(j);
int occurenceId=jobIn.getInt("occurenceId");
int pageNo=jobIn.getInt("pageNo");
String fullPhrase=jobIn.getString("fullPhrase");
occurencesList.add(new PhraseModel.OccurenceDetails(occurenceId, pageNo, fullPhrase));
}
//here your Phrase[] value store in pdfArrayList
phrase_Lists.add(new PhraseModel.PhraseList(documentId,documentName,phrase,noOfOccurences,occurencesList));
Log.i("phraseList size = ", ""+phraseArray.length());
}
if (phrase_Lists != null)
{
Log.i("phraseList size = ", ""+phraseArray.length());
}
return phrase_Lists;
}catch (JSONException e){
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("hipaJson.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
Logcat :
11-23 15:52:06.428 1519-2794/? E/ActivityManager: applyOptionsLocked: Unknown animationType=0
11-23 15:52:06.428 459-2412/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
11-23 15:52:07.059 29210-29210/? E/HAL: PATH3 /odm/lib64/hw/gralloc.qcom.so
11-23 15:52:07.059 29210-29210/? E/HAL: PATH2 /vendor/lib64/hw/gralloc.qcom.so
11-23 15:52:07.059 29210-29210/? E/HAL: PATH1 /system/lib64/hw/gralloc.qcom.so
11-23 15:52:07.059 29210-29210/? E/HAL: PATH3 /odm/lib64/hw/gralloc.msm8953.so
11-23 15:52:07.059 29210-29210/? E/HAL: PATH2 /vendor/lib64/hw/gralloc.msm8953.so
11-23 15:52:07.059 29210-29210/? E/HAL: PATH1 /system/lib64/hw/gralloc.msm8953.so
11-23 15:52:11.066 459-2412/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
11-23 15:52:11.152 29210-29210/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.hkcl.pdfsearchapp, PID: 29210
java.lang.ClassCastException: in.hkcl.pdfsearchapp.PhraseModel$PhraseList cannot be cast to java.util.ArrayList
at in.hkcl.pdfsearchapp.ExpandableListAdapter.getGroupView(ExpandableListAdapter.java:81)
at android.widget.ExpandableListConnector.getView(ExpandableListConnector.java:446)
at android.widget.AbsListView.obtainView(AbsListView.java:2367)
at android.widget.ListView.makeAndAddView(ListView.java:1972)
at android.widget.ListView.fillDown(ListView.java:704)
at android.widget.ListView.fillFromTop(ListView.java:765)
at android.widget.ListView.layoutChildren(ListView.java:1744)
at android.widget.AbsListView.onLayout(AbsListView.java:2161)
at android.view.View.layout(View.java:17548)
at android.view.ViewGroup.layout(ViewGroup.java:5614)
Please explain and help, what i am doing wrong?? The app has splashscreen > landingActivity containing expandable list which i am not able to show as app crashes giving class cat exception in getGroupView method.
list_group.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.CardView
android:id="#+id/parent_phraseList_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#BDBDBD"
app:cardElevation="4dp"
android:padding="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:padding="5dp">
<TextView
android:id="#+id/docNameLabel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Doc Name : "
android:textStyle="bold"/>
<TextView
android:id="#+id/docName"
android:layout_toRightOf="#id/docNameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/totalOccurencesLabel"
android:layout_below="#id/docNameLabel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Total Occurences : "
android:textStyle="bold"/>
<TextView
android:id="#+id/totalOccurences"
android:layout_toRightOf="#id/totalOccurencesLabel"
android:layout_below="#id/docNameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
<ImageButton
android:id="#+id/linkToDirectOpenDoc_btn"
android:layout_below="#id/totalOccurencesLabel"
android:layout_centerHorizontal="true"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/link"
android:elevation="6dp"
android:layout_marginTop="5dp"/>
<ImageButton
android:id="#+id/expandCard_btn"
android:layout_below="#id/totalOccurencesLabel"
android:layout_toRightOf="#id/linkToDirectOpenDoc_btn"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/expand"
android:elevation="6dp"
android:layout_marginTop="5dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:padding="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#FFFFFF">
<TextView
android:id="#+id/occurenceId_label"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Occurence : "
android:textStyle="bold"/>
<TextView
android:id="#+id/occurenceId"
android:layout_toRightOf="#id/occurenceId_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/fullPhrase_label"
android:layout_below="#id/occurenceId_label"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Full Phrase : "
android:textStyle="bold"
android:layout_marginTop="5dp"/>
<TextView
android:id="#+id/fullPhrase"
android:layout_below="#id/occurenceId_label"
android:layout_toRightOf="#id/fullPhrase_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
<TextView
android:id="#+id/pageNo_label"
android:layout_below="#id/fullPhrase_label"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Full Phrase : "
android:textStyle="bold"
android:layout_marginTop="5dp"/>
<TextView
android:id="#+id/pageNo"
android:layout_below="#id/fullPhrase_label"
android:layout_toRightOf="#id/pageNo_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Try replacing
ArrayList<PhraseModel.PhraseList> parentList = (ArrayList<PhraseModel.PhraseList>) getGroup(groupPosition);
by
PhraseList parentList = (PhraseList) getGroup(groupPosition);
This may help
//Change this
ArrayList<PhraseModel.PhraseList> parentList = (ArrayList<PhraseModel.PhraseList>) getGroup(groupPosition);
//To
PhraseModel.PhraseList mPhraseListItem = getGroup(groupPosition);
//AND getGroup return type to PhraseModel.PhraseList
public PhraseModel.PhraseList getGroup(int groupPosition) {
return this.mPhraseList.get(groupPosition);
}
Update As Per Requirement
I made Some Change In Your ExpandableListAdapter class. I made it as simple as possible. Just Copy and Paste This Class.
public class ExpandableListAdapter extends BaseExpandableListAdapter {
Context context;
ExpandableListView expandableListView;
private ArrayList<PhraseModel.PhraseList> mPhraseList;
private int lastExpandedPosition = -1;
public ExpandableListAdapter(Context context, ArrayList<PhraseModel.PhraseList> mPhraseList, ExpandableListView expandableListView) {
this.context = context;
this.mPhraseList = mPhraseList;
this.expandableListView = expandableListView;
}
public PhraseModel.OccurenceDetails getChild(int groupPosition, int childPosition){
return this.mPhraseList.get(groupPosition).getOccurenceDetails().get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final PhraseModel.OccurenceDetails occurenceDetails = getChild(groupPosition, childPosition);
if(convertView==null){
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView occurenceId,fullPhrase,pageNo;
occurenceId=(TextView)convertView.findViewById(R.id.occurenceId);
fullPhrase=(TextView)convertView.findViewById(R.id.fullPhrase);
pageNo=(TextView)convertView.findViewById(R.id.pageNo);
occurenceId.setText(String.valueOf(occurenceDetails.getOccurenceId()));
fullPhrase.setText(occurenceDetails.getFullPhrase());
pageNo.setText(String.valueOf(occurenceDetails.getPageNo()));
return convertView;
}
public int getChildrenCount(int groupPosition) {
return this.mPhraseList.get(groupPosition).getOccurenceDetails().size();
}
public PhraseModel.PhraseList getGroup(int groupPosition) {
return this.mPhraseList.get(groupPosition);
}
public int getGroupCount() {
return this.mPhraseList.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(final int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
PhraseModel.PhraseList parentList = getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView docName,totalOccurences;
docName=(TextView)convertView.findViewById(R.id.docName);
totalOccurences=(TextView)convertView.findViewById(R.id.totalOccurences);
docName.setText(parentList.getDocumentName());
totalOccurences.setText(String.valueOf(parentList.getNoOfOccurences()));
ImageButton linkToDirectOpenDoc_btn, expandCard_btn;
linkToDirectOpenDoc_btn = (ImageButton) convertView.findViewById(R.id.linkToDirectOpenDoc_btn);
linkToDirectOpenDoc_btn.setFocusable(false);
expandCard_btn = (ImageButton) convertView.findViewById(R.id.expandCard_btn);
expandCard_btn.setFocusable(false);
expandCard_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (lastExpandedPosition == groupPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
lastExpandedPosition = -1;
} else {
expandableListView.collapseGroup(lastExpandedPosition);
lastExpandedPosition = groupPosition;
expandableListView.expandGroup(lastExpandedPosition);
}
}
});
return convertView;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Then in your Activity put below code to set up adapters and array lists. This is just for your reference you have to make change it as per your need, so you can get this values from your assets.
//FIRST GROUP
PhraseModel.OccurenceDetails oneOccurenceDetails = new PhraseModel.OccurenceDetails(1, 20, "Occurence Details Pharse One");
ArrayList<PhraseModel.OccurenceDetails> firstOccurenceDetails = new ArrayList<>();
firstOccurenceDetails.add(oneOccurenceDetails);
PhraseModel.PhraseList onePhraseList = new PhraseModel.PhraseList(1,
"Doc One", "Pharse One", 10, firstOccurenceDetails);
//SECOND GROUP
PhraseModel.OccurenceDetails twoOccurenceDetails = new PhraseModel.OccurenceDetails(2, 30, "Occurence Details Pharse Second");
ArrayList<PhraseModel.OccurenceDetails> secondOccurenceDetails = new ArrayList<>();
secondOccurenceDetails.add(twoOccurenceDetails);
PhraseModel.PhraseList twoPhraseList = new PhraseModel.PhraseList(1,
"Doc Two", "Pharse Two", 10, secondOccurenceDetails);
ArrayList<PhraseModel.PhraseList> onePhraseArrayList = new ArrayList<>();
onePhraseArrayList.add(onePhraseList);
onePhraseArrayList.add(twoPhraseList);
ExpandableListAdapter expandableListAdapter = new ExpandableListAdapter(this, onePhraseArrayList, expandableListView);
expandableListView.setAdapter(expandableListAdapter);
Try this code,
public class ExpandableListMAdapter extends BaseExpandableListAdapter {
Context context;
public ArrayList<String> mPhraseList;
private HashMap<Integer,ArrayList<String>> occurenceList;
public ExpandableListMAdapter(Context context, ArrayList<String> mPhraseList, HashMap<Integer, ArrayList<String>> occurenceList) {
this.context = context;
this.mPhraseList = mPhraseList;
this.occurenceList = occurenceList;
}
public Object getChild(int groupPosition, int childPosition){
return this.occurenceList.get(this.mPhraseList.get(groupPosition)).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final ArrayList<String> childList = occurenceList.get(groupPosition);
if(convertView==null){
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtchild;
txtchild=(TextView)convertView.findViewById(R.id.txtchild);
txtchild.setText(childList.get(childPosition));
/* TextView occurenceId,fullPhrase,pageNo;
occurenceId=(TextView)convertView.findViewById(R.id.occurenceId);
fullPhrase=(TextView)convertView.findViewById(R.id.fullPhrase);
pageNo=(TextView)convertView.findViewById(R.id.pageNo);
occurenceId.setText(childList.get(groupPosition).getOccurenceId());
fullPhrase.setText(childList.get(groupPosition).getFullPhrase());
pageNo.setText(childList.get(groupPosition).getPageNo());*/
return convertView;
}
public int getChildrenCount(int groupPosition) {
return this.occurenceList.get(groupPosition).size(); }
public Object getGroup(int groupPosition) {
return this.mPhraseList.get(groupPosition);
}
public int getGroupCount() {
return this.mPhraseList.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ArrayList<String> parentList = mPhraseList;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView txtgroup;
txtgroup=(TextView)convertView.findViewById(R.id.txtgroup);
txtgroup.setText(parentList.get(groupPosition));
/* TextView docName,totalOccurences;
docName=(TextView)convertView.findViewById(R.id.docName);
totalOccurences=(TextView)convertView.findViewById(R.id.totalOccurences);
docName.setText(parentList.get(groupPosition).getDocumentName());
totalOccurences.setText(parentList.get(groupPosition).getNoOfOccurences());*/
return convertView;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
I'm new to Java, Android and SQLite, so quite frankly I'm amazed that I have gotten this far.
I am trying to create a simple cataloguing app for my bonsai collection which displays a summary of my collection in a RecyclerView on the MainActivity.
I've got the database working, in that I can add items to it (checked through DB Browser for SQLite). The trouble I'm having is displaying that data in the RecyclerView. Currently it is just showing the laucher icon placeholder image and not populating the TextViews with the data from the DB. The number of views that are showing in the RecyclerView correspond with the number of entries in the DB.
I'm not sure what I'm doing wrong, so any help would be greatly appreciated.
MainActivity.java
Datasource mDataSource;
Button btnAddNew;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataSource = new Datasource(this);
mDataSource.open();
List<DataModel> listFromDB = mDataSource.getAllItems();
DataItemAdapter adapter = new DataItemAdapter(this, listFromDB);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvItems);
recyclerView.setAdapter(adapter);
btnAddNew = (Button) findViewById(R.id.btnInsert);
}
DataModel.Java
public class DataModel {
private String itemId;
private String itemName;
private String itemCommonName;
public DataModel() {
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCommonName() {
return itemCommonName;
}
public void setItemCommonName(String itemCommonName) {
this.itemCommonName = itemCommonName;
}
Datasource.java
public class Datasource {
private Context mContext;
private SQLiteDatabase mDatabase;
SQLiteOpenHelper mDbHelper;
public Datasource(Context context){
this.mContext = context;
mDbHelper = new DatabaseHelper(mContext);
mDatabase = mDbHelper.getWritableDatabase();
}
public void open(){
mDatabase = mDbHelper.getWritableDatabase();
}
public void close(){
mDatabase.close();
}
public boolean insertData(String name, String commonName, String scientificName){
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_COMMON_NAME, commonName);
contentValues.put(COL_SCI_NAME, scientificName);
long result = db.insert(DATABASE_TABLE, null, contentValues);
db.close();
if(result == -1) {
return false;
}else{
return true;
}
}
public List<DataModel> getAllItems(){
List<DataModel> dataModels = new ArrayList<>();
Cursor cursor = mDatabase.query(DATABASE_TABLE, ItemsTable.ALL_COLUMNS,
null, null, null, null, null);
while (cursor.moveToNext()){
DataModel item = new DataModel();
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_ID)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_NAME)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_COMMON_NAME)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_SCI_NAME)));
dataModels.add(item);
}
return dataModels;
}
DataItemAdapter.java
public class DataItemAdapter extends RecyclerView.Adapter<DataItemAdapter.ViewHolder> {
private List<DataModel> mItems;
private Context mContext;
public DataItemAdapter(Context context, List<DataModel> items) {
this.mContext = context;
this.mItems = items;
}
#Override
public DataItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(DataItemAdapter.ViewHolder holder, int position) {
final DataModel item = mItems.get(position);
holder.tvName.setText(item.getItemName());
holder.tvCommonName.setText(item.getItemCommonName());
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName, tvCommonName;
public ImageView ivProfilePic;
public View mView;
public ViewHolder(View itemView){
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCommonName = (TextView) itemView.findViewById(R.id.tvCommonName);
ivProfilePic = (ImageView) itemView.findViewById(R.id.ivProfilePic);
mView = itemView;
}
}
RecyclerView object in activity_main.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/rvItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"/>
TextViews and Image view list_item.xml
<ImageView
android:id="#+id/ivProfilePic"
android:layout_width="75dp"
android:layout_height="75dp"
app:srcCompat="#mipmap/ic_launcher_round"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:contentDescription="Profile Pic"
tools:ignore="HardcodedText"/>
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="19dp"
android:layout_toEndOf="#+id/ivProfilePic"
android:text="TextView"
android:textSize="18sp"
android:visibility="visible"/>
<TextView
android:id="#+id/tvCommonName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView"
android:visibility="visible"/>
Screenshot of what the MainActivity currently looks like:
Any other information required, just ask and I'll try to post it up.
Sorted it out, seems so simple now that I look at it.
In the Cursor, I hadn't changed the item setters to the correct ones after I copied and pasted the first line, just the column names.
Also I was identifying the ID column as a string, where it should have been an integer - also updated this in the DataModel class
while (cursor.moveToNext()){
DataModel item = new DataModel();
item.setItemId(cursor.getInt(
cursor.getColumnIndex(ItemsTable.COL_ID)));
item.setItemName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_NAME)));
item.setItemCommonName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_COMMON_NAME)));
item.setItemSciName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_SCI_NAME)));
dataModels.add(item);
}
return dataModels;
}
I need help to make listview adapter. Below is code please make the adapter both value name with roomid.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
RoomModel.java
public class RoomModel {
private String name, id, roomid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getroomId() {
return roomid;
}
public void setroomId(String roomid) {
this.roomid = roomid;
}
}
try the following Adapter......
public class MyAdapter extends BaseAdapter {
Context con;
ArrayList<your type> mlist;
RoomModel sched;
public MyAdapter(Context con,ArrayList<your type> mlist )
{
this.con=con;
this.mlist=mlist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mlist.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mlist[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sched=mlist.get(position);
LayoutInflater inflater=(LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.your_layout,parent,false);
TextView tv1=(TextView)convertView.findViewById(R.id.your_textview);
tv1.setText(sched.getId());
TextView tv2=(TextView)convertView.findViewById(R.id.your_textview);
tv2.setText(sched.getName());
TextView tv3=(TextView)convertView.findViewById(R.id.your_textview);
tv3.setText(sched.getroomId());
return convertView;
}
}
and change the following code.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
MyAdapter adapter=new MyAdapter(this,CustomListViewValuesArr);
listView.setAdapter(adapter);
OK as requested by Sandeep, I will give you simple hint but I can't give you full codes that you can directly copy and paste. Just follow instructions
Create an XML file for single item of the list which may have certain elements as you need, for example It's single_item.xml which has 3 TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Sample Id"
android:textColor="#0414f4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="10sp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Sample Title"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sample body"
android:textSize="16sp"/>
</LinearLayout>
and after getting the reference of listView from main layout set the adapter like this, And here modelList is an ArrayList.
mAdapter = new CustomAdapter(MainActivity.this, R.layout.single_item, modelList);
mAdapter.notifyDataSetChanged();
mListView.setAdapter(mAdapter);
Then the class CustomAdapter looks like this
public class CustomAdapter extends ArrayAdapter<Model> {
ArrayList<Model> modelList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Model> objects) {
super(context, resource, objects);
this.modelList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.single_item,parent,false);
}
// Lookup view for data population
TextView tvId = (TextView) convertView.findViewById(R.id.tvId);
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvBody = (TextView) convertView.findViewById(R.id.tvBody);
// Populate the data into the template view using the data object
tvId.setText(String.valueOf(model.getId()));
tvTitle.setText(model.getroomId());
tvBody.setText(model.getName());
// Return the completed view to render on screen
return convertView;
}
}
NOTE : I have commented and made it simple as possible to help you. Hope this may help. You can comment if any problem raised.
I'm using drag-sort-listview to sort rows of my ListView, and I have created a demo using this library, but it is not working. When I try to drag rows it is not working.
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Strawberry",
"Banana", "Orange", "Mixed" };
public static final String[] descriptions = new String[] {
"It is an aggregate accessory fruit",
"It is the largest herbaceous flowering plant", "Citrus Fruit",
"Mixed Fruits" };
public static final Integer[] images = { R.drawable.drag,
R.drawable.drag, R.drawable.drag, R.drawable.drag };
//ListView listView;
DragSortListView listView;
List<RowItem> rowItems;
CustomListViewAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (DragSortListView) findViewById(R.id.listview);
//listView = (ListView) findViewById(R.id.list);
final CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setDropListener(new DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
//DragSortListView list = getListView();
RowItem item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
listView.moveCheckState(from, to);
//Log.d("DSLV", "Selected item is " + listView.getCheckedItemPosition());
}
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dslv="http://schemas.android.com/apk/res/com.example.testingui"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.mobeta.android.dslv.DragSortListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="5dp"
dslv:collapsed_height="2dp"
dslv:drag_enabled="true"
dslv:drag_handle_id="#drawable/drag"
dslv:drag_scroll_start="0.33"
dslv:drag_start_mode="onMove"
dslv:float_alpha="0.6"
dslv:max_drag_scroll_speed="0.5"
dslv:remove_enabled="true"
dslv:remove_mode="flingRemove"
dslv:slide_shuffle_speed="0.3"
dslv:sort_enabled="true"
dslv:track_drag_sort="true"
dslv:use_default_controller="true" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descs);
holder.txtTitle = (TextView) convertView.findViewById(R.id.titles);
holder.imageView = (ImageView) convertView.findViewById(R.id.icons);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icons"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/titles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icons"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/descs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titles"
android:layout_toRightOf="#+id/icons"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
RowItem.java
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
Use Drag handle Id in DragSortListView tag in Xml
dslv:drag_handle_id="#id/drag_handle"
Make an id.xml file and put drag handle id as above to make it common and use the same id on dragable handle image view in your row item.
Hope it helps.