I am just learning the RecyclerView and cannot figure out why the imageView with android:id="#+id/im_item_icon" will not show up on the screen. I even have another imageView that works but when I swap the IDs the original not working view works and the working one will not work. So basically the problem must be with the ID but I cannot figure out why. BTW I got the code from a blog "http://wiseassblog.com/tutorials/2016/03/04/how-to-build-a-recyclerview/"
DerpAdapter.java
public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder> {
private List<ListItem> listData;
private LayoutInflater inflater;
public DerpAdapter(List<ListItem> listData, Context c){
inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public DerpAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent, false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
ListItem item = listData.get(position);
holder.title.setText(item.getTitle());
holder.icon.setImageResource(item.getImageResId());
}
#Override
public int getItemCount() {
return listData.size();
}
class DerpHolder extends RecyclerView.ViewHolder {
private TextView title;
private ImageView icon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
icon = (ImageView)itemView.findViewById(R.id.im_item_icon);
//We'll need the container later on, when we add an View.OnClickListener
container = itemView.findViewById(R.id.cont_item_root);
}
}
DerpData.java
public class DerpData {
private static final String[] titles = {"Nothingness cannot be defined",
"Time is like a river made up of the events which happen, and a violent stream; " +
"for as soon as a thing has been seen, it is carried away, and another comes" +
" in its place, and this will be carried away too,",
"But when I know that the glass is already broken, every minute with it is precious.",
"For me, it is far better to grasp the Universe as it really is than to persist in" +
" delusion, however satisfying and reassuring.",
"The seeker after the truth is not one who studies the writings of the ancients and," +
" following his natural disposition, puts his trust in them, but rather the" +
" one who suspects his faith in them and questions what he gathers from them," +
" the one who submits to argument and demonstration, and not to the " +
"sayings of a human being whose nature is fraught with all kinds " +
"of imperfection and deficiency.",
"You must take personal responsibility. You cannot change the circumstances, the" +
" seasons, or the wind, but you can change yourself. That is something you" +
" have charge of."
};
private static final String[] subTitles = {"Bruce Lee",
"Marcus Aurelius",
"Meng Tzu",
"Ajahn Chah",
"Carl Sagan",
"Alhazen",
"Jim Rohn"
};
private static final int icon = R.drawable.ic_tonality_black_36dp;
public static List <ListItem> getListData() {
List <ListItem> data = new ArrayList <>();
//Repeat process 4 times, so that we have enough data to demonstrate a scrollable
//RecyclerView
for (int x = 0; x < 4; x++) {
//create ListItem with dummy data, then add them to our List
for (int i = 0; i < titles.length; i++) {
ListItem item = new ListItem();
item.setTitle(titles[i]);
item.setSubTitle(subTitles[i]);
data.add(item);
}
}
return data;
}
ListItem.java
public class ListItem {
private int imageResId;
private String subTitle;
private String title;
private boolean favourite = false;
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public boolean isFavourite() {
return favourite;
}
public void setFavourite(boolean favourite) {
this.favourite = favourite;
}
public int getImageResId() {
return imageResId;
}
public void setImageResId(int imageResId) {
this.imageResId = imageResId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
ListActivity.java
public class ListActivity extends AppCompatActivity {
private RecyclerView recView;
private DerpAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recView = (RecyclerView)findViewById(R.id.rec_list);
//Check out GridLayoutManager and StaggeredGridLayoutManager for more options
recView.setLayoutManager(new LinearLayoutManager(this));
adapter = new DerpAdapter(DerpData.getListData(), this);
recView.setAdapter(adapter);
}
activity_detail.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="application.binarysoup.jsonpractice.ui.DetailActivity">
<TextView
android:id="#+id/lbl_quote_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium" />
<TextView
android:id="#+id/lbl_quote_attribution"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/lbl_quote_text"
android:fontFamily="sans-serif-light"
android:textStyle="italic" />
activity_list.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="application.binarysoup.jsonpractice.ui.ListActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/rec_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="72dp"
android:background="#drawable/background_state_drawable"
android:clickable="true"
>
<ImageView
android:id="#+id/im_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="16dp"
android:src="#drawable/ic_tonality_black_36dp" />
<TextView
android:id="#+id/lbl_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/im_item_icon"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Sois comme l'eau mon ami"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/lbl_item_sub_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lbl_item_text"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Mononc' J"
android:textSize="14sp" />
<ImageView
android:id="#+id/im_item_icon_secondary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="true"
android:padding="16dp"
android:src="#drawable/ic_star_border_black_24dp"
android:background="#drawable/background_state_drawable"
/>
Can't get ImageView to show up on RecyclerView
You have to initialize imageResId in order to appear it in the recyclerView
for (int i = 0; i < titles.length; i++) {
ListItem item = new ListItem();
item.setTitle(titles[i]);
item.setSubTitle(subTitles[i]);
//put the code to initialise the imageResId here
data.add(item);
}
Related
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.
That is when the sender from one device sends message,it should appear on the right hand side and when the other device gets the message it should appear on the left hand side.
My java class: This is the function I am calling
private void chatRowStyling(boolean isItMe, ViewHolder holder){
if (isItMe){
holder.layoutParams.gravity = Gravity.END;
holder.chatBody.setTextColor(Color.BLUE);
holder.senderName.setBackgroundResource(R.drawable.speech_bubble_green);
}else{
holder.layoutParams.gravity = Gravity.START;
holder.chatBody.setTextColor(Color.GREEN);
holder.senderName.setBackgroundResource(R.drawable.speech_bubble_orange);
}
Log.i("TAG","error :" + mySnapShot);
holder.senderName.setLayoutParams(holder.layoutParams);
holder.chatBody.setLayoutParams(holder.layoutParams);
}
In the Screenshot, all the messages appear on the right side, whereas I want one to be on right and another to be on left from different users.
This is my XML code :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/singleMessageContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:text="#string/sender"
android:textColor="#2980b9"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_margin="5dip"
android:padding="12dp"
android:text="#string/author"
android:textColor="#2c3e50" />
</LinearLayout>
The best way to do it would be to implement RecyclerView with separate view types, that way you could adjust layout however you want without some shady workaround. Here is example to do it.
Reference : How to create RecyclerView with multiple view type?
EDIT:
Convinced by comments I decided to add some more explanation.
You could create two separate layouts, one for your messages:
<RelativeLayout 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">
<TextView
android:id="#+id/tvAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
<TextView
android:id="#+id/tvMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tvAuthor"
android:layout_alignParentRight="true"/>
</RelativeLayout>
and the other one for messages from friend:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tvAuthor" />
</RelativeLayout>
Then you can create a class for your messages:
public class Message {
private String message;
private String author;
public Message(String message, String author) {
this.message = message;
this.author = author;
}
public String getMessage() {
return message;
}
public String getAuthor() {
return author;
}
}
Next step would be to create adapter for your RecyclerView that will use two seperate ViewHolders, one for your messages and the other for messages from your friend. Inside OnCreateViewHolder you can choose which layout you want to display for each message. Then in OnBindViewHolder, you can fill TextViews with correct message data.
public class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Message> messages;
private final static int TYPE_FROM_FRIEND = 1;
private final static int TYPE_TO_FRIEND = 2;
public MessageAdapter(ArrayList<Message> messages) {
this.messages = messages;
}
public int getItemViewType(int position) {
if (messages.get(position).getAuthor().equals("Me")) {
return TYPE_TO_FRIEND;
} else {
return TYPE_FROM_FRIEND;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = 0;
RecyclerView.ViewHolder viewHolder;
switch (viewType){
case TYPE_TO_FRIEND:
layout = R.layout.view_message_to_friend;
View toFriendView = LayoutInflater
.from(parent.getContext())
.inflate(layout, parent, false);
viewHolder=new ToFriendViewHolder(toFriendView);
break;
case TYPE_FROM_FRIEND:
layout = R.layout.view_message_from_friend;
View fromFriendView = LayoutInflater
.from(parent.getContext())
.inflate(layout, parent, false);
viewHolder = new FromFriendViewHolder(fromFriendView);
break;
default:
viewHolder = null;
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
int viewType=holder.getItemViewType();
switch (viewType){
case TYPE_TO_FRIEND:
((ToFriendViewHolder)holder).tvMessage.setText(messages.get(position).getMessage());
((ToFriendViewHolder)holder).tvAuthor.setText(messages.get(position).getAuthor());
break;
case TYPE_FROM_FRIEND:
((FromFriendViewHolder)holder).tvMessage.setText(messages.get(position).getMessage());
((FromFriendViewHolder)holder).tvAuthor.setText(messages.get(position).getAuthor());
break;
}
}
private class ToFriendViewHolder extends RecyclerView.ViewHolder {
private TextView tvAuthor;
private TextView tvMessage;
public ToFriendViewHolder(View view) {
super(view);
tvAuthor = (TextView) view.findViewById(R.id.tvAuthor);
tvMessage = (TextView) view.findViewById(R.id.tvMessage);
}
}
private class FromFriendViewHolder extends RecyclerView.ViewHolder {
private TextView tvAuthor;
private TextView tvMessage;
public FromFriendViewHolder(View view) {
super(view);
tvAuthor = (TextView) view.findViewById(R.id.tvAuthor);
tvMessage = (TextView) view.findViewById(R.id.tvMessage);
}
}
#Override
public int getItemCount() {
return messages.size();
}
}
Finally you can set RecyclerView's adapter in your activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView rvMain;
private ArrayList<Message> messages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvMain = (RecyclerView) findViewById(R.id.rvMain);
rvMain.setLayoutManager(new LinearLayoutManager(this));
messages.add(new Message("Hello", "Me"));
messages.add(new Message("Hi", "Friend"));
messages.add(new Message("How are you?", "Me"));
messages.add(new Message("I'm fine and you?", "Friend"));
MessageAdapter adapter = new MessageAdapter(messages);
rvMain.setAdapter(adapter);
}
}
You can achieve it by setting the view gravity not the LayoutParams with something like this:
if(isIfMe) {
holder.linearLayout.setGravity(Gravity.END);
holder.tvAuthor.setGravity(Gravity.END);
} else {
holder.linearLayout.setGravity(Gravity.END);
holder.tvAuthor.setGravity(Gravity.END);
}
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 looked up for the possible solutions but I could not figure out how to apply them in my case.
I am using a RecyclerView to display several CardViews inside it. Initially all cards have white background and I want to change the background color when a card is touched. Each CardView displays a name and an id as described in 'MyCards' class :
public class MyCards {
private String sName;
private int sId;
private boolean sPresent;
public String getName() {
return this.sName;
}
public MyCards(String sName, int sId, boolean sPresent) {
this.sName = sName;
this.sId = sId;
this.sPresent = sPresent;
}
public void setName(String t) {
this.sName = t;
}
public int getId() {
return sId;
}
public void setId(int id) {
this.sId = id;
}
public boolean isPresent() {
return sPresent;
}
public void setPresent(boolean present) {
this.sPresent = present;
}
}
I am making an ArrayList of these MyCards object in the 'Roster' class :
public class Roster extends ActionBarActivity{
private static final int READ_REQUEST_CODE = 42;
private static final String TAG = null;
private RecyclerView rObject;
private MyAdapter adapter;
String abc = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roster_recycle);
rObject = (RecyclerView)findViewById(R.id.recycler_view);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
rObject.setLayoutManager(llm);
MyCards c1 = new MyCards("Abhinav", 123, true);
MyCards c2 = new MyCards("Abhishek", 13, false);
performFileSearch();
c1.setName("Abhinav");
c2.setName("Baba");
List<MyCards> cardList = new ArrayList<MyCards>();
cardList.add(c1);
cardList.add(c2);
adapter = new MyAdapter(Roster.this,cardList);
rObject.setAdapter(adapter);
}
The CardView is defined in the item_layout.xml file :
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardCornerRadius="4dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/sName"
android:layout_width="match_parent"
android:layout_height="20dp"
android:gravity="center_vertical"
android:text="contact det"
android:textSize="14dp" />
<TextView
android:id="#+id/sId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/sName"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:text="Name"
android:textSize="10dp" />
<TextView
android:id="#+id/sPresent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/sId"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:text="Present"
android:textSize="10dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
My question is : If I click on a card displaying data for 'c1' object then how can I identify that it was from 'c1' and not 'c2'. How do I use click handler in such cases where we display multiple cards?
I'm sorry if my question is too basic but I'm really stuck at it.
Thank you so much for your responses, they really helped. Finally I found a video on YouTube which explained the concept in a nice manner. I am posting the link so that others can also benefit if they get stuck. Here is the video -
see this :- https://www.youtube.com/watch?v=zE1E1HOK_E4
Take a look at this answer for using an onItemClickListener with a RecyclerView.
public class MyAdapter extends RecyclerView.Adapter {
Context mContext;
ArrayList<MyCard> mData;
public MyAdapter(Context context , ArrayList<MyCard> data ) {
mContext = context;
mData = data;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView sName, sId , sPresent;
public ViewHolder(View itemView) {
super(itemView);
sName = (TextView) itemView.findViewById(R.id.sName);
sId = (TextView) itemView.findViewById(R.id.sId);
sPresent = (TextView) itemView.findViewById(R.id.sPresent);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// your logic
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout , parent , false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public int getItemCount() {
return mData.size();
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final MyCard card = mData.get(position);
holder.sName.setText(card.getName().toString());
holder.sId.setText(card.getId().toString());
holder.sPresent.setText(card.getPresent().toString());
}
}
Hi thanks for reading this! Please help me.
I am trying to create a restaurant app which the display 3 buttons in the menu then click the food button which display the list of food, then customer can choose the food they want to order then send back the order back to first page. I read a lot of the article and some say use the listview.setItemsCanFocus(true) but I having problem to understand it to implement it. and some say the button listener inside the getView but when I implement my program just hang. Please help me. Thank you.
my menu :
here is my food(second) page
I am having problems:
to transfer the data back from the food.class back to my main class which is
restaurant.class
After I add the button in the list the food is not clickable(the whole row of food).
my main class(restaurant)
public class SesameRestaurant extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void foodMenu(View v){
startActivity(new Intent(SesameRestaurant.this,Food.class));
//setContentView(R.layout.foods);
}
public void drinkMenu(View v){startActivity(new Intent(SesameRestaurant.this,Drink.class));}
public void billMenu(View v){}
}
my second class (food.class)
package com.restaurant.sesame;
public class Food extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
"Cow Rib steak",
"Thai Prawn Fried Rice",
"Christmas Sensation Delight",
"Salmon Steak" };
static final String[] detail = new String[] {
"1h 37m Shipping: $10.00",
"1h 39m Shipping: Free",
"58m 6s Shipping: $10.00",
"59m 30s Shipping: $10.95" };
private Integer [] imgid = { R.drawable.food1, R.drawable.food2, R.drawable.food3, R.drawable.food4 };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foods);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Log.w("my app", "Click list Item!!!");
Toast.makeText(getApplicationContext(), "You have selected "+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
public void orderClick(View v){
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail)
{
mId=id;
mTitle = title;
mDetail=detail;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
public void backClick(View v){
finish();
}
}
my food menu interface foods.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_height="wrap_content"
android:text="Back"
android:onClick="backClick"
android:layout_width="fill_parent">
</Button>
my list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/img"
android:scaleType="centerCrop"
android:layout_width="100dp"
android:layout_height="100dp"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:id="#+id/title"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="16sp" />
<TextView
android:layout_width="fill_parent"
android:id="#+id/detail"
android:textColor="#ffffff"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity :"
android:textColor="#ffffff" />
<EditText
android:id="#+id/quantityInput"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_toRightOf="#id/quantity"
android:hint="1-10"
android:paddingLeft="10dp"
android:textSize="12dp" />
<Button
android:id="#+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_toRightOf="#id/quantity"
android:onClick="orderClick"
android:text="Order"
android:textSize="12dp" />
</RelativeLayout>
</LinearLayout>
I'm at school now so I don't have time to get a you a code snippet at all but you are going to need to use startActivityForResult() instead of just startActivity(). This will allow you to send information back to your main app upon completion of the your food activity.
Respond if you need me to find a snippet for you and I'll write one up quick once I get home in about an hour.