RecyclerView shows Strings but not Images - android

I have a SQLite database and want to search Items thorugh DB and then showing the items on recyclerView. Everything looking fine but recyclerView not showing the pictures, But somehow It shows the Strings
Normally pictures I saved inside the SQLite as BLOB should be displayed on the left.
Here is SearchFragment (Where I make the search and start recyclerView to display items)
public class SearchFragment extends Fragment {
Button searchbutton;
EditText editText;
View v;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_search, container, false);
addListenerOnButton(v);
return v;
}
private void addListenerOnButton(View v) {
searchbutton = v.findViewById(R.id.searchfragment_button);
editText = v.findViewById(R.id.searchfragment_edittext);
searchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String keystring = editText.getText().toString();
if(keystring.isEmpty())
Toast.makeText(getContext(),R.string.empty_search ,Toast.LENGTH_LONG).show();
else
new FoodQuery().execute(keystring);
}
});
}
//Place I start the search on background
private class FoodQuery extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String [] keys) {
String name_col;
DietAppDatabaseHelper daDBHelper;
SQLiteDatabase daDB;
daDBHelper = new DietAppDatabaseHelper(getContext());
try {
daDB = daDBHelper.getReadableDatabase();
if (Locale.getDefault().getLanguage() == "tr")
name_col = "name_tr";
else
name_col = "name_eng";
String query = "SELECT * FROM food_data WHERE " //Query here
+ name_col + " LIKE ?" ;
cursor = daDB.rawQuery(query, new String[]{"%" + keys[0] + "%"});
viewResults(name_col);
daDB.close();
} catch (SQLiteException e){
Log.d("SearchFragment", "doInBackground: " + e);
}
return null;
}
}
private void viewResults(String lang) {
int name_col = -1; //For language issues not important
if(lang == "name_tr")
name_col = 1;
else if(lang == "name_eng")
name_col = 2;
ArrayList<String> tmpnames = new ArrayList<>(); //I put pictures to byte[] and names to String Arraylist here
ArrayList<byte[]> tmppictures = new ArrayList<>();
if(cursor.moveToFirst()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
while(cursor.moveToNext()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
}
}
else {
Looper.prepare();
Toast.makeText(getContext(), R.string.no_food_found, Toast.LENGTH_LONG).show(); //To prevent empty search
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
RecyclerView recyclerView = v.findViewById(R.id.recycler_view);
SearchResultAdapter adapter = new SearchResultAdapter(getContext(), tmppictures, tmpnames);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);
}
});
}
}
Layout File of SearchFragment
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.SearchFragment"
android:id="#+id/fragment_search">
<Button
android:id="#+id/searchfragment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="#string/nav_search"
android:textColor="#FFFFFF"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:id="#+id/searchfragment_edittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="64dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="#+id/searchfragment_button"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="124dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the adapter
public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder>{
private ArrayList<byte[]> foodimages;
private ArrayList<String> foodnames;
private Context context;
public SearchResultAdapter(Context context, ArrayList<byte[]> foodimages, ArrayList<String> foodnames) {
this.foodimages = new ArrayList<>(foodimages);
this.foodnames = new ArrayList<>(foodnames);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_result_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.foodname.setText(foodnames.get(position));
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
}
#Override
public int getItemCount() {
return foodnames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView foodimage;
TextView foodname;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
foodimage = itemView.findViewById(R.id.food_seacrh_image);
foodname = itemView.findViewById(R.id.food_search_name);
parentLayout = itemView.findViewById(R.id.search_item);
}
}
}
Lastly, the layout of my item to use in recyclerView
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/search_item">
<ImageView
android:id="#+id/food_seacrh_image"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<TextView
android:id="#+id/food_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/food_seacrh_image"
android:textColor="#FFFFFF"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:textSize="17sp"
android:layout_toEndOf="#+id/food_seacrh_image"
android:layout_marginStart="30dp" />

It seems like the problem could be the line:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
Should probably be:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.get(position).size));
The third param on decodeByteArray should be the length (in bytes) of the image, you are passing in the actual number of images.

Related

Inserting a TextView text to SQLite upon a Button click

Question: How do I pass a TextView information into a variable so when a button is clicked it will add that information to a created SQLite database called collections.
Files left out (because I didn't think they related: androidmanafest.xml, database.java (this was for populating the cards database), and cards.java (for setters getters).
What it looks like:
enter image description here
Main Activity:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
//used for inserting card into collection database
DB_Controller controller;
TextView card_name, type, rarity, artist;
Button addCollectionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This is all for the controller in order to pass each card into collection database
controller = new DB_Controller(this,"collection.db",null,1);
setContentView(R.layout.layout_item);
card_name = (TextView)findViewById(R.id.card_name);
type = (TextView)findViewById(R.id.type);
rarity = (TextView)findViewById(R.id.rarity);
artist = (TextView)findViewById(R.id.artist);
//functionality of button "ADD TO COLLECTION"
addCollectionButton = (Button)findViewById(R.id.button_collection);
addCollectionButton.setOnClickListener(new View.OnClickListener() {
//when button clicked, insert into collection database
#Override
public void onClick(View view) {
String nameCard = card_name.getText().toString();
String typeCard = type.getText().toString();
String rarityCard = rarity.getText().toString();
String artistCard = artist.getText().toString();
//switch is used in case we need to add more buttons elsewhere in the app
//switch(view.getId()){
// case R.id.button_collection:
//controller.insert_card("drl","drl", "drl", "drl", "drl");
Toast.makeText(getBaseContext(), "ADDED TO COLLECTION", Toast.LENGTH_LONG).show(); //confirm card was added
//break;
//}
}
});
setContentView(R.layout.activity_main);
//init View
recyclerView = (RecyclerView)findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar)findViewById(R.id.search_bar);
//materialSearchBar.inflateMenu(R.layout.activity_main);
//init DB
database = new Database(this);
//setup search bar
//materialSearchBar.setHint("Search");
//materialSearchBar.setCardViewElevation(10);
loadSuggestList();
//This is used when typing in search bar suggesting words like those that have been typed
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
// method for when user types in search bar, return suggested strings
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int after) {
List<String> suggest = new ArrayList<>();
for(String search : suggestList) {
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
//This is used when user has typed the word(s) needed to search and hits the search icon
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled)
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//init Adapter default set all result
//adapter = new SearchAdapter(this, database.getFriends());
adapter = new SearchAdapter(this, database.getCards());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
//adapter = new SearchAdapter(this, database.getFriendByName(text));
adapter = new SearchAdapter(this, database.getCardsByName(text));
recyclerView.setAdapter(adapter);
}
//for populating suggestion list when search bar has been activated
private void loadSuggestList() {
suggestList = database.getNames();
materialSearchBar.setLastSuggestions(suggestList);
}
}
layout_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="8dp"
android:layout_margin="8dp">
<!--Creation of overall look of searched results
Main design tile for each searched result-->
<LinearLayout
android:orientation="horizontal"
android:layout_margin="8dp"
android:background="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--default image for each tile-->
<ImageView
android:src="#drawable/ic_image_black_24dp"
android:layout_width="70dp"
android:layout_height="70dp" />
<!--design tile within the main tile to display the information pulled from database-->
<LinearLayout
android:orientation="vertical"
android:layout_weight="9"
android:layout_width="0dp"
android:layout_height="wrap_content">
<!--information pulled from database design: NAME
android:id="#+id/name"-->
<TextView
android:id="#+id/card_name"
android:layout_marginLeft="10dp"
android:gravity="center_vertical|start"
android:textAllCaps="true"
android:textStyle="bold"
android:text="Eddy Lee"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--information pulled from database design: EMAIL
android:id="#+id/email"-->
<TextView
android:id="#+id/type"
android:layout_marginLeft="10dp"
android:gravity="center_vertical|start"
android:textStyle="italic"
android:text="eddy#gmail.com"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--information pulled from database design: PHONE
android:id="#+id/phone"-->
<TextView
android:id="#+id/rarity"
android:layout_marginLeft="10dp"
android:gravity="center_vertical|start"
android:textAllCaps="true"
android:textStyle="bold"
android:text="(123)456-7890"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--information pulled from database design: ADDRESS
android:id="#+id/address"-->
<TextView
android:id="#+id/artist"
android:layout_marginLeft="10dp"
android:gravity="center_vertical|start"
android:textAllCaps="true"
android:textStyle="normal"
android:text="123 Seseme Street"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_collection"
android:layout_width="200dp"
android:layout_height="35dp"
android:text="Add to Collection"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
activity_main.xml:
<?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="com.darrelbott.search.MainActivity">
<com.mancj.materialsearchbar.MaterialSearchBar
app:mt_speechMode="false"
app:mt_hint="Custom hint"
app:mt_maxSuggestionsCount="10"
app:mt_searchBarColor="#color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/search_bar" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_search"
android:layout_below="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
DB_Controller:
public class DB_Controller extends SQLiteOpenHelper {
private static final String TABLE_COLLECTION = "collection";
private static final String COLUMN_COLLECTION_ACCOUNT = "account";
private static final String COLUMN_COLLECTION_NAME = "card_name";
private static final String COLUMN_COLLECTION_TYPE = "type";
private static final String COLUMN_COLLECTION_RARITY = "rarity";
private static final String COLUMN_COLLECTION_ARTIST = "artist";
SQLiteDatabase db;
Context context;
int version = 1;
public DB_Controller(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, "collection.db", factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_COLLECTION + " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_COLLECTION_ACCOUNT + " TEXT, "
+ COLUMN_COLLECTION_NAME + " TEXT, "
+ COLUMN_COLLECTION_TYPE + " TEXT, "
+ COLUMN_COLLECTION_RARITY + " TEXT, "
+ COLUMN_COLLECTION_ARTIST + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//sqLiteDatabase.execSQL("DROP TABLE IF EXISTS collection;");
//onCreate(sqLiteDatabase);
}
public void insert_card(String account, String card_name, String type, String rarity, String artist) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_COLLECTION_ACCOUNT,account);
contentValues.put(COLUMN_COLLECTION_NAME,card_name);
contentValues.put(COLUMN_COLLECTION_TYPE,type);
contentValues.put(COLUMN_COLLECTION_RARITY,rarity);
contentValues.put(COLUMN_COLLECTION_ARTIST,artist);
db.insert(TABLE_COLLECTION,null,contentValues);
//this.getWritableDatabase().insertOrThrow("collection.db","",contentValues);
}
}
Adapter (which holds both SearchAdapter & SearchViewHolder):
class SearchViewHolder extends RecyclerView.ViewHolder {
//public TextView name, address, email, phone;
public TextView card_name, type, rarity, artist;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
card_name = (TextView)itemView.findViewById(R.id.card_name);
type = (TextView)itemView.findViewById(R.id.type);
rarity = (TextView)itemView.findViewById(R.id.rarity);
artist = (TextView)itemView.findViewById(R.id.artist);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
//private List<Friend> friends;
private List<Cards> cards;
public SearchAdapter(Context context, List<Cards> cards /*List<Friend> friends*/ ) {
this.context = context;
//this.friends = friends;
this.cards = cards;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
Button addCollectionButton;
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, int position) {
/*
holder.name.setText(friends.get(position).getName());
holder.address.setText(friends.get(position).getAddress());
holder.email.setText(friends.get(position).getEmail());
holder.phone.setText(friends.get(position).getPhone());
*/
holder.card_name.setText(cards.get(position).getName());
holder.type.setText(cards.get(position).getType());
holder.rarity.setText(cards.get(position).getRarity());
holder.artist.setText(cards.get(position).getArtist());
/*
//functionality of button "ADD TO COLLECTION"
final DB_Controller controller = new DB_Controller(this,"collection.db",null,1);
addCollectionButton.setOnClickListener(new View.OnClickListener() {
//when button clicked, insert into collection database
#Override
public void onClick(View view) {
//String card_name1 = card_name.setText(cards.get(position).getName());
//switch is used in case we need to add more buttons elsewhere in the app
//switch(view.getId()){
// case R.id.button_collection:
controller.insert_card("drl","drl", "drl", "drl", "drl");
//Toast.makeText(getApplicationContext(), "ADDED TO COLLECTION", Toast.LENGTH_LONG).show(); //confirm card was added
//break;
//}
}
});
*/
}
#Override
public int getItemCount() {
//return friends.size();
return cards.size();
}
}
You need to have the onClickListener inside the adapter where the button actually is. What you have done is have the listener in the main activity which is not correct. Put your listener in onBindViewHolder() and it should work if there is no issue in the sql code
As I commented earlier: You need to add the onClick() method of your "addCollectionButton" Button to your custom adapter class in the onBindViewHolder() method. The "button_collection" Button in your CardView layout has nothing to do with the "main_activity" layout.
Try this code for your Adapter.
Note: I did this in a text editor, so there might be a couple of typos!
Also Note: I changed you "cards" List into an ArrayList--so you will need to compensate in you Activity code.
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.MyViewHolder> {
private static final String TAG = SearchAdapter.class.getSimpleName();
private Context mContext;
private final DB_Controller dbController;
private ArrayList<Cards> cards;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView card_name, type, rarity, artist;
public Button addCollectionButton;
public MyViewHolder(View itemView) {
super(itemView);
card_name = (TextView)itemView.findViewById(R.id.card_name);
type = (TextView)itemView.findViewById(R.id.type);
rarity = (TextView)itemView.findViewById(R.id.rarity);
artist = (TextView)itemView.findViewById(R.id.artist);
addCollectionButton = (Button)itemView.findViewById(R.id.button_collection);
}
}
public SearchAdapter(Context context, ArrayList<Cards> cards) {
this.mContext = context;
dbController = new DB_Controller(context,"collection.db",null,1);
this.cards = cards;
}
#Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Cards cardsData = cards.get(position);
holder.card_name.setText(cardsData.getName());
holder.type.setText(cardsData.getType());
holder.rarity.setText(cardsData.getRarity());
holder.artist.setText(cardsData.getArtist());
holder.addCollectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG, "on click " + position);
String cardName = cardsData.getName();
String cardType = cardsData.getType();
String cardRarity = cardsData.getRarity();
String cardArtist = cardsData.getArtist();
// You will need to add the data as needed!
dbController.insert_card("drl","drl", "drl", "drl", "drl");
Toast.makeText(mContext, "ADDED TO COLLECTION: " + cardName, Toast.LENGTH_LONG).show(); //confirm card was added
}
});
}
#Override
public int getItemCount() {
return cards.size();
}
}
----------
Please let me know if you have any issues with the above code.

Data from JSON does not appear on the RecyclerView layout

I have created RecyclerView and showing data from JSON.
Issue I'm facing is, while Toast data is showing correctly, but in RecyclerView same data is not appear.
Here is code:
public class MainActivity extends AppCompatActivity {
private static final int NUM_LIST_ITEMS = 100;
private static final String TOKEN =
"71cf2d3dec294394e267fbb0bf28916f4198f8d6";
private CuloAdapter culoAdapter;
List<Hotel> lh = new ArrayList<>();
RecyclerView recyclerView;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rv_tiketapi);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layout);
CuloAdapter ar = new CuloAdapter(lh);
recyclerView.setAdapter(ar);
loadHotelLocation();
}
private void loadHotelLocation() {
final search apiService = ApiService.getService(search.class);
retrofit2.Call<SingleResult<Hotel>> call = apiService.findHotel(TOKEN,
"json");
call.enqueue(new Callback<SingleResult<Hotel>>() {
#Override
public void onResponse(retrofit2.Call<SingleResult<Hotel>> call,
Response<SingleResult<Hotel>> response) {
if (response.body().getDiagnostic().isSuccess()) {
//SingleResult.ResultList list =
response.body().getResults();
List<Hotel> mHotels = (List<Hotel>)
response.body().getResults().getResult();
lh.addAll(mHotels);
Toast.makeText(getApplicationContext(), "OK" +lh,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(retrofit2.Call<SingleResult<Hotel>> call,
Throwable t) {
}
});
}
RecyclerView Adapter :
public class CuloAdapter extends
RecyclerView.Adapter<CuloAdapter.ViewHolder> {
public CuloAdapter(List<Hotel> lh) {
this.items = lh;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtTitle;
public TextView txtSubTitle;
public ImageView imgIcon;
public ViewHolder(final View container) {
super(container);
txtTitle = (TextView) container.findViewById(R.id.airportName);
txtSubTitle = (TextView) container.findViewById(R.id.airportCode);
}
}
private List<Hotel> items;
public CuloAdapter(final Activity activity, List<Hotel> items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onBindViewHolder(CuloAdapter.ViewHolder holder, int position) {
Hotel item = items.get(position);
holder.txtTitle.setText(item.getLabel());
holder.txtSubTitle.setText(item.getId());
}
#Override
public CuloAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_flight, parent, false);
return new ViewHolder(v);
}
}
MainActivity XML :
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.admin.exampletiketapi.MainActivity">
<EditText
android:id="#+id/et_find"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_tiketapi"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Item List XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/airportsLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp">
<TextView
android:id="#+id/airportName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="Soekarno Hatta" />
<TextView
android:id="#+id/airportCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="20" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:background="#DDD"
android:visibility="visible" />
</LinearLayout>
In your code you are trying to set adapter before loading data.
CuloAdapter ar = new CuloAdapter(lh);
recyclerView.setAdapter(ar);
loadHotelLocation();
What i found is You are getting data in loadHotelLocation(), but trying to set adpter before that,
Call notifyDatasetChanged after lh.addAll(mHotels). And check for null's else you are heading for crash in case search results are zero/null

RecyclerView does not display items

I am using RecyclerView in Android with a model class that has title and details. Nothing is showing. Even after log inside Adapter nothing is shown in Android Monitor.
MainActivity.class
public ArrayList<Menu> menu_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
initUi();
}
public void initUi(){
RecyclerView menu_recycler = (RecyclerView) findViewById(R.id.main_menu_recycler_view);
//set the layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation( linearLayoutManager.VERTICAL );
menu_recycler.setLayoutManager( linearLayoutManager );
//set adapter
MainMenuAdapter mainMenuAdapter = new MainMenuAdapter( getMenulist() );
menu_recycler.setAdapter( mainMenuAdapter );
}
public ArrayList<Menu> getMenulist() {
menu_list = new ArrayList<Menu>();
menu_list.add( new Menu("About Us", " Learn more about our values, mission and vision ") );
menu_list.add( new Menu("Services ", " In implementing its mandate, the Agency will provide the following to its external and internal customers:\n"));
menu_list.add( new Menu("Stakeholders", " Who are the key players, Find out more") );
menu_list.add( new Menu("Learn about Counterfeits", "Gain more insight on counterfeit products"));
return menu_list;
}
and here is my adapter
public class MainMenuAdapter extends RecyclerView.Adapter<MainMenuAdapter.MyViewHolder> {
public List<Menu> list_of_menus;
public MainMenuAdapter( List<Menu> list_of_menus){
this.list_of_menus = list_of_menus;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row,parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Menu menu = list_of_menus.get(position);
Log.e("MENU IN ADAPTER TITLE", menu.title);
holder.title_text.setText( menu.title );
holder.details_text.setText( menu.details );
}
#Override
public int getItemCount() {
return 0;
}
/*
View Holder class
* */
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView title_text, details_text;
public MyViewHolder(View itemView) {
super(itemView);
title_text = (TextView) itemView.findViewById(R.id.menu_title);
details_text = (TextView) itemView.findViewById(R.id.menu_details);
}
}
}
And the Model Class
public class Menu {
public String title, details;
public Menu(String title, String details){
this.details = details;
this.title = title;
}
}
And the layout file main_activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.maos.aca.MainMenuActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="334dp"
android:layout_height="453dp" app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp" app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp" android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent" android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent" android:id="#+id/main_menu_recycler_view"
android:scrollbars="vertical"/>
</android.support.constraint.ConstraintLayout>
And finally the row
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/menu_title"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:id="#+id/menu_details"/>
</LinearLayout>
I know this question has been asked before, but none of the answers helped me out.I'll appreciate any lead.
You need to change the getItemCount() method to this:
#Override
public int getItemCount() {
return list_of_menus.size();
}
The RecyclerView will not display any elements if you are reporting that its size is zero.
Change this:
#Override
public int getItemCount() {
return 0;
}
To this:
#Override
public int getItemCount() {
return list_of_menus.size();
}

RecyclerView Displays only last objects in List

I am trying to display data in a RecyclerView. I have created an adapter to handle the RecyclerViews from different activities. The issue I am facing is displaying the data appropriately. So far I can only display the last elements in the list. In this case, the last candidate for each ContestedOffice. I have attached my code for both the activity and adapter as well as a screenshot of the output.
My Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String LOGCAT = RecyclerAdapter.class.getSimpleName();
private static final int VIEW_TYPE_VOTE = 0;
private static final int VIEW_TYPE_PREVIEW = 1;
private List candidatesList;
private LinearLayout checkBoxParent;
private VoteActivity voteActivity;
private Context context;
public RecyclerAdapter(List candidatesList) //Generic List
{
this.candidatesList = candidatesList;
}
#Override
public int getItemViewType(int position) {
if (candidatesList.get(position) instanceof Candidate) {
return VIEW_TYPE_PREVIEW;
} else {
return VIEW_TYPE_VOTE;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
if (viewType == VIEW_TYPE_PREVIEW) {
View preview = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_candidate_recycler, parent, false);
return new CandidateViewHolder(preview); // view holder for candidates items
} else if (viewType == VIEW_TYPE_VOTE) {
View ballot = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_ballot_view, parent, false); //false too
return new BallotViewHolder(ballot); // view holder for ContestedOffice items
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final int itemType = getItemViewType(position);
if (itemType == VIEW_TYPE_PREVIEW) {
CandidateViewHolder.class.cast(holder).bindData((Candidate)
candidatesList.get(position));
} else if (itemType == VIEW_TYPE_VOTE) {
BallotViewHolder.class.cast(holder).bindData((ContestedOffice)
candidatesList.get(position));
}
}
#Override
public int getItemCount() {
Log.d(LOGCAT, " Size: " + candidatesList.size());
return candidatesList.size();
}
/**
* ViewHolder class
*/
private class BallotViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private AppCompatTextView vote_candidate_name;
private AppCompatTextView vote_candidate_details;
private AppCompatTextView vote_candidate_party;
BallotViewHolder(View view) {
super(view);
checkBoxParent = (LinearLayout) view.findViewById(R.id.checkbox_layout_parent);
vote_candidate_name = (AppCompatTextView) view.findViewById(R.id.vote_candidate_name)
vote_candidate_party = (AppCompatTextView) view.findViewById(R.id.vote_candidate_party);
vote_candidate_details = (AppCompatTextView) view.findViewById(R.id.vote_candidate_details);
}
void bindData(ContestedOffice candidate)
{
int length = candidate.getList().size();
Log.d(LOGCAT, "BallotList size:" + length);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
//params.setMargins(10, 10, 10, 10);
params.gravity = Gravity.END;
CheckBox checkBox = null;
for (int i = 0; i < length; i++)
{
vote_candidate_name.setText(candidate.getList().get(i).getCandidateName());
vote_candidate_party.setText(candidate.getList().get(i).getParty());
vote_candidate_details.setText(candidate.getList().get(i).getDetails());
//Create checkboxes for each recycler view created
checkBox = new CheckBox(context);
checkBox.setTag(candidate.getList().get(i).getCandidateID());
checkBox.setId(candidate.getList().get(i).getCandidateID());
//checkBox.setText(R.string.checkBox_message);
checkBox.setText(String.valueOf(candidate.getList().get(i).getCandidateID()));
checkBox.setBackgroundColor(Color.RED);
Log.d(LOGCAT, "TAGS: " + checkBox.getTag() + " id: " + checkBox.getId());
}
if (checkBox != null) {
checkBox.setOnClickListener(this);
}
checkBoxParent.addView(checkBox, params);
}
#Override
public void onClick(View v) {
// Is the view now checked?
boolean checked = ((CheckBox) v).isChecked();
// Check which checkbox was clicked
switch (v.getId()) {
case 31:
if (checked) {
Log.d(LOGCAT, "Here:" + v.getTag().toString());
} else
break;
case 30:
if (checked) {
Log.d(LOGCAT, "Here:" + v.getTag().toString());
} else
break;
}
}
}
/**
* ViewHolder class
*/
private class CandidateViewHolder extends RecyclerView.ViewHolder {
private AppCompatTextView candidate_name;
private AppCompatTextView candidate_details;
private AppCompatTextView candidate_party;
private AppCompatTextView candidate_position;
// private AppCompatImageView candidate_image;
CandidateViewHolder(View view) {
super(view);
candidate_name = (AppCompatTextView) view.findViewById(R.id.candidate_name);
// candidate_image = (AppCompatImageView) view.findViewById(R.id.candidate_image);
candidate_position = (AppCompatTextView) view.findViewById(R.id.candidate_position);
candidate_party = (AppCompatTextView) view.findViewById(R.id.candidate_party);
candidate_details = (AppCompatTextView) view.findViewById(R.id.candidate_details);
}
void bindData(Candidate candidate)//Candidate
{
candidate_name.setText(candidate.getCandidateName());
candidate_position.setText(candidate.getPosition());
candidate_details.setText(candidate.getDetails());
candidate_party.setText(candidate.getParty());
// candidate_image.setImageBitmap(candidate.getCandidatePhoto());
}
}
}
My VoteActivity Class
public class VoteActivity extends AppCompatActivity implements View.OnClickListener
{
private static final String LOGCAT = VoteActivity.class.getSimpleName();
private AppCompatActivity activity = VoteActivity.this;
private RecyclerView vote_recycler_view;
private LinearLayout checkBoxParent;
private CheckBox vote_candidate_checkBox;
private AppCompatButton appCompatButtonVote;
private RecyclerAdapter recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
private Ballot ballot;
private List <ContestedOffice> ballotList = new ArrayList<>();
private List<Candidate> candidateList = new ArrayList<>();
private DatabaseHelper databaseHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote);
getSupportActionBar().setTitle("");
initViews();
initObjects();
initListeners();
}
private void initListeners()
{
appCompatButtonVote.setOnClickListener(this);
}
private void initObjects()
{
recyclerAdapter = new RecyclerAdapter(ballotList);
databaseHelper = new DatabaseHelper(this);
layoutManager = new LinearLayoutManager(activity);
vote_recycler_view.setLayoutManager(layoutManager);
vote_recycler_view.setItemAnimator(new DefaultItemAnimator());
vote_recycler_view.setHasFixedSize(true);
vote_recycler_view.setAdapter(recyclerAdapter);
getCandidates();
}
private void getCandidates()
{
new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
ballotList.clear();
candidateList.clear();
candidateList.addAll(databaseHelper.getAllCandidates());
createBallot();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
recyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
private void initViews()
{
checkBoxParent = (LinearLayout) findViewById(R.id.checkbox_layout_parent);
vote_recycler_view = (RecyclerView) findViewById(R.id.vote_recycler_view);
//vote_candidate_checkBox = (CheckBox) findViewById(R.id.vote_candidate_checkBox);
appCompatButtonVote = (AppCompatButton) findViewById(R.id.appCompatButtonVote);
}
public List<ContestedOffice> createBallot()
{
int candidateListSize = candidateList.size();
String position;
ArrayList<String> positionArray = new ArrayList<>();
ContestedOffice office;
//Looping through the candidates list and add all the positions being contested for
// to an array list.
for (int i = 0; i< candidateListSize; i++)
{
position = candidateList.get(i).getPosition();
positionArray.add(position);
}
//Create a set to remove all duplicate positions
Set<String> noDuplicates = new HashSet<>();
noDuplicates.addAll(positionArray);
positionArray.clear();
positionArray.addAll(noDuplicates);
Log.d(LOGCAT, "Contested Offices and Candidates: " + positionArray.size() + " "+ candidateListSize);
//Create the Contested Office according to the size of the position array
//and make sure the names are added.
int noOfContestedOffice = positionArray.size();
for(int i = 0; i<noOfContestedOffice; i++)
{
office = new ContestedOffice(positionArray.get(i));
Log.d(LOGCAT, "New Contested Office Created:" + office.getName());
Candidate c = new Candidate();
for(int j = 0; j < candidateListSize; j++)
{
//All the Seats/Position being Contested For
String candidatePosition = candidateList.get(j).getPosition();
String contestedOfficeName = office.getName();
if(candidatePosition.equals(contestedOfficeName)) {
c = candidateList.get(j);
//Add the candidate to the Contested Office
office.add(c);
}
Log.d(LOGCAT, "Added Candidate: "+ candidateList.get(j) +" to: "+ office.getName());
}
//Add offices to ballot and ballot List
ballot = new Ballot();
ballot.add(office);
//Ideally Ballot into BallotList
ballotList.add(office);
Log.d(LOGCAT, "Office definitely added to ballotList: " + ballotList.size());
}
return ballotList;
}
}
My VoteActivity XML
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/colorBackground"
android:orientation="vertical"
tools:context=".activities.VoteActivity">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/colorPrimary"
android:gravity="center"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dashboard_vote_message"
android:textAlignment="center"
android:textSize="20sp" />
<android.support.v7.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textAlignment="center"
android:id="#+id/vote_message_placeholder"
android:text="#string/vote_message" />
</android.support.v7.widget.LinearLayoutCompat>
<include layout="#layout/fragment_ballot_layout"/>
<include layout="#layout/footer_vote_button" />
</LinearLayout>
RecyclerView XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/recycler_layout_parent"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_marginTop="5dp">
<android.support.v7.widget.RecyclerView
android:layout_weight="1"
android:id="#+id/vote_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"/>
</LinearLayout>
</LinearLayout>
CardView XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
xmlns:tools="http://schemas.android.com/tools"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/vote_candidate_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_vertical"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:src = "#drawable/btn_ballot"
android:textColor="#android:color/white"
android:textSize="16sp"
tools:text="8.9"
android:contentDescription="#string/candidate_photo" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:id="#+id/vote_candidate_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:maxLines="1"
android:textAllCaps="true"
android:textColor="#color/textColorCandidateName"
android:textSize="12sp"
tools:text="CANDIDATE NAME" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/vote_candidate_party"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textColorPartyDetails"
android:textSize="12sp"
android:ellipsize="end"
tools:text="PARTY NAME" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/vote_candidate_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:textColor="#color/textColorDetails"
android:textSize="16sp"
tools:text="Long placeholder for candidate details. 2 Lines Max" />
</LinearLayout>
<LinearLayout
android:id="#+id/checkbox_layout_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:orientation="vertical">
<!--Dynamic Checkboxes here-->
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Code Output
i think you are creating object of candidate every time in for loop make below chnages it will solve your problem
Candidate c = new Candidate();
ballot = new Ballot();
for(int i = 0; i<noOfContestedOffice; i++)
{
office = new ContestedOffice(positionArray.get(i));
Log.d(LOGCAT, "New Contested Office Created:" + office.getName());
for(int j = 0; j < candidateListSize; j++)
{
//All the Seats/Position being Contested For
String candidatePosition = candidateList.get(j).getPosition();
String contestedOfficeName = office.getName();
if(candidatePosition.equals(contestedOfficeName)) {
c = candidateList.get(j);
//Add the candidate to the Contested Office
office.add(c);
}
Log.d(LOGCAT, "Added Candidate: "+ candidateList.get(j) +" to: "+ office.getName());
}
//Add offices to ballot and ballot List
ballot.add(office);
//Ideally Ballot into BallotList
ballotList.add(office);
Log.d(LOGCAT, "Office definitely added to ballotList: " + ballotList.size());
}
just check it once and you are done with your problem.
i have update xml below
<android.support.v7.widget.RecyclerView
android:layout_weight="1"
android:id="#+id/vote_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
check it out the height of recyclerview.

i wanted to save my data on listview after clicking the back button and also view it after pressing view button.But i am not getting it

I have a Recyclerview in my main activity and a button on a every fragment of recyclerview. When i click on that button the data just get added to listview present on another activity. And I have a button present on my action bar, when i click that button wants to see only the list view. Thanks in Advance.
My MainAcitivity code is as follows:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
// ArrayList<Integer> images;
// ArrayList<String> imageNames, contents;
public static int[] images = {R.drawable.bengalithali,R.drawable.chikanthali,R.drawable.eggthali, R.drawable.gujratithali,
R.drawable.maharstrianthali, R.drawable.keralathali, R.drawable.rajsthanithali, R.drawable.tamilthali};
public static String[] imageNames = {"Bengali Thali","Chikan Thali", "Egg Thali", "Gujrathi Thali", "Maharashtrian Thali", "Kerala Thali",
"Rajsthani Thali", "Tamil Thali"};
public static String[] contents = {"As seen in Pic","As seen in Pic","As seen in Pic","As seen in Pic","As seen in Pic","As seen in Pic",
"As seen in Pic","As seen in Pic"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// images = new ArrayList<>();
// images.add(R.drawable.bengalithali);
// images.add(R.drawable.chikanthali);
// images.add(R.drawable.eggthali);
// images.add(R.drawable.gujratithali);
// images.add(R.drawable.maharstrianthali);
// images.add(R.drawable.keralathali);
// images.add(R.drawable.rajsthanithali);
// images.add(R.drawable.tamilthali);
//
// imageNames = new ArrayList<>();
// imageNames.add("Bengali Thali");
// imageNames.add("Chikan Thali");
// imageNames.add("Egg Thali");
// imageNames.add("Gujrathi Thali");
// imageNames.add("Maharashtrian Thali");
// imageNames.add("Kerala Thali");
// imageNames.add("Rajsthani Thali");
// imageNames.add("Tamil Thali");
//
// contents = new ArrayList<>();
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
adapter = new RecyclerAdapter(MainActivity.this,images, imageNames, contents);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_button,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(MainActivity.this, MyCartList.class);
startActivity(intent);
return super.onOptionsItemSelected(item);
}
}
My Recyclerview adapter code is as follows:
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
String[] imageNames, contents;
int[] images;
Context context;
public RecyclerAdapter(Context context,int[] images,String[] imageNames,String[] contents) {
this.images = images;
this.imageNames = imageNames;
this.contents = contents;
this.context = context;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
RecyclerViewHolder rvh = new RecyclerViewHolder(view);
return rvh;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.productImage.setFitsSystemWindows(true);
holder.productImage.setImageResource(images[position]);
holder.productName.setText(imageNames[position]);
holder.productContent.setText(contents[position]);
}
#Override
public int getItemCount() {
return images.length;
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder{
ImageView productImage;
TextView productName, productContent, quantity;
CircleButton plusButton, minusButton;
FButton addToCartButton;
public RecyclerViewHolder(final View itemView) {
super(itemView);
productImage = (ImageView) itemView.findViewById(R.id.product_image);
productName = (TextView) itemView.findViewById(R.id.product_name);
productContent = (TextView) itemView.findViewById(R.id.product_content);
plusButton = (CircleButton) itemView.findViewById(R.id.plus_button);
minusButton = (CircleButton) itemView.findViewById(R.id.minus_button);
quantity = (TextView) itemView.findViewById(R.id.show_quantity);
addToCartButton = (FButton) itemView.findViewById(R.id.add_button);
plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int Quantity = Integer.parseInt(quantity.getText().toString());
quantity.setText(String.valueOf(Quantity+1));
if (Quantity == 10 && plusButton.isClickable()){
quantity.setText("10");
}
}
});
minusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int Quantity = Integer.parseInt(quantity.getText().toString());
quantity.setText(String.valueOf(Quantity-1));
if (Quantity == 0 && minusButton.isClickable()){
quantity.setText("0");
}
}
});
addToCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MyCartList.class);
// Bundle bundle = new Bundle();
// bundle.putString("KEYONE",imageNames[getAdapterPosition()]);
// bundle.putString("KEYTWO", contents[getAdapterPosition()]);
// intent.putExtras(bundle);
intent.putExtra("KEYONE", imageNames[getAdapterPosition()]);
intent.putExtra("KEYTWO", contents[getAdapterPosition()]);
view.getContext().startActivity(intent);
Toast.makeText(context, ""+imageNames[getAdapterPosition()]+ "\n"+ contents[getAdapterPosition()], Toast.LENGTH_SHORT).show();
}
});
}
}
}
My CartList activity code is as follows:
public class MyCartList extends AppCompatActivity {
ListView myList = null;
MyListViewAdapter myListViewAdapter;
public static ArrayList<String> c = new ArrayList<>();
public static ArrayList<String> d = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart_list);
Intent i = getIntent();
String a = i.getStringExtra("KEYONE");
String b = i.getStringExtra("KEYTWO");
c.add(a);
d.add(b);
myList = (ListView) findViewById(R.id.my_list_view);
myListViewAdapter = new MyListViewAdapter(MyCartList.this,c,d);
myList.setAdapter(myListViewAdapter);
}
}
My listview adapter code is as follows:
public class MyListViewAdapter extends BaseAdapter{
Context mContext;
public static ArrayList<String> thaliNames, thaliContent;
SharedPreferences sharedPreferences;
public MyListViewAdapter(Context context,ArrayList<String> thaliNames, ArrayList<String> thaliContent) {
this.mContext = context;
this.thaliNames = thaliNames;
this.thaliContent = thaliContent;
}
#Override
public int getCount() {
return thaliNames.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_list, null);
TextView listItem = (TextView) view.findViewById(R.id.my_product_name);
listItem.setText(thaliNames + "\n" + thaliContent);
return view;
}
}
activity_main.xml is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.gaurya.carttask.MainActivity"
android:scrollbars="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
list_tems.xml is as follows:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/product_image"
android:layout_width="150dp"
android:layout_height="200dp"
app:riv_border_color="#android:color/holo_red_dark"
app:riv_corner_radius="30dip"
app:riv_border_width="2dip"
app:riv_mutate_background="true"
app:riv_tile_mode="repeat"
app:riv_oval="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical">
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="20dp"
android:text="Name"
android:textSize="20sp"/>
<TextView
android:id="#+id/product_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:text="Name"
android:textSize="15sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<at.markushi.ui.CircleButton
android:id="#+id/plus_button"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_marginTop="25dp"
android:layout_marginLeft="15dp"
app:cb_color="#64daed"
android:src="#drawable/plus"
/>
<TextView
android:id="#+id/show_quantity"
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_marginTop="25dp"
android:text="0"
android:gravity="center"
android:textSize="30sp"
android:padding="5dp"
android:layout_marginLeft="10dp"/>
<at.markushi.ui.CircleButton
android:id="#+id/minus_button"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_marginTop="25dp"
app:cb_color="#64daed"
android:src="#drawable/negative"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<info.hoang8f.widget.FButton
android:id="#+id/add_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="add to cart"
app:shadowEnabled="true"
app:shadowHeight="5dp"
app:cornerRadius="15dp"
android:layout_marginTop="17dp"/>
</LinearLayout>
</LinearLayout>
activity_my_cart_list.xml is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_my_cart_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.gaurya.carttask.MyCartList">
<ListView
android:id="#+id/my_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</ListView>
</RelativeLayout>
my_list.xml is as follows:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/my_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The Simplest way is, You can create one public class which can hold List of Elements and you can access it whenever you want.
Example by Using String Object
public static class MyListHolder{
static List<String> lstOfObj;
public Static MyListHolder(){
lstOfObj = new ArrayList<String>();
}
public static void addNewObject(String object){
lstOfObj.add(object);
}
public static List<String> getMyObjList(){
return lstOfObj;
}
}
Now You can use this class & methods to manage your List of Object.

Categories

Resources