How to get items selected from checked listview on viewpager? - android

I am using a viewpager in my program and on that I am displaying custom listview. On every viewpager swipe I am displaying the same listview but with differnt list items. I want to get all the items checked from all those listviews, when I click on the submit button.
But this submit button is not on my viewpager. Its quite complicated for me. Here is my main class code(I am just showing part of my code there are no errors in the code right now):
public class HotelMenu extends FragmentActivity implements CompletionListener {
static final int ITEMS = 10;
MyAdapter mAdapter;
ViewPager mPager;
private NetworkTask networkTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_menu);
get_restaurant_menu();
mAdapter = new MyAdapter(getSupportFragmentManager(),HotelMenu.this);
mPager = (ViewPager) findViewById(R.id.pager);//adapter for viewpager
Button submit= (Button) findViewById(R.id.next);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//here I want all the items checked from the listview
}
});
}
Here is my layout for this class:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip"
android:background="#drawable/home_screen_background">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tvRestNameForMenu"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#ffffff"
android:layout_gravity="center_vertical"
android:background="#drawable/offers_text"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:alpha="0.7"
android:background="#android:color/white">
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:background="#drawable/button_shape"
android:textColor="#android:color/white">
</Button>
</LinearLayout>
</LinearLayout>
This is my adpater for viewpager:
public static class MyAdapter extends FragmentStatePagerAdapter {
Context context;
public MyAdapter(FragmentManager fragmentManager, Context context) {
super(fragmentManager);
this.context=context;
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show list of maincourse items
// return ArrayListFragment.newInstance(position, mainCourse);//pass viewpager page position and list to be displayed
case 1: // Fragment # 1 - This will show list of soups
return ArrayListFragment.newInstance(position,startersName,startersCost );
default:// Fragment # 2-9 - Will show list
return ArrayListFragment.newInstance(position, maincourseName,maincourseCost);
}
}
}
and finally this is my fragment for displaying listview on viewpager:
public class ArrayListFragment extends android.support.v4.app.Fragment{
int fragNum;
String[] arr;
ArrayList<String>item_name;
ArrayList<String>item_cost;
ListView lvsoups;
MyAdapter myAdapter;
Context context;
LayoutInflater inflater1;
View layoutView;
public static final ArrayListFragment newInstance(int val, ArrayList<String> itemName, ArrayList<String> itemCost){
ArrayListFragment list=new ArrayListFragment();
//Bundle is used to use values and array passed through hotel menu class
Bundle bundle = new Bundle(2);
bundle.putInt("val", val);
bundle.putStringArrayList("itemName",itemName);
bundle.putStringArrayList("itemCost",itemCost);
list.setArguments(bundle);
return list ;
}
/**
* Retrieving this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init passed values
fragNum = getArguments() != null ? getArguments().getInt("val") : 1;
item_name=getArguments().getStringArrayList("itemName");
item_cost=getArguments().getStringArrayList("itemCost");
}
/**
* to set view to the fragment activity
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_pager_list,
container, false);
lvsoups = (ListView) layoutView.findViewById(R.id.listMenu);
myAdapter = new MyAdapter(getActivity(), item_name,item_cost);
lvsoups.setAdapter(myAdapter);//set adapter to the list view
return layoutView;
}
//adapter for the listview
public class MyAdapter extends BaseAdapter {
ArrayList<String> itemName;
ArrayList<String> itemCost;
Context context;
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<String> item_name, ArrayList<String> item_cost) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(item_name!=null)
{
// arr = new String[objects.length];
this.itemName = item_name;
this.itemCost=item_cost;
}
}
#Override
public int getCount() {
return itemName.size();
}
#Override
public Object getItem(int position) {
return itemName.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int value;
View menuRow = inflater.inflate(R.layout.hotel_menu_list_item, null);
TextView tvSoups = (TextView) menuRow.findViewById(R.id.tvMenuItem); //To set name of menu item, for example Corn Soup
TextView tvPrice = (TextView) menuRow.findViewById(R.id.tvMenuPrice); //To set price of that item
CheckBox cbQty = (CheckBox) menuRow.findViewById(R.id.cbMenuItem);
Spinner spQty = (Spinner) menuRow.findViewById(R.id.spinnerQty);
String[] quantity = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
ArrayAdapter spinnerAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, quantity);
spQty.setAdapter(spinnerAdapter);
tvSoups.setText(itemName.get(position));
tvPrice.setText(itemCost.get(position));
Log.e("arr", itemName.get(position));
if (cbQty.isChecked()) {
value = 1;
} else {
value = 0;
}
menuRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent=new Intent(SearchResult.this,RestMainActivity.class);
// intent.putExtra("Hotel_Master_Id",hotelMasterIdList.get(position));
// startActivity(intent);
}
});
return menuRow;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
This is my hotel_menu_list_item.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:weightSum="5">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cbMenuItem" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_weight="3"
android:id="#+id/tvMenuItem" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_weight="1"
android:id="#+id/tvMenuPrice" />
<Spinner
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/spinnerQty"
android:layout_weight="1"
>
</Spinner>
</LinearLayout>

Related

OnClickListener not working with fragments

I'm cant get the onclicklistener to work with fragments. I've searched stackoverflow and tried all the tips but i still cant get it to work. So i do my first post here. I've tried adding android:focusable="false", android:clickable="false" and android:descendantFocusability="blocksDescendants" to the layouts with no luck. Ive removed them because they make no difference. I've tried other solutions as well but none of them works. This is my first post so if i posted something wrong let me know and ill redo it, I've borrowed someones customlist just to get a working example.
Here is one of the fragments i want a clickable list in
public class ActivitiesFragment extends Fragment {
ListView list;
String[] maintitle ={
"Aktivitet 1","Aktivitet 2",
"Aktivitet 3","Aktivitet 4",
"Aktivitet 5",
};
String[] subtitle ={
"A","B",
"C","D",
"E",
};
Integer[] imgid={
R.drawable.ic_dashboard_black_24dp,R.drawable.ic_dashboard_black_24dp,
R.drawable.ic_dashboard_black_24dp,R.drawable.ic_dashboard_black_24dp,
R.drawable.ic_dashboard_black_24dp,
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activities, container, false);
MyListAdapter adapter = new MyListAdapter(getActivity(), maintitle, subtitle,imgid);
list = (ListView) rootView.findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0) {
Toast.makeText(getActivity().getApplicationContext(),"One",Toast.LENGTH_SHORT).show();
}
else if(position == 1) {
Toast.makeText(getActivity().getApplicationContext(),"Two",Toast.LENGTH_SHORT).show();
}
else if(position == 2) {
Toast.makeText(getActivity().getApplicationContext(),"Three",Toast.LENGTH_SHORT).show();
}
else if(position == 3) {
Toast.makeText(getActivity().getApplicationContext(),"Four",Toast.LENGTH_SHORT).show();
}
else if(position == 4) {
Toast.makeText(getActivity().getApplicationContext(),"Five",Toast.LENGTH_SHORT).show();
}
}
});
return rootView;
}
}
Here is the Adapter:
public class MyListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] maintitle;
private final String[] subtitle;
private final Integer[] imgid;
public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Integer[] imgid) {
super(context, R.layout.mylist, maintitle);
// TODO Auto-generated constructor stub
this.context=context;
this.maintitle=maintitle;
this.subtitle=subtitle;
this.imgid=imgid;
}
public View getView(int position,View rowView,ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.mylist, null,true);
TextView titleText = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
titleText.setText(maintitle[position]);
imageView.setImageResource(imgid[position]);
subtitleText.setText(subtitle[position]);
return rowView;
}
}
The xml for the fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp"/>
</RelativeLayout>
The xml for the list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="10dp" />
</LinearLayout>
</LinearLayout>
Here's whole implementation of RecyclerView with item click listener.
Fragment:
public class MyFragment extends Fragment implements ItemClickListener {
RecyclerView rvList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_activities, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
rvList = view.findViewById(R.id.rvList);
ArrayList<ItemData> list = new ArrayList<>();
list.add(new ItemData("Aktivitet 1","A",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 2","B",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 3","C",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 4","D",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 5","E",R.drawable.ic_dashboard_black_24dp))
RVAdapter adapter = new RVAdapter(this, list);
rvList.setLayoutManager(new LinearLayoutManager(getContext()));
rvList.setAdapter(adapter);
}
#Override
public void onItemClicked(ItemData data, int position) {
// item click will be listened here
Toast.makeText(getContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
Fragment Layout: frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Layout for the list: item.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"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#4d4d4d"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
RecyclerView ViewHolder:
public class RecyclerVH extends RecyclerView.ViewHolder {
private TextView titleText;
private ImageView imageView;
private TextView subtitleText;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
titleText = itemView.findViewById(R.id.title);
imageView = itemView.findViewById(R.id.icon);
subtitleText = itemView.findViewById(R.id.subtitle);
}
void bind(ItemData data) {
titleText.setText(data.getMainTitle());
imageView.setImageResource(data.getImgId());
subtitleText.setText(data.getSubTitle());
}
}
RecyclerView Adapter:
public class RVAdapter extends RecyclerView.Adapter<RecyclerVH> {
private ArrayList<ItemData> list;
private ItemClickListener listener;
public RVAdapter(ItemClickListener listener, ArrayList<ItemData> list) {
this.list = list;
this.listener = listener;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final RecyclerVH holder, int position) {
holder.bind(list.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClicked(list.get(holder.getAdapterPosition()),
holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return list.size();
}
}
interface ItemClickListener {
void onItemClicked(ItemData data, int position);
}
Update 1:
Add these lines to the root tag of item layout:
android:focusable="true"
android:clickable="true"
Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:clickable="true"
android:orientation="horizontal">
...
</LinearLayout>
Time ago I had a similar problem, with an ImageView in my list item. My solution was changing android:focusable to false inside the ImageView block. I never knew why, but it worked fine.
Anyway, I strongly recommend to start using RecyclerView and ViewHolder pattern. https://developer.android.com/guide/topics/ui/layout/recyclerview
It's much more powerful, flexible and a major enhancement over ListView.

how to save the editText values into an array or arrayList in a viewPager which extends PagerAdapter

I have an activity which parses the json & sends its values to viewPager
public class SwipeQuestions extends AppCompatActivity {
// Declare Variables
ViewPager viewPager;
PagerAdapter adapter;
ArrayList<String> questions = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_questions);
viewPager = findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(10);
adapter = new ViewPagerAdapter(SwipeQuestions.this, questions);
viewPager.setAdapter(adapter);
}
}
& its XML(activity_swipe_questions) is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
each question should appear in separate view with a editText where the user can enter the text & on the last question there will be a submit button which will save all the editText values in to an array or arrayList.
The Viewpager Adapter class is extending PagerAdapter is defined below
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
private Context context;
LayoutInflater inflater;
Button submitButton;
private ArrayList<String> enteredAnswerArray = new ArrayList<String>();
private ArrayList<String> questions;
public ViewPagerAdapter(Context context, ArrayList<String> questions) {
this.context = context;
this.questions = questions;
}
#Override
public int getCount() {
return questions.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView txtQuestion;
EditText enteredAnswer;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,false);
txtQuestion = itemView.findViewById(R.id.question); // Locate the TextViews in viewpager_item.xml
txtQuestion.setText(questions.get(position)); // Capture position and set to the TextViews
submitButton = itemView.findViewById(R.id.submit_btn);
enteredAnswer = itemView.findViewById(R.id.answer_textbox);
if(position == (questions.size()-1)){
submitButton.setVisibility(View.VISIBLE);
}
else {
submitButton.setVisibility(View.GONE);
}
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.out.println(enteredAnswerArray.size());
// System.out.println("0"+enteredAnswerArray.get(0));
// System.out.println("1"+enteredAnswerArray.get(1));
Log.i("clicked", "button izz clicked");
}
});
(container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
(container).removeView((RelativeLayout) object); // Remove viewpager_item.xml from ViewPager
}
}
& its XML(viewpager_item) is defined below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="10dp" >
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/answer_textbox"
android:text="Question" />
<EditText
android:id="#+id/answer_textbox"
style="#android:style/Widget.DeviceDefault.EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/question"
android:ems="10"
android:fontFamily="casual"
android:inputType="textMultiLine|textImeMultiLine"
android:singleLine="false" />
<Button
android:id="#+id/submit_btn"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/answer_textbox"
android:text="Submit"/>
</RelativeLayout>
Now for every question the user has entered some text in the editText fields & i want to save each editText value to an array or arrayList on click of submit button which is on the last view of viewPager.
Rite now i've 10 questions so i set viewPager.setOffscreenPageLimit() to 10 so that the values entered by the user doesn't get deleted as user slides the screen
Can anyone help me out how the save the editText values in a viewPager.
I googled a lot But couldn't find anything relevant
The easiest solution is to:
Create an ArrayList enteredAnswers in the ViewPagerAdapter class and add it's items in your instantiateItem method
Create a method that iterates the enteredAnswers list and returns a list of String with the written answers
Be careful to write all the necessary null checks

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.

Get view for button click on the Fragment of the ViewPager

I have successfully set up the a FragmentActivity with FragementPagerAdapter associated with ViewPager to implement two tabbed application .
One of the Tabs namely "Wave" has a text view and a button . All I want is call textview.setText method via the onClick method of button described by its xml attribute .
I do not know where should I initialize my TextView or Button , how can I get the context of Wave tab and where should I write onclick method-
public class InformationShow extends FragmentActivity {
XMLdata dataObject;
ViewPager viewPager;
PagerAdapter adpt;
Fragment temp;
TextView tv;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewPager=(ViewPager)findViewById(R.id.pager);
adpt = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adpt);
// temp=adpt.fg.findFragmentById((int)adpt.getItemId(1));
tv=(TextView)findViewById(R.id.graphWaveTextView);
bt = (Button)findViewById(R.id.button1);
}
public void changeText(View v){
tv.setText("It worked ");
}
Adapter Class
public class PagerAdapter extends FragmentPagerAdapter {
int count = 2;
CharSequence namme[] = {"Temperature","Wave"};
XMLdata data;
FragmentManager fg;
public PagerAdapter(FragmentManager fragmentManager ){
super(fragmentManager);
this.fg = fragmentManager;
}
Context context;
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:{
TemperatureGraphFrag temp = new TemperatureGraphFrag();
return temp;
}
case 1:{WaveHeightGraphFrag wave = new WaveHeightGraphFrag();
return wave;
}
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return namme[position];
}
}
Fragments Class
public class TemperatureGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_t, container, false);
return view;
}
}
public class WaveHeightGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_sig_wave_height, container, false);
return view;
}
}
fragment_main XML implemented by FragmentActicity
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#65C2C9"
android:scrollbarSize="5dp"/>
</android.support.v4.view.ViewPager>
Tab 2 Fragment XML graph_sig_wave_height
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/graphWaveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"
android:onClick="changeText"/>
</LinearLayout>
Tab 1 fragment layout XML graph_t
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linearTemp"
>
<TextView
android:id="#+id/graphTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center"
/>
</LinearLayout>
Add the following method to your WaveHeightGraphFrag class:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
final TextView t = (TextView) view.findViewById(R.id.graphWaveTextView);
Button b = (Button) view.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
t.setText("It worked ");
}
});
}
This is what you want.

Android - ListView refresh/update from the Main Activity where it is called

I have an application that lists the values of a product by Variant, Unit, and Quantity.
I have an activity where the ListView is shown:
public class OrderForm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
lv1.setAdapter(new CustomListAdapter(this, image_details));
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
OrderDetailsClass orderData = new OrderDetailsClass();
return results;
}
public void onAddItem(View view){
ArrayList results = new ArrayList();
OrderDetailsClass orderData = new OrderDetailsClass();
orderData = new OrderDetailsClass();
orderData.setVariants("Flavored");
orderData.setUnit("cans");
orderData.setQuantity(1);
results.add(orderData);
//selectVariant();
//selectUnit();
//selectQuantity();
}
}
This is my CustomAdapter
public class CustomListAdapter extends BaseAdapter {
private ArrayList<OrderDetailsClass> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<OrderDetailsClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.variantView = (TextView) convertView.findViewById(R.id.variant);
holder.unitView = (TextView) convertView.findViewById(R.id.unit);
holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.variantView.setText(listData.get(position).getVariants());
holder.unitView.setText("By, " + listData.get(position).getUnit());
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantity()));
return convertView;
}
static class ViewHolder {
TextView variantView;
TextView unitView;
TextView quantityView;
}
public void updateResults(ArrayList<OrderDetailsClass> results) {
listData = results;
//Triggers the list update
notifyDataSetChanged();
}
}
This is list_row_layout
<?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="match_parent" >
<!--
android:minHeight="50dp"
android:orientation="horizontal"
android:padding="5dip"
-->
<TextView
android:id="#+id/variant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="variant" />
<TextView
android:id="#+id/unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="unit" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="quantity" />
</RelativeLayout>
This is the activity_order_form
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/custom_list"
android:layout_width="fill_parent"
android:layout_height="386dp"
android:dividerHeight="1dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="onAddItem"
android:text="Add" />
</RelativeLayout>
What I want to do is that when I press the onAddItem function, after the data has been added, the ListView will refresh and display the changes. So far, what I've seen is that notifyDataSetChanged() being used in the BaseAdapter class. I've tried it but it seems that notifyDataSetChanged() should be called within BaseAdapter, I want to be able to refresh from my OrderForm activity.
Any ideas?
Thanks.
Keep a reference to your CustomAdapter in OrderForm activity:
public class OrderForm extends Activity {
CustomListAdapter customListAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
customListAdapter = new CustomListAdapter(this, image_details);
lv1.setAdapter(customListAdapter);
}
Then you can call customAdapter.notifyDataSetChanged(). This is a public method on the adapter so you can call it from the activity just fine.

Categories

Resources