How to show arraylist data in recyclerview? - java

I have an ArrayList with repeated data, I want to show the first 5 items in the first row of recyclerview then the second 5 items in the second row, and so on. How can I achieve this in Recyclerview?
Arraylist: [2013-04-01, OB Int. Updated upto 31/03/2013, 0, 0, 0,
2013-09-10, Cont. For Due-Month 082013, 780, 239, 541, 2014-03-28,
Cont. For Due-Month 032014, 780, 239, 541, 2014-02-03, Cont. For
Due-Month 012014, 780, 239, 541, 2013-07-26, Cont. For Due-Month
072013, 780, 239, 541]
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> {
private AppCompatActivity activity;
List<String> data = new ArrayList();
private LayoutInflater inflater;
class MyViewHolder extends RecyclerView.ViewHolder {
private final View saparator;
private final TextView txtLabel;
public MyViewHolder(View itemView) {
super(itemView);
this.txtLabel = (TextView) itemView.findViewById(R.id.detail_parameter);
this.saparator = itemView.findViewById(R.id.detail_value);
}
}
public DataAdapter(AppCompatActivity activity, List<String> data) {
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
this.data = data;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(this.inflater.inflate(R.layout.pfpassbook_item, parent, false));
}
#SuppressLint("WrongConstant")
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtLabel.setText((CharSequence) this.data.get(position));
holder.txtLabel.setTextSize(15.0f);
holder.txtLabel.setTextColor(this.activity.getResources().getColor(R.color.colorAccent));
}
public int getItemCount() {
return this.data.size();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView rcList;
public String platenum = null;
RelativeLayout idForSaveView;
public static ArrayList<String> statement;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.pfpassbook);
statement = (ArrayList<String>) getIntent().getSerializableExtra("statement");
setView();
idForSaveView = (RelativeLayout) findViewById(R.id.relate);
}
private void setView() {
this.rcList = (RecyclerView) findViewById(R.id.detail_recyclerview);
this.rcList.setLayoutManager(new GridLayoutManager(this, 5));
this.rcList.setHasFixedSize(true);
this.rcList.setAdapter(new DataAdapter(DetailActivity.this, statement));
}
}
pfpassbook_item.xml
<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="0dp"
app:cardElevation="0dp"
app:cardBackgroundColor="#android:color/transparent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/design_default_color_error"
android:orientation="horizontal">
<TextView
android:id="#+id/detail_parameter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingTop="2dp"
android:paddingBottom="2dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>

First of all you shouldn't be in this kind of situation.
You can fix it BY converting this data to some ArrayList of Objects where object will hold 5 values .
This is just to get you started and give you idea.
import java.util.ArrayList;
public class HelloWorld {
public static class Model {
String value1;
String value2;
String value3;
String value4;
String value5;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
public String getValue3() {
return value3;
}
public void setValue3(String value3) {
this.value3 = value3;
}
public String getValue4() {
return value4;
}
public void setValue4(String value4) {
this.value4 = value4;
}
public String getValue5() {
return value5;
}
public void setValue5(String value5) {
this.value5 = value5;
}
#Override
public String toString() {
return "Model{" +
"value1='" + value1 + '\'' +
", value2='" + value2 + '\'' +
", value3='" + value3 + '\'' +
", value4='" + value4 + '\'' +
", value5='" + value5 + '\'' +
'}';
}
}
public static void main(String[] args) {
System.out.println("Hello World");
String a[] = {"2013-04-01", "OBInt.Updatedupto31/03/2013", "0", "0", "0", "2013-09-10", "Cont.ForDue-Month082013", "780", "239", "541", "2014-03-28", "Cont.ForDue-Month032014", "780", "239", "541", "2014-02-03", "Cont.ForDue-Month012014", "780", "239", "541", "2013-07-26", "Cont.ForDue-Month072013", "780", "239", "541"};
ArrayList<Model> arrayList = new ArrayList<>();
for (int i = 0; i < a.length ; i = i + 5) {
Model m = new Model();
m.setValue1(a[i]);
m.setValue2(a[i + 1]);
m.setValue3(a[i + 2]);
m.setValue4(a[i + 3]);
m.setValue5(a[i + 4]);
arrayList.add(m);
}
System.out.println(arrayList.size() + "");
for(int i =0 ;i<arrayList.size();i++){
System.out.println(arrayList.get(i));
}
}
}
Provided that the size of the array will be in multiple of 5.
For me cleaning the data before setting to recyclerView is a good way to go as you can catch the errors before setting it on recyclerView.
Also by doing this you can use it in CustomAdapter to make desired View for your Items.
UPDATE 1:
DataAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> {
private AppCompatActivity activity;
ArrayList<Model> data = new ArrayList();
private LayoutInflater inflater;
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView)itemView.findViewById( R.id.textView );
textView2 = (TextView)itemView.findViewById( R.id.textView2 );
textView3 = (TextView)itemView.findViewById( R.id.textView3 );
textView4 = (TextView)itemView.findViewById( R.id.textView4 );
textView5 = (TextView)itemView.findViewById( R.id.textView5 );
}
}
public DataAdapter(AppCompatActivity activity, ArrayList<Model> data) {
this.activity = activity;
this.inflater = LayoutInflater.from(activity);
this.data = data;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(this.inflater.inflate(R.layout.pfpassbook_item, parent, false));
}
public void onBindViewHolder(MyViewHolder holder, int position) {
Model m = data.get(position);
holder.textView.setText(m.getValue1());
holder.textView2.setText(m.getValue2());
holder.textView3.setText(m.getValue3());
holder.textView4.setText(m.getValue4());
holder.textView5.setText(m.getValue5());
}
public int getItemCount() {
return this.data.size();
}
}
setViewMethod:
private void setView() {
this.rcList = (RecyclerView) findViewById(R.id.detail_recyclerview);
this.rcList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL,false));
this.rcList.setHasFixedSize(true);
String[] a = {"2013-04-01", "OBInt.Updatedupto31/03/2013", "0", "0", "0", "2013-09-10", "Cont.ForDue-Month082013", "780", "239", "541", "2014-03-28", "Cont.ForDue-Month032014", "780", "239", "541", "2014-02-03", "Cont.ForDue-Month012014", "780", "239", "541", "2013-07-26", "Cont.ForDue-Month072013", "780", "239", "541"};
ArrayList<Model> arrayList = new ArrayList<>();
for (int i = 0; i < a.length ; i = i + 5) {
Model m = new Model();
m.setValue1(a[i]);
m.setValue2(a[i + 1]);
m.setValue3(a[i + 2]);
m.setValue4(a[i + 3]);
m.setValue5(a[i + 4]);
arrayList.add(m);
}
this.rcList.setAdapter(new DataAdapter(this, arrayList));
}
Model Class :
public class Model {
String value1;
String value2;
String value3;
String value4;
String value5;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
public String getValue3() {
return value3;
}
public void setValue3(String value3) {
this.value3 = value3;
}
public String getValue4() {
return value4;
}
public void setValue4(String value4) {
this.value4 = value4;
}
public String getValue5() {
return value5;
}
public void setValue5(String value5) {
this.value5 = value5;
}
#Override
public String toString() {
return "Model{" +
"value1='" + value1 + '\'' +
", value2='" + value2 + '\'' +
", value3='" + value3 + '\'' +
", value4='" + value4 + '\'' +
", value5='" + value5 + '\'' +
'}';
}
}
pfpassbook_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView4"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:id="#+id/textView5"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
You can design pfpassbook_item any way you want. always bind your data in Array of objects instead of adding one by one in the array.

You can use spanCount for showing desired quantity of items in a row like this
layoutManager!!.spanCount = 5
And in XML inside your recyclerview like this
app:spanCount="5"

You can use StaggeredGridLayoutManager as the layout of recyclerview
XML
<androidx.recyclerview.widget.RecyclerView
android:id="+#id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
app:spanCount="5" />
Here spanCount defines the number of items you want to display in a row
If you want to define using class
val layoutManager = StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL)
recyclerView.layoutManager = layoutManager

Related

Android autocompletetextview dropdown not showing

I am facing an issue of autocompletetextview dropdown not showing when searching dynamically from Sqlite database. Below is my code.
Any help would be grateful. Thanks
activity_list.xml
<LinearLayout 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"
android:orientation="vertical"
tools:context=".List">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:orientation="vertical"
android:paddingTop="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:textColor="#color/purple_500"
android:layout_gravity="right"
android:layout_marginEnd="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_weight="1"
android:src="#drawable/bullets" />
<AutoCompleteTextView
android:id="#+id/actvItems"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:hint="Add your item here"
android:layout_weight="5"
android:textColor="#color/black" />
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:hint="Quantity"
android:layout_weight="3"
android:textColor="#color/black"
android:background="#drawable/rounded_black_stroke"
android:padding="10dp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="x3"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.3"
android:orientation="horizontal"
android:paddingTop="30dp"
android:background="#drawable/bottom_nav_bg">
<LinearLayout
android:id="#+id/icon_list"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:onClick="list"
android:orientation="vertical">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/icon_list"
app:tint="#color/purple_500" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MY LIST"
android:textColor="#color/purple_500"/>
</LinearLayout>
<LinearLayout
android:id="#+id/icon_home"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:onClick="home"
android:orientation="vertical">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/icon_home2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HOME" />
</LinearLayout>
<LinearLayout
android:id="#+id/icon_profile"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:onClick="profile"
android:orientation="vertical">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/icon_person" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MY PROFILE" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
items_drop_down dropdown layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="15dp"
android:background="#F9F6FF">
<TextView
android:id="#+id/tvBrand"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Product Brand"
android:textAllCaps="true"
android:textSize="12sp"/>
<TextView
android:id="#+id/tvItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Product Name"
android:textSize="18sp"
android:textColor="#color/black"/>
</LinearLayout>
itemsList Model class
public class ItemsList {
int item_id;
String item, brand;
public ItemsList() {
this.item_id = item_id;
this.item = item;
this.brand = brand;
}
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
Sqlite Database class AnnapurnaDB
public class AnnapurnaDB {
private static final String db_name = "annapurnadb";
private static final String tbl_items = "items";
private static final String tbl_user_items = "user_items";
private static final String tbl_user_items_tmp = "user_items_tmp";
private static final String tbl_user_items_inventory = "user_items_inventory";
private static final int db_version = 1;
public static final String item_id = "item_id";
public static final String brand = "brand";
public static final String item_desc = "item_desc";
public static final String item_size = "item_size";
public static final String item_type = "item_type";
public static final String weight = "weight";
public static final String mrp = "mrp";
public static final String item = "item";
public static final String user_id = "user_id";
public static final String avg_days = "avg_days";
public static final String avg_quantity = "avg_quantity";
public static final String status = "status";
public static final String purchase_date = "purchase_date";
public static final String date_added = "date_added";
public static final String unit = "unit";
public static final String quantity = "quantity";
public static final String manufacturing_date = "manufacturing_date";
public static final String expiry_date = "expiry_date";
public static final String exhaust_date = "exhaust_date";
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public AnnapurnaDB(Context context) {
this.ourContext = context;
}
private class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context){
super(context, db_name, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String sqlCreateItems = "CREATE TABLE " + tbl_items + " (" +
item_id + " INTEGER, " +
brand + " TEXT NOT NULL, " +
item_desc + " TEXT NOT NULL, " +
item_size + " TEXT DEFAULT NULL, " +
item_type + " TEXT DEFAULT NULL, " +
weight + " TEXT DEFAULT NULL, " +
mrp + " TEXT DEFAULT NULL, " +
item + " TEXT DEFAULT NULL);";
String sqlCreateUserItems = "CREATE TABLE " + tbl_user_items + " (" +
user_id + " INTEGER NOT NULL, " +
item_id + " INTEGER NOT NULL, " +
avg_days + " INTEGER DEFAULT NULL, " +
avg_quantity + " INTEGER DEFAULT NULL, " +
status + " TEXT DEFAULT NULL, " +
purchase_date + " DATE DEFAULT NULL, " +
date_added + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP);";
String sqlCreateUserItemsTmp = "CREATE TABLE " + tbl_user_items_tmp + " (" +
item_id + " INTEGER NOT NULL, " +
avg_days + " INTEGER DEFAULT NULL, " +
avg_quantity + " INTEGER DEFAULT NULL, " +
status + " TEXT DEFAULT NULL, " +
purchase_date + " DATE DEFAULT NULL, " +
date_added + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP);";
String sqlCreateUserItemsInventory = "CREATE TABLE " + tbl_user_items_inventory + " (" +
user_id + " INTEGER NOT NULL, " +
item_id + " INTEGER NOT NULL, " +
unit + " TEXT DEFAULT NULL, " +
quantity + " TEXT DEFAULT NULL, " +
manufacturing_date + " TEXT DEFAULT NULL, " +
expiry_date + " TEXT DEFAULT NULL, " +
purchase_date + " DATE DEFAULT NULL, " +
exhaust_date + " DATE DEFAULT NULL);";
sqLiteDatabase.execSQL(sqlCreateItems);
sqLiteDatabase.execSQL(sqlCreateUserItems);
sqLiteDatabase.execSQL(sqlCreateUserItemsTmp);
sqLiteDatabase.execSQL(sqlCreateUserItemsInventory);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
public AnnapurnaDB open() throws SQLException {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public void insertItems(String item_id_v, String brand_v, String item_desc_v, String item_size_v, String item_type_v, String weight_v, String mrp_v, String item_v){
ContentValues contentValues = new ContentValues();
contentValues.put(item_id, item_id_v);
contentValues.put(brand, brand_v);
contentValues.put(item_desc, item_desc_v);
contentValues.put(item_size, item_size_v);
contentValues.put(item_type, item_type_v);
contentValues.put(weight, weight_v);
contentValues.put(mrp, mrp_v);
contentValues.put(item, item_v);
ourDatabase.insert(tbl_items, null, contentValues);
}
public Cursor getAllItems(){
return ourDatabase.rawQuery("SELECT * FROM " + tbl_items, null);
}
public List<ItemsList> search(String keyword){
List<ItemsList> itemsLists = null;
Cursor cursor = ourDatabase.rawQuery("SELECT item_id, brand, item FROM " + tbl_items + " WHERE " + item + " LIKE ?", new String[] {"%" + keyword + "%"} );
if(cursor.moveToFirst()){
itemsLists = new ArrayList<ItemsList>();
do{
ItemsList itemsList = new ItemsList();
itemsList.setItem_id(cursor.getInt(0));
itemsList.setBrand(cursor.getString(1));
itemsList.setItem(cursor.getString(2));
}while (cursor.moveToNext());
}
return itemsLists;
}
}
ItemSearchAdapter
public class ItemSearchAdapter extends ArrayAdapter<ItemsList> {
private Context context;
private int LIMIT = 5;
private List<ItemsList> itemsLists;
public ItemSearchAdapter(Context context, List<ItemsList> itemsLists){
super(context, R.layout.items_drop_down, itemsLists);
this.context = context;
this.itemsLists = itemsLists;
}
#Override
public int getCount(){
return Math.min(LIMIT, itemsLists.size());
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.items_drop_down, null);
ItemsList itemsList = itemsLists.get(position);
TextView tvBrand = view.findViewById(R.id.tvBrand);
TextView tvItem = view.findViewById(R.id.tvItem);
tvBrand.setText(itemsList.getBrand());
tvItem.setText(itemsList.getItem());
return view;
}
#NonNull
#Override
public Filter getFilter() {
return new ItemFilter(this, context);
}
private class ItemFilter extends Filter {
private ItemSearchAdapter itemSearchAdapter;
private Context context;
public ItemFilter(ItemSearchAdapter itemSearchAdapter, Context context){
super();
this.itemSearchAdapter = itemSearchAdapter;
this.context = context;
}
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
itemSearchAdapter.itemsLists.clear();
FilterResults filterResults = new FilterResults();
if(charSequence == null || charSequence.length() == 0){
filterResults.values = new ArrayList<ItemsList>();
filterResults.count = 0;
}else{
AnnapurnaDB annapurnaDB = new AnnapurnaDB(context);
annapurnaDB.open();
List<ItemsList> itemsLists = annapurnaDB.search(charSequence.toString());
filterResults.values = itemsLists;
filterResults.count = itemsLists.size();
annapurnaDB.close();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemSearchAdapter.itemsLists.clear();
if(filterResults.values != null && filterResults.count > 0) {
itemSearchAdapter.itemsLists.addAll((List<ItemsList>) filterResults.values);
itemSearchAdapter.notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
ItemsList itemsList = (ItemsList) resultValue;
return itemsList.getItem();
}
}
}
Item List Activity
public class List extends AppCompatActivity {
AutoCompleteTextView actvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
actvItems = findViewById(R.id.actvItems);
java.util.List<ItemsList> itemsLists = new ArrayList<ItemsList>();
ItemSearchAdapter itemSearchAdapter = new ItemSearchAdapter(getApplicationContext(), itemsLists);
actvItems.setThreshold(1);
actvItems.setAdapter(itemSearchAdapter);
}
public void list(View view) {
startActivity(new Intent(List.this, List.class));
}
public void home(View view) {
startActivity(new Intent(List.this, Home.class));
}
public void profile(View view) {
startActivity(new Intent(List.this, MyProfile.class));
}
}

How to implement "favourite" button feature (like favourite recipe/food) and display on another list in another fragment

I want to have a feature that when the user clicked the button on a certain row, it will add the row to another list which is called favorite list. Currently i have created database that also include favourite status. I already tried to start with creating a button that when its clicked it will change the fav status.
Im still new on android studio, just learnt for half a month. So go easy on me. I am currently stuck on this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 13778
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.myapplication.data.DatabaseHandler.addRecipe(com.example.myapplication.model.Recipe)' on a null object reference
at com.example.myapplication.adapter.RecyclerViewAdapter$ViewHolder$1.onClick(RecyclerViewAdapter.java:123)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Recipe.java
public class Recipe {
private int id;
private String name;
private String description;
private String ingredient;
private int image;
private String favStatus;
public Recipe() {
}
public Recipe(int id, String name, String description, String ingredient, int image, String favStatus) {
this.id = id;
this.name = name;
this.description = description;
this.ingredient = ingredient;
this.image = image;
this.favStatus = favStatus;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredient() {
return ingredient;
}
public void setIngredient(String ingredient) {
this.ingredient = ingredient;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getFavStatus() {
return favStatus;
}
public void setFavStatus(String favStatus) {
this.favStatus = favStatus;
}
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, Util.DATABASE_NAME, null, Util.DATABASE_VERSION);
}
//We create our table..
#Override
public void onCreate(SQLiteDatabase db) {
//SQL- Structured Query Language
/*
create table _name(id, name, desc, ingredient, image);
*/
String CREATE_CONTACT_TABLE = "CREATE TABLE " + Util.TABLE_NAME + "("
+ Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT,"
+ Util.KEY_DESCRIPTION + " TEXT," + Util.KEY_INGREDIENT + " TEXT,"
+ Util.KEY_IMAGE + " BLOB," + Util.KEY_FAV_STATUS + " TEXT" + ")";
db.execSQL(CREATE_CONTACT_TABLE); //Creating our table..
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE = String.valueOf(R.string.db_drop);
db.execSQL(DROP_TABLE, new String[]{Util.DATABASE_NAME});
//Create table again
onCreate(db);
}
//Add Recipe
public void addRecipe(Recipe recipe) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME, recipe.getName());
values.put(Util.KEY_DESCRIPTION, recipe.getDescription());
values.put(Util.KEY_INGREDIENT, recipe.getIngredient());
values.put(Util.KEY_IMAGE, recipe.getImage());
values.put(Util.KEY_FAV_STATUS, recipe.getFavStatus());
//Insert into row..
db.insert(Util.TABLE_NAME, null, values);
Log.d("DBHandler", "addRecipe: " + "item added");
db.close();
}
//Get a recipe
public Recipe getRecipe(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Util.TABLE_NAME,
new String[] { Util.KEY_ID, Util.KEY_NAME, Util.KEY_DESCRIPTION, Util.KEY_FAV_STATUS,
Util.KEY_INGREDIENT, Util.KEY_IMAGE}, Util.KEY_ID +"=?",
new String[]{String.valueOf(id)},
null, null, null);
if (cursor != null)
cursor.moveToFirst();
Recipe recipe = new Recipe();
recipe.setId(Integer.parseInt(cursor.getString(0)));
recipe.setName(cursor.getString(1));
recipe.setDescription(cursor.getString(2));
recipe.setIngredient(cursor.getString(3));
recipe.setImage(Integer.parseInt(cursor.getString(4)));
recipe.setFavStatus(cursor.getString(5));
return recipe;
}
//Get all Recipes
public List<Recipe> getAllRecipes() {
List<Recipe> recipeList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//Select all recipes
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll, null);
//Loop through our data
if (cursor.moveToFirst()) {
do {
Recipe recipe = new Recipe();
recipe.setId(Integer.parseInt(cursor.getString(0)));
recipe.setName(cursor.getString(1));
recipe.setDescription(cursor.getString(2));
recipe.setIngredient(cursor.getString(3));
recipe.setImage(Integer.parseInt(cursor.getString(4)));
recipe.setFavStatus((cursor.getString(5)));
//add recipe objects to our list
recipeList.add(recipe);
}while (cursor.moveToNext());
}
return recipeList;
}
//Update recipe
public int updateRecipe (Recipe recipe) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Util.KEY_NAME, recipe.getName());
values.put(Util.KEY_DESCRIPTION, recipe.getDescription());
values.put(Util.KEY_INGREDIENT, recipe.getIngredient());
values.put(Util.KEY_IMAGE, recipe.getImage());
values.put(Util.KEY_FAV_STATUS, recipe.getFavStatus());
//Update the row
return db.update(Util.TABLE_NAME, values, Util.KEY_ID + "=?",
new String[]{String.valueOf(recipe.getId())});
}
//Delete single recipe
public void deleteRecipe(Recipe recipe) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Util.TABLE_NAME, Util.KEY_ID + "=?",
new String[]{String.valueOf(recipe.getId())});
db.close();
}
//Select all favorite list method.
public List<Recipe> getAllFavRecipes() {
List<Recipe> recipeList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
//Select all recipes
String selectAll = "SELECT * FROM " + Util.TABLE_NAME + " WHERE " + Util.KEY_FAV_STATUS + " ='1'";
Cursor cursor = db.rawQuery(selectAll, null);
//Loop through our data
if (cursor.moveToFirst()) {
do {
Recipe recipe = new Recipe();
recipe.setId(Integer.parseInt(cursor.getString(0)));
recipe.setName(cursor.getString(1));
recipe.setDescription(cursor.getString(2));
recipe.setIngredient(cursor.getString(3));
recipe.setImage(Integer.parseInt(cursor.getString(4)));
recipe.setFavStatus((cursor.getString(5)));
//add recipe objects to our list
recipeList.add(recipe);
}while (cursor.moveToNext());
}
return recipeList;
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable{
private Context context;
private List<Recipe> recipeList;
private List<Recipe> recipeListFull;
private DatabaseHandler db;
public RecyclerViewAdapter(Context context, List<Recipe> recipeList) {
this.context = context;
this.recipeList = recipeList;
recipeListFull = new ArrayList<>(recipeList);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recipe_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
Recipe recipe = recipeList.get(position); //each recipe object inside of our list
viewHolder.recipeName.setText(recipe.getName());
viewHolder.description.setText(recipe.getDescription());
viewHolder.image.setImageResource(recipe.getImage());
}
#Override
public int getItemCount() {
return recipeList.size();
}
#Override
public Filter getFilter() {
return filterRecipe;
}
private Filter filterRecipe = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String searchText = charSequence.toString().toLowerCase();
List<Recipe> tempList = new ArrayList<>();
if(searchText.length()==0 | searchText.isEmpty()) {
tempList.addAll(recipeListFull);
}else {
for (Recipe item:recipeListFull) {
if (item.getName().toLowerCase().contains(searchText)) {
tempList.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tempList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
recipeList.clear();
recipeList.addAll((Collection<? extends Recipe>) filterResults.values);
notifyDataSetChanged();
}
};
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView recipeName;
public TextView description;
public ImageView image;
public ImageView favBtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
recipeName = itemView.findViewById(R.id.name);
description = itemView.findViewById(R.id.description);
image = itemView.findViewById(R.id.recipe_imageView);
favBtn = itemView.findViewById(R.id.fav_image_btn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Recipe recipe = recipeList.get(position);
if (recipe.getFavStatus().equals("0")) {
recipe.setFavStatus("1");
db.addRecipe(recipe);
favBtn.setImageResource(R.drawable.favourite_star);
} else {
recipe.setFavStatus("0");
db.deleteRecipe(recipe);
favBtn.setImageResource(R.drawable.shadow_fav_star);
}
}
});
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipe = recipeList.get(position);
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("name", recipe.getName());
intent.putExtra("description", recipe.getDescription());
intent.putExtra("ingredient", recipe.getIngredient());
intent.putExtra("image", recipe.getImage());
context.startActivity(intent);
//Log.d("Clicked", "onClick: " + recipe.getName());
}
}
//Create method to read and check for fav status for every row..
}
recipeRow.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/row_cardView"
android:layout_width="0dp"
android:layout_height="150dp"
android:layout_marginStart="1dp"
android:layout_marginTop="2dp"
android:layout_marginEnd="1dp"
app:cardCornerRadius="15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<ImageView
android:id="#+id/recipe_imageView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginStart="3dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="12dp"
android:ellipsize="end"
android:fontFamily="#font/courgette"
android:maxLines="2"
android:text="Title Text"
android:textColor="#color/darker"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.007"
app:layout_constraintStart_toEndOf="#+id/recipe_imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ellipsize="end"
android:maxLines="3"
android:text="Desc Text"
android:textSize="13sp"
android:textColor="#color/darkGray"
app:layout_constraintBottom_toTopOf="#+id/fav_image_btn"
app:layout_constraintEnd_toEndOf="#+id/name"
app:layout_constraintStart_toStartOf="#+id/name"
app:layout_constraintTop_toBottomOf="#+id/name" />
<ImageView
android:id="#+id/fav_image_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="25dp"
android:layout_marginBottom="7dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/favourite_star" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
The following error can occur when you try to use object which is not initialised before using it. means it's in null state, as you can see your db object in RecyclerViewAdapter is not initialised.
to solve this just initialised the object before using it or check if it's not null.
in you case just do as
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable{
....
private DatabaseHandler db; // object declared here
public RecyclerViewAdapter(Context context, List<Recipe> recipeList) {
this.context = context;
this.recipeList = recipeList;
recipeListFull = new ArrayList<>(recipeList);
db = new DatabaseHandler(context); // db object initialised here
}
....
}

Recycler View with multiple adapter and viewtype not working

This is my required prototype:
What result I am getting
I am trying this with multiple viewtype in single RecylerView but I am not getting required result. And not getting what logic need to write if using getItemViewType(). Please help me out
This is JSON Data which I want to implement into RecylerView
{
"rows": [{
"sequence_id":1,
"sequence_description":"animal description goes here",
"sequence_image":"thumbnail.png",
"sequence_title": "Animal",
"child_rows":[
{
"id": "1",
"name":"Lion",
"description" : "lion description goes here",
"image": "Lion.png"
},
{
"id": "2",
"name":"Tiger",
"description" : "Tiger description goes here",
"image": "Tiger.png"
},
{
"id": "3",
"name":"Elephant",
"description" : "Elephant description goes here",
"image": "Elephant.png"
}
]
},
{
"sequence_id":2,
"sequence_description":"animal description goes here",
"sequence_image":"thumbnail.png",
"sequence_title": "Birds",
"child_rows":[
{
"id": "1",
"name":"Parrot",
"description" : "Parrot description goes here",
"image": "parrot.png"
},
{
"id": "2",
"name":"Pigeon",
"description" : "Pigeon description goes here",
"image": "Pigeon.png"
},
{
"id": "3",
"name":"Crow",
"description" : "Crow description goes here",
"image": "crow.png"
}
]
}
]
}
Activity.java
mrecyclerview = (RecyclerView) findViewById(R.id.recyclerView);
try {
JSONObject jsonObj = new JSONObject(dataStr.getJsonString());
JSONArray jsondata = jsonObj.getJSONArray("rows");
for(int i = 0;i<jsondata.length();i++){
JSONObject rowsdata = jsondata.getJSONObject(i);
Integer sequence_id = rowsdata.getInt("sequence_id");
String sequence_description = rowsdata.getString("sequence_description");
String sequence_image = rowsdata.getString("sequence_image");
String sequence_title = rowsdata.getString("sequence_title");
List<ScreenOneInventory> minventorylist = new ArrayList<ScreenOneInventory>();
ScreenOneRows soRows = new ScreenOneRows();
JSONArray childres = rowsdata.getJSONArray("child_rows");
for(int j =0;j<childres.length();j++){
JSONObject inventorydata = childres.getJSONObject(j);
Log.i("Fragment","I am here in loop j:"+j);
String id = inventorydata.getString("id");
String name = inventorydata.getString("name");
String description = inventorydata.getString("description");
String image = inventorydata.getString("image");
ScreenOneInventory soinventoryObj = new ScreenOneInventory();
soinventoryObj.setId(id);
soinventoryObj.setname(name);
soinventoryObj.setDescription(description);
soinventoryObj.setImage(image);
minventorylist.add(soinventoryObj);
}
soRows.setSequence_id(sequence_id);
soRows.setSequence_Description(sequence_description);
soRows.setSequence_image(sequence_image);
soRows.setSop_title(sequence_title);
soRows.setInventoryList(minventorylist);
RowsData.add(soRows);
}
} catch (JSONException e) {
e.printStackTrace();
}
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
ScreenOneAdapter adapter = new ScreenOneAdapter(getActivity(),RowsData,mrecyclerview);
mrecyclerview.setAdapter(adapter);
}
This is My Parent Rows adapter ScreenOneAdapter.java
public class ScreenOneAdapter extends RecyclerView.Adapter<ScreenOneAdapter.BaseViewHolder> {
private LayoutInflater mInflater;
private List<ScreenOneRows> mRowsList;
public static final int PARENT_VIEW = 0;
public static final int CHILD_VIEW = 1;
private RecyclerView recyclerView;
private Context mcontext;
public ScreenOneAdapter(Context context, List<ScreenOneRows> mRowsList, RecyclerView mrecyclerview) {
this.mInflater = LayoutInflater.from(context);
this.mRowsList = mRowsList;
this.recyclerView = mrecyclerview;
this.mcontext = context;
}
#Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
view = mInflater.inflate(R.layout.list_item_rows,parent,false);
RowsListHolder rowHolder = new RowsListHolder(view);
return rowHolder;
}
#Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
ScreenOneRows current = mRowsList.get(position);
RowsListHolder rHolder = (RowsListHolder) holder;
rHolder.setData(current);
List mInventoryList = current.getInventoryList();
InventoryListAdapter iadapter = new InventoryListAdapter(mcontext,mInventoryList);
recyclerView.setAdapter(iadapter);
}
#Override
public int getItemCount() {
return (null != mRowsList ? mRowsList.size() : 0);
}
public class BaseViewHolder extends RecyclerView.ViewHolder{
public BaseViewHolder(View itemView) {
super(itemView);
}
}
public class RowsListHolder extends BaseViewHolder{
private ImageView icon;
private TextView title;
private TextView description;
public RowsListHolder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.img_icon);
title = (TextView) itemView.findViewById(R.id.tvTitle);
description = (TextView) itemView.findViewById(R.id.tvDescription);
}
public void setData(ScreenOneRows current){
this.title.setText(current.getSequence_title());
this.description.setText(current.getSequence_description());
}
}
}
This is my child rows adapter InventoryListAdapter.java
public class InventoryListAdapter extends RecyclerView.Adapter<InventoryListAdapter.InventoryListHolder> {
private List<ScreenOneInventory> mInventoryList;
private LayoutInflater mInflater;
public InventoryListAdapter(Context context, List<ScreenOneInventory> mInventoryList) {
this.mInventoryList = mInventoryList;
this.mInflater = LayoutInflater.from(context);
}
#Override
public InventoryListAdapter.InventoryListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView;
rootView = mInflater.inflate(R.layout.list_item_inventory,parent,false);
InventoryListHolder invHolder = new InventoryListHolder(rootView);
return invHolder;
}
#Override
public void onBindViewHolder(InventoryListAdapter.InventoryListHolder holder, int position) {
ScreenOneInventory currentInv = mInventoryList.get(position);
InventoryListHolder invenHolder = (InventoryListHolder) holder;
invenHolder.setData(currentInv);
}
#Override
public int getItemCount() {
return (null != mInventoryList ? mInventoryList.size() : 0);
}
public class InventoryListHolder extends RecyclerView.ViewHolder {
private ImageView imgicon;
private TextView title;
private TextView description;
public InventoryListHolder(View itemView) {
super(itemView);
imgicon = (ImageView) itemView.findViewById(R.id.img_inv_icon);
title = (TextView) itemView.findViewById(R.id.titletxt);
description = (TextView) itemView.findViewById(R.id.descriptiontxt);
}
public void setData(ScreenOneInventory data) {
this.title.setText(data.getName());
this.status.setText(data.getDescription());
}
}
}
There is no need to create the Two different adapter You can use two different item layout in case of Row and child.
you need to create One common list view with a extra info like this value is row value or child value.
if row value is true inflate the item_row.xml
if row value is false inflate the item_child.xml
I have created the sample application You can copy paste and check
**Main Activity **
public class MainActivity extends AppCompatActivity {
List<ScreenOneInventory> minventorylist = new ArrayList<ScreenOneInventory>();
List<ScreenOneRows> screenOneRowses = new ArrayList<>();
ArrayList<ItemInterface> finalList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String dataStr = "{\n" +
" \"rows\": [{\n" +
" \"sequence_id\":1,\n" +
" \"sequence_description\":\"animal description goes here\",\n" +
" \"sequence_image\":\"thumbnail.png\",\n" +
" \"sequence_title\": \"Animal\", \n" +
" \"child_rows\":[\n" +
" {\n" +
" \"id\": \"1\",\n" +
" \"name\":\"Lion\",\n" +
" \"description\" : \"lion description goes here\",\n" +
" \"image\": \"Lion.png\"\n" +
"\n" +
" },\n" +
" {\n" +
" \"id\": \"2\",\n" +
" \"name\":\"Tiger\",\n" +
" \"description\" : \"Tiger description goes here\",\n" +
" \"image\": \"Tiger.png\"\n" +
" },\n" +
" {\n" +
" \"id\": \"3\",\n" +
" \"name\":\"Elephant\",\n" +
" \"description\" : \"Elephant description goes here\",\n" +
" \"image\": \"Elephant.png\"\n" +
" } \n" +
" ]\n" +
" },\n" +
"{\n" +
" \"sequence_id\":2,\n" +
" \"sequence_description\":\"animal description goes here\",\n" +
" \"sequence_image\":\"thumbnail.png\",\n" +
" \"sequence_title\": \"Birds\", \n" +
" \"child_rows\":[\n" +
" {\n" +
" \"id\": \"1\",\n" +
" \"name\":\"Parrot\",\n" +
" \"description\" : \"Parrot description goes here\",\n" +
" \"image\": \"parrot.png\"\n" +
" },\n" +
" {\n" +
" \"id\": \"2\",\n" +
" \"name\":\"Pigeon\",\n" +
" \"description\" : \"Pigeon description goes here\",\n" +
" \"image\": \"Pigeon.png\"\n" +
" },\n" +
" {\n" +
" \"id\": \"3\",\n" +
" \"name\":\"Crow\",\n" +
" \"description\" : \"Crow description goes here\",\n" +
" \"image\": \"crow.png\"\n" +
" } \n" +
" ]\n" +
" } \n" +
" ]\n" +
"}";
try {
JSONObject jsonObj = new JSONObject(dataStr);
JSONArray jsondata = jsonObj.getJSONArray("rows");
for (int i = 0; i < jsondata.length(); i++) {
JSONObject rowsdata = jsondata.getJSONObject(i);
String sequence_id = rowsdata.getString("sequence_id");
String sequence_description = rowsdata.getString("sequence_description");
String sequence_image = rowsdata.getString("sequence_image");
String sequence_title = rowsdata.getString("sequence_title");
ScreenOneRows soRows = new ScreenOneRows();
soRows.setSequence_id(sequence_id);
soRows.setSequence_description(sequence_description);
soRows.setSequence_image(sequence_image);
soRows.setSequence_title(sequence_title);
finalList.add(soRows);
JSONArray childres = rowsdata.getJSONArray("child_rows");
for (int j = 0; j < childres.length(); j++) {
JSONObject inventorydata = childres.getJSONObject(j);
Log.i("Fragment", "I am here in loop j:" + j);
String id = inventorydata.getString("id");
String name = inventorydata.getString("name");
String description = inventorydata.getString("description");
String image = inventorydata.getString("image");
ScreenOneInventory soinventoryObj = new ScreenOneInventory();
soinventoryObj.setId(id);
soinventoryObj.setName(name);
soinventoryObj.setDescription(description);
soinventoryObj.setImage(image);
finalList.add(soinventoryObj);
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
MyCustomAdapter myCustomAdapter = new MyCustomAdapter(finalList, this);
recyclerView.setAdapter(myCustomAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Entity classes
ScreenOneInventory
class ScreenOneInventory implements ItemInterface {
String id;
String name;
String description;
String image;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean isRow() {
return false;
}
}
ScreenOneRows.java
class ScreenOneRows implements ItemInterface{
String sequence_id;
String sequence_description;
String sequence_image;
String sequence_title;
public String getSequence_id() {
return sequence_id;
}
public void setSequence_id(String sequence_id) {
this.sequence_id = sequence_id;
}
public String getSequence_description() {
return sequence_description;
}
public void setSequence_description(String sequence_description) {
this.sequence_description = sequence_description;
}
public String getSequence_image() {
return sequence_image;
}
public void setSequence_image(String sequence_image) {
this.sequence_image = sequence_image;
}
public String getSequence_title() {
return sequence_title;
}
public void setSequence_title(String sequence_title) {
this.sequence_title = sequence_title;
}
#Override
public boolean isRow() {
return true;
}
}
Recycler view Adapter **
** MyCustomAdapter.java
public class MyCustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int ROW_VIEW = 0;
public static final int CHILD_VIEW = 1;
ArrayList<ItemInterface> finalList;
WeakReference<Context> mContextWeakReference;
public MyCustomAdapter(ArrayList<ItemInterface> finalList, Context context) {
this.finalList = finalList;
this.mContextWeakReference = new WeakReference<Context>(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = mContextWeakReference.get();
if (viewType == ROW_VIEW) {
return new SectionViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false));
}
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_child, parent, false), context);
}
#Override
public int getItemViewType(int position) {
if (finalList.get(position).isRow()) {
return ROW_VIEW;
} else {
return CHILD_VIEW;
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Context context = mContextWeakReference.get();
if (context == null) {
return;
}
if (ROW_VIEW == getItemViewType(position)) {
SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
ScreenOneRows screenOneRows = (ScreenOneRows) finalList.get(position);
sectionViewHolder.textView.setText(screenOneRows.getSequence_title());
sectionViewHolder.textView2.setText(screenOneRows.getSequence_description());
return;
}
MyViewHolder myViewHolder = (MyViewHolder) holder;
ScreenOneInventory childInventory = (ScreenOneInventory) finalList.get(position);
myViewHolder.textView.setText(childInventory.getName());
myViewHolder.textView2.setText(childInventory.getDescription());
}
#Override
public int getItemCount() {
//return mUsersAndSectionList.size();
return finalList.size();
}
//holder
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView, textView2;
ImageView image;
public MyViewHolder(View itemView, final Context context) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
textView2 = itemView.findViewById(R.id.textView2);
image = itemView.findViewById(R.id.image);
}
}
public class SectionViewHolder extends RecyclerView.ViewHolder {
TextView textView, textView2;
ImageView image;
public SectionViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
textView2 = itemView.findViewById(R.id.textView2);
image = itemView.findViewById(R.id.image);
}
}
ItemInterface.java
this class is used to make generic type of arraylist which can be infate using one adapter
public interface ItemInterface{
boolean isRow();
}
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.my.stackoverflowrecyclerview.MainActivity"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg"
/>
</RelativeLayout>
item_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginStart="50dp"
android:background="#FFF"
android:orientation="vertical"
>
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#mipmap/ic_launcher_round"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/image"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="12dp"
android:layout_toEndOf="#+id/image"
android:text="TextView" />
</RelativeLayout>
item_child.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginStart="50dp"
android:background="#FFF"
android:orientation="vertical"
>
<ImageView
android:id="#+id/image"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#mipmap/ic_launcher_round"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/image"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="12dp"
android:layout_toEndOf="#+id/image"
android:text="TextView" />
</RelativeLayout>
here is output

How can I put drawable image into gridview?

I have a gridview with 5 columns, how could add in column 4 and 5, images that I have in drawable folder? The problem is that being a String arraylist not catch me drawable because it is an integer.
This is my XML:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrolView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<GridView
android:id="#+id/Grid"
android:numColumns="5"
android:stretchMode="columnWidth"
android:layout_width="match_parent"
android:gravity="center"
android:columnWidth="120dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:layout_height="2000dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"></GridView>
</LinearLayout>
This is the java code where I call carrito.xml, and i make the listview. This list view is filled with a String array.
public class carrito extends Fragment {
protected Context context;
private int numComandesCarrito;
private String[][] CarritoProductes;
private double Total;
DecimalFormat precision = new DecimalFormat("0.00");
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(Total);
public carrito(){
}
public void setContext (Context context){
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int i, i2;
numComandesCarrito = ((MainActivity) context).getNumComandesCarrito();
// Toast.makeText(context, Integer.toString(numComandesCarrito), Toast.LENGTH_LONG).show();
CarritoProductes = ((MainActivity) context).getCarritoProductes();
Total = 0;
ArrayList<String> lineasPedido = new ArrayList<String>();
ArrayList<Integer> itemsimg = new ArrayList( );
//Afegim la capçalera de la grid
lineasPedido.add("Plat");
lineasPedido.add("Quantitat");
lineasPedido.add("Preu");
for (i= 0; i < numComandesCarrito; i++){
for (i2 = 0; i2<3; i2++){
if (i2 == 2) {
lineasPedido.add(precision.format(Double.parseDouble(CarritoProductes[i2][i])) + " €");
Total = Total + Double.parseDouble(CarritoProductes[i2][i]);
}
else{
lineasPedido.add(CarritoProductes[i2][i]);
}
}
itemsimg.add(R.drawable.botonmenos);
}
lineasPedido.add("");
lineasPedido.add("");
lineasPedido.add("Total: " + (precision.format(Total)) + " €");
View rootView = inflater.inflate(R.layout.carrito, container, false);
GridView grdView = (GridView)rootView.findViewById(R.id.grdComanda);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, lineasPedido);
grdView.setAdapter(adapter);
return rootView;
}
You have to use custom adapter to put image in gridview
activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="5dp" >
</GridView>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutbg"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="#+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:paddingLeft="15dp"
android:text="TextView" />
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="15dp"
android:text="TextView" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
FriendAdapter.java
public class FriendAdapter extends ArrayAdapter<FriendBean>{
private Context mCtx;
private ArrayList<FriendBean> items = new ArrayList<FriendBean>();
private ViewHolder mHolder;
ImageLoader imgLoader = new ImageLoader(mCtx);
public LayoutInflater inflater;
int loader = R.drawable.loader;
public FriendAdapter(Context context, int textViewResourceId, ArrayList<FriendBean> items) {
super(context, textViewResourceId, items);
this.items = items;
this.mCtx = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=vi.inflate(R.layout.row, null);
mHolder=new ViewHolder();
mHolder.mImage=(ImageView)v.findViewById(R.id.img);
mHolder.mName=(TextView)v.findViewById(R.id.name);
mHolder.mPh=(TextView)v.findViewById(R.id.num);
mHolder.mlayoutbg=(RelativeLayout)v.findViewById(R.id.layoutbg);
v.setTag(mHolder);
}
else{
mHolder=(ViewHolder)v.getTag();
}
imgLoader.DisplayImage(items.get(position).getImage(), loader, mHolder.mImage);
//mHolder.mImage.setBackgroundResource(items.get(position).getImage());
mHolder.mName.setText(items.get(position).getName());
mHolder.mPh.setText(items.get(position).getPh());
mHolder.mlayoutbg.setBackgroundColor(Color.GREEN);
// if(position%3==1){
// mHolder.mlayoutbg.setBackgroundColor(Color.GRAY);
// }else if(position%3==2){
// mHolder.mlayoutbg.setBackgroundColor(Color.WHITE);
// }else{
// mHolder.mlayoutbg.setBackgroundColor(Color.YELLOW);
// }
return v;
}
public class ViewHolder {
public ImageView mImage;
public TextView mName;
public TextView mPh;
public RelativeLayout mlayoutbg;
}
}
FriendBean.java
package com.example.bean;
public class FriendBean {
private String Image;
private String name;
private String ph;
private String des;
public FriendBean(String Image, String name, String ph, String des) {
this.Image = Image;
this.name = name;
this.ph = ph;
this.des = des;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPh() {
return ph;
}
public void setPh(String ph) {
this.ph = ph;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
private FriendAdapter friendAdapter;
String friend_name, friend_phone, url, des;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (GridView) findViewById(R.id.gridView1);
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"gridarray.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("json");
Log.e("Length", "" + jsonarray.length());
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
friend_name = jsonObj.getString("friend_name");
friend_phone = jsonObj.getString("friend_phone");
url = jsonObj.getString("image_url");
des = jsonObj.getString("des");
FriendBean bean = new FriendBean(url, friend_name, friend_phone,
des);
arr.add(bean);
Log.e("u", url);
Log.e("friend_name", friend_name);
Log.e("friend_phone", friend_phone);
}
friendAdapter = new FriendAdapter(MainActivity.this, R.layout.row, arr);
mList.setAdapter(friendAdapter);
mList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Clicked on " + arg2,
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), NewPage.class);
i.putExtra("friend_name", arr.get(arg2).getName());
i.putExtra("friend_phone", arr.get(arg2).getPh());
i.putExtra("url", arr.get(arg2).getImage());
i.putExtra("des", arr.get(arg2).getDes());
startActivity(i);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
gridarray.json (put it in asset folder)
{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Madhumoy",
"friend_phone" : "123",
"des" : "Hi I'm Madhumoy"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sattik",
"friend_phone" : "123",
"des" : "Hi I'm Sattik"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Koushik",
"friend_phone" : "123",
"des" : "Hi I'm Koushik"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Himanshu",
"friend_phone" : "123",
"des" : "Hi I'm Himanshu"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sandy",
"friend_phone" : "123",
"des" : "Hi I'm Sandy"
}
] }
Hope this will work..
Maybe try something like this? The user comments seem to be positive for the most part. http://www.compiletimeerror.com/2013/02/display-images-in-gridview.html#.VRF2I2NTf5w

Arraylist TextView

I created a TextView with an ArrayList, but the output is not showing any text, what am I doing wrong? The xml has all the different views defined in it, with the imageview and multiple textviews, but I cant seem to get it to display any text.
TextItem.java:
public class TextItem {
private int imageId;
private String description;
private String description_real;
private String openingtimes;
private String openingtimes_real;
private String prices;
private String prices_real;
public TextItem(int imageId,
String description,
String description_real,
String openingtimes,
String openingtimes_real,
String prices,
String prices_real) {
this.imageId = imageId;
this.description = description;
this.description_real = description_real;
this.openingtimes = openingtimes;
this.openingtimes_real = openingtimes_real;
this.prices = prices;
this.prices_real= prices_real;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getdescription_real() {
return description_real;
}
public void setdescription_real(String description_real) {
this.description_real = description_real;
}
public String getopeningtimes(){
return openingtimes;
}
public void setopeningtimes(String openingtimes) {
this.openingtimes = openingtimes;
}
public String getopeningtimes_real(){
return openingtimes_real;
}
public void setopeningtimes_real(String openingtimes_real) {
this.openingtimes_real = openingtimes_real;
}
public String prices(){
return prices;
}
public void setprices(String prices) {
this.prices = prices;
}
public String getprices_real(){
return prices_real;
}
public void setprices_real(String prices_real) {
this.prices_real = prices_real;
}
#Override
public String toString() {
return description + "\n" + description_real + "/n" + "/n" +
openingtimes + "\n" + openingtimes_real + "/n" + "/n" +
prices + "\n" + prices_real + "/n" + "/n" ;
}}
Air.java:
public class Air extends Activity {
public static final String[] description = new String[] {"Lorem"};
public static final String[] description_real = new String[] {"Lorem"};
public static final String[] openingtimes = new String[] { "Lorem"};
public static final String[] openingtimes_real = new String[] {"Lorem"};
public static final String[] prices = new String[] { "Lorem"};
public static final String[] prices_real = new String[] {"Lorem"};
public static final Integer[] images = {
R.drawable.hotel };
ImageView ImageView;
TextView TextView;
List<TextItem> TextItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.textview_item);
TextItems = new ArrayList<TextItem>();
for (int i = 0; i < description.length ; i++) {
TextItem item = new TextItem(images[i],
description[i],
description_real[i],
openingtimes[i],
openingtimes_real[i],
prices[i],
prices_real[i]);
TextItems.add(item);
ImageView = (ImageView) findViewById(R.id.picture);
TextView = (TextView) findViewById(R.id.description);
TextView = (TextView) findViewById(R.id.description_real);
TextView = (TextView) findViewById(R.id.openingtimes);
TextView = (TextView) findViewById(R.id.openingtimes_real);
TextView = (TextView) findViewById(R.id.prices);
TextView = (TextView) findViewById(R.id.prices_real);
}
}
}
.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/picture"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/picture"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/description_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
<TextView
android:id="#+id/openingtimes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/description_real"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/openingtimes_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/openingtimes"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
<TextView
android:id="#+id/prices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/openingtimes_real"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/prices_real"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/prices"
android:paddingLeft="10dp"
android:textColor="#666666"
android:textSize="14sp" />
</RelativeLayout>
textView.setText("SomeText") is missing
you should do this
yourTextView.setText(textItem.getDescription)
also you are assigning many values to the same textview inside a loop, this is wrong, u gonna have one textItems displayed
code
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
public class StackActivity extends Activity {
public static final String[] description = new String[] { "Lorem" };
public static final String[] description_real = new String[] { "Lorem" };
public static final String[] openingtimes = new String[] { "Lorem" };
public static final String[] openingtimes_real = new String[] { "Lorem" };
public static final String[] prices = new String[] { "Lorem" };
public static final String[] prices_real = new String[] { "Lorem" };
public static final Integer[] images = { R.drawable.ic_launcher };
android.widget.ImageView ImageView;
android.widget.TextView TextView;
List<TextItem> TextItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextItems = new ArrayList<TextItem>();
for (int i = 0; i < description.length; i++) {
TextItem item = new TextItem(images[i], description[i],
description_real[i], openingtimes[i], openingtimes_real[i],
prices[i], prices_real[i]);
TextItems.add(item);
ImageView = (android.widget.ImageView) findViewById(R.id.picture);
ImageView.setImageResource(TextItems.get(i).getImageId());
TextView = (android.widget.TextView) findViewById(R.id.description);
TextView.setText(TextItems.get(i).getdescription());
TextView = (android.widget.TextView) findViewById(R.id.description_real);
TextView.setText(TextItems.get(i).getdescription());
TextView = (android.widget.TextView) findViewById(R.id.openingtimes);
TextView.setText(TextItems.get(i).getopeningtimes());
TextView = (android.widget.TextView) findViewById(R.id.openingtimes_real);
TextView.setText(TextItems.get(i).getopeningtimes_real());
TextView = (android.widget.TextView) findViewById(R.id.prices);
TextView.setText(TextItems.get(i).prices());
TextView = (android.widget.TextView) findViewById(R.id.prices_real);
TextView.setText(TextItems.get(i).getprices_real());
TextView.setText(TextItems.get(0).getdescription());
}
}
}

Categories

Resources