This question already has answers here:
Cardview onclick opens a new activity
(2 answers)
Closed 6 years ago.
Everytime I click a different card an activity will be called like that EvsActivity.
But if no. of cards are 100 then i have to create 100 activity which is not a feasible solution.
so anybody with a better solution plz ur help will be appreciated
//Recyclerview with cardview code
package com.studyleague.app;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class AvailableContent extends TemplateFragment {
#Bind(R.id.available_recycler_view)
RecyclerView recyclerView;
public AvailableContent() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.available_content, container, false);
ButterKnife.bind(this, v);
recyclerView.setHasFixedSize(true);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 2, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(glm);
List<AvailableContentModel> content = new ArrayList<>();
for (int i = 0; i < AvailableContentData.acName.length; i++) {
content.add(new AvailableContentModel(AvailableContentData.acIcon[i], AvailableContentData.acName[i]));
}
final AvailableContentAdapter contentAdapter = new AvailableContentAdapter(getActivity(), content);
recyclerView.setAdapter(contentAdapter);
return v;
}
}
//Adapter//
package com.studyleague.app;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class AvailableContentAdapter extends RecyclerView.Adapter<AvailableContentAdapter.ContentViewHolder> {
private final List<AvailableContentModel> dataSet;
private Context context;
public ArrayList<AvailableContentModel> content;
public AvailableContentAdapter(Context context, List<AvailableContentModel> content) {
this.context = context;
this.dataSet = content;
}
#Override
public ContentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.available_content_card, parent, false);
return new ContentViewHolder(view);
}
#Override
public void onBindViewHolder(final ContentViewHolder hold, final int listPosition) {
hold.acImg.setImageResource(dataSet.get(listPosition).getContentImg());
hold.acText.setText(dataSet.get(listPosition).getContentName());
}
#Override
public int getItemCount() {
return dataSet.size();
}
public class ContentViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.available_card_image_view)
ImageView acImg;
#Bind(R.id.available_card_text_view)
TextView acText;
public ContentViewHolder(final View view) {
super(view);
ButterKnife.bind(this, view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (getAdapterPosition()) {
case 0:
Toast.makeText(v.getContext(), "Mechanics", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(v.getContext(), "B. E. E.", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(v.getContext(), "Maths", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(v.getContext(), "Chemistry", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(v.getContext(), "Physics", Toast.LENGTH_SHORT).show();
break;
case 5:
context.startActivity(new Intent(context, EvsActivity.class));
break;
default:
Toast.makeText(v.getContext(), "YOLO", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
}
//Activity that is called when i click one of the card//
package com.studyleague.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class EvsActivity extends AppCompatActivity {
#Bind(R.id.exp_list)
ExpandableListView expListView;
private List<String> chap;
private HashMap<String, List<String>> hashMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_evs);
ButterKnife.bind(this);
// preparing list data
prepareListData();
// setting list adapter
ExpandableListAdapter listAdapter = new ExpandableListAdapter(this, chap, hashMap);
expListView.setAdapter(listAdapter);
// expListView on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String groupName = chap.get(groupPosition);
String childName = hashMap.get(groupName).get(childPosition);
Toast.makeText(getApplication(), groupName + " : " + childName, Toast.LENGTH_SHORT)
.show();
Intent i = new Intent(EvsActivity.this, Study.class);
startActivity(i);
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
// Hash map for both header and child
hashMap = new HashMap<>();
// Array list for header
chap = new ArrayList<>();
// Adding headers to list
chap.add("1. Multidisciplinary Nature of Environmental Studies");
chap.add("2. Sustainable Development");
chap.add("3. Environmental Pollution");
chap.add("4. Environmental Legislation");
chap.add("5. Renewable Sources of Energy");
chap.add("6. Environment and Technology");
chap.add("7. Another Chapter");
chap.add("8. Almost Another Chapter");
// Array list for child items
List<String> child1 = new ArrayList<>(fillChildData(1, 5));
List<String> child2 = new ArrayList<>(fillChildData(2, 3));
List<String> child3 = new ArrayList<>(fillChildData(3, 11));
List<String> child4 = new ArrayList<>(fillChildData(4, 6));
List<String> child5 = new ArrayList<>(fillChildData(5, 4));
List<String> child6 = new ArrayList<>(fillChildData(6, 2));
List<String> child7 = new ArrayList<>(fillChildData(7, 2));
List<String> child8 = new ArrayList<>(fillChildData(8, 2));
// Adding header and children to hash map
hashMap.put(chap.get(0), child1);
hashMap.put(chap.get(1), child2);
hashMap.put(chap.get(2), child3);
hashMap.put(chap.get(3), child4);
hashMap.put(chap.get(4), child5);
hashMap.put(chap.get(5), child6);
hashMap.put(chap.get(6), child7);
hashMap.put(chap.get(7), child8);
}
private Collection<String> fillChildData(int index, int n) {
List<String> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add("Group " + index + " - Child : " + (i + 1));
}
return list;
}
}
//Code of data incase needed//
package com.studyleague.app;
public class AvailableContentData {
static final Integer[] acIcon = {
R.mipmap.mec,
R.mipmap.elec,
R.mipmap.mat,
R.mipmap.chem,
R.mipmap.ic,
R.mipmap.env
};
static final String[] acName = {
"Mechanics",
"B. E. E.",
"Maths",
"Chemistry",
"Physics",
"E. V. S."
};
}
Typed this up under the wrong account (cant comment, sorry), didn't stick I guess. You create one Activity with one ListView and pass in the adapter that you want to use from the CardView intent.
Butterfly Cardview -> BUTTERFLY -> ButterflyAdapter
Baseball Bat Cardview -> BASEBALL -> BaseballBatAdatper
if your items are not related. If they are related you can use the same adapter but send in a different layout based on what you sent in.
Butterfly -> R.layout.butterfly_items
Whale -> R.layout.whale_items
Related
I'm developing in Android Studio.
I have a ListView that every item in it contains number of elements including 2 Buttons:increase/decrease and a EditText filed:edit_txt .
I need that in each click on the button "increase" will increase the number in the edit_txt filed.
As well as in every click on the button "decrease" it will decrease the number in the edit_txt filed.
how do i make it work?
The class called "ProductList" and it expands AppCompatActivity.
package com.example.yuliaaa.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ProductList extends AppCompatActivity {
private List<myProductsView> myProducts_types = new ArrayList<myProductsView>();
ArrayAdapter<myProductsView> adapter;
private ArrayList<myProductsView> choosen_items = new ArrayList<myProductsView>();
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pop_productlist);
populateProductsList();
populateListView();
}
private void populateProductsList() {
myProducts_types.add(new myProductsView("p1", "d1", 1111, 12.90, R.drawable.cereal, 1));
myProducts_types.add(new myProductsView("p2", "dddd", 1112, 10.90, R.drawable.cereal, 2));
myProducts_types.add(new myProductsView("p3", "ffff", 1112, 30.00, R.drawable.cereal, 1));
myProducts_types.add(new myProductsView("p4", "kkkkk", 1112, 20.00, R.drawable.cereal, 3));
}
private void populateListView() {
adapter = new MyListAdapter();
list = (ListView) findViewById(R.id.product_list);
list.setAdapter(adapter);
}
public void StartCalck(View view){
Intent intent = new Intent(ProductList.this, SplitBuying.class);
startActivity(intent);
}
public void deleteItems(View view){
for(int i=0;i<choosen_items.size();i++){
adapter.remove(choosen_items.get(i));
}
}
public class MyListAdapter extends ArrayAdapter<myProductsView>{
public MyListAdapter(){
super(ProductList.this, R.layout.pop_productlist, myProducts_types);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//make sure we have a view to work with(may have been given null
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.product_item_view, parent, false);
}
//we need to populate the list
//find the product to work with
final myProductsView currentProduct = myProducts_types.get(position);
//fill the view
final CheckBox checkBox = (CheckBox)itemView.findViewById(R.id.product_checkBox);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choosen_items.add(currentProduct);
}
});
TextView productname = (TextView) itemView.findViewById(R.id.product_name);
productname.setText(currentProduct.getProductName());
EditText quantity = (EditText)itemView.findViewById(R.id.edit_text);
quantity.setText(String.valueOf(currentProduct.getQuantity()));
Button increase = (Button)itemView.findViewById(R.id.btn_plus);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return itemView;
}
}
}
The class myProductsView is class that represent a product.
The productlist.xml contains the ListView with the id: mylist.
And the product_item_view.xml which is how every item in the list view would look like contains:
-Checkbox:"product_checkBox"
-TextView:"product_name"
-Button:"btn_plus"
-EditText:"edit_text"
-Button:"btn_minus"
thank you,
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myProducts_types.add(new myProductsView("p5", "abc", 100, 100.00, R.drawable.wheat, 4));
adapter.notifyDataSetChanged();
}
});
I am working on Calendar App to display list of items selected by user. i have set adapter in fragment with 2 array_lists(one for image resources and other for items name) and size of list but rather than to display particular number of list items only first item is coming and get_View method is calling 10 times just for first list element and only one item comes to display.
code of ItemSelectedclass
package shopping.com.shopping.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.ArrayList;
import shopping.com.shopping.R;
public class ItemSelected extends BaseAdapter {
Context mContext;
int limit;
int count=0;
ScrollView sc_list;
private LayoutInflater inflater = null;
String item_name[]={"Egg","Bread","Milk","Watercan","Fruit","Egg","Bread"};
int imgsrc[]={R.drawable.smallegg,R.drawable.smallbread,R.drawable.smallmilk,R.drawable.smallwatert,R.drawable.smallapple,R.drawable.smallegg,R.drawable.smallbread};
ArrayList<String> listofIndexes,listofquantities;
ArrayList<String> location_or_society_details;
public ItemSelected(Context context ,ArrayList<String> listofIndexes,ArrayList<String> listofquantities,int limit) {
// "imgsrc" is the image-reference of selected item from the list
// "quantity" is the quantity of selected item which customer want to book
// "imgTitle" is the name of selected img like milk,bread,watertank
// "getimgSrc[]" is the array which contains refrences of all the items
// "get_title" is the array which contains all the items names
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
this.limit=limit;
this.listofIndexes=listofIndexes;
this.listofquantities=listofquantities;
}
#Override
public int getCount() {
return limit;
}
#Override
public Object getItem(int position) {
return this.listofIndexes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Log.d("testing","afzal");
count++;
TextView i_name=null,i_count=null;
ImageView i_image=null;
if(convertView == null) {
inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.items_list, null);
}
i_image = (ImageView) view.findViewById(R.id.i_image);
i_name = (TextView) view.findViewById(R.id.i_name);
i_count = (TextView) view.findViewById(R.id.i_count);
i_name.setText("testing");
i_count.setText("count");
i_image.setImageResource(R.drawable.logo);
//setting respective value of Booked list_items with 'Item_name' and their 'Quantity'. suppose first user select item#5 with quantity 5 then item#2 with quatity 9 and so on, then first child of listView should b item#5 with quant 5 second list_item should be 2 with quantity 9 and so on
// String index= listofIndexes.get(position);
// String quantity=listofquantities.get(position);
// i_name.setText(item_name[Integer.parseInt(index)]);
// i_image.setImageResource(imgsrc[Integer.parseInt(index)]);
// i_count.setText(Integer.parseInt(quantity));
return view;
}
}
code for TabFragment1 class
package shopping.com.shopping.fragmensts;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.Toast;
import com.samsistemas.calendarview.widget.CalendarView;
import com.samsistemas.calendarview.widget.DayView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import shopping.com.shopping.R;
import shopping.com.shopping.activities.ListItemsActivity;
import shopping.com.shopping.activities.SetOrder;
import shopping.com.shopping.activities.SignUpSignIn;
import shopping.com.shopping.adapter.ItemSelected;
import shopping.com.shopping.adapter.PagerAdapter;
public class TabFragment1 extends Fragment implements View.OnClickListener{
private CalendarView mCalendarView;
private View myFragmentView;
Button btn;
ItemSelected adapter;
ListView listview;
LinearLayout l_lay;
ScrollView scroll;
ArrayList<String> listofIndexes,listofquantities;
int iTem_Index=3;
String item_name[]={"Egg","Bread","Milk","Watercan","Fruit","Egg","Bread"};
int imgsrc[]={R.drawable.smallegg,R.drawable.smallbread,R.drawable.smallmilk,R.drawable.smallwatert,R.drawable.smallapple,R.drawable.smallegg,R.drawable.smallbread};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView= inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
mCalendarView = (CalendarView) myFragmentView.findViewById(R.id.calendar_view);
btn= (Button) myFragmentView.findViewById(R.id.try_it_now);
l_lay = (LinearLayout) myFragmentView.findViewById(R.id.linear);
listview = (ListView) myFragmentView.findViewById(R.id.booked_item);
scroll=(ScrollView)myFragmentView.findViewById(R.id.scroll_list);
SharedPreferences sh_pref=getActivity().getSharedPreferences("backToHome", Context.MODE_PRIVATE);
int flag= sh_pref.getInt("flag", 0);
String item=sh_pref.getString("item","null");
int quantity=sh_pref.getInt("quantity",0);
//if user has booked something then listView in home page will be visible
if(flag==3){
int count=0;
try {
listofIndexes=new ArrayList<String>();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(getActivity().openFileInput("ItemsBooked")));
String readItem;
StringBuffer stringBuffer = new StringBuffer();
while ((readItem = inputReader.readLine()) != null){
listofIndexes.add(readItem);
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
listofquantities=new ArrayList<String>();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(getActivity().openFileInput("Quantity")));
String readQuantity;
StringBuffer stringBuffer = new StringBuffer();
while ((readQuantity = inputReader.readLine()) != null) {
count++;
Toast.makeText(getActivity(), "count is .."+count, Toast.LENGTH_SHORT).show();
listofquantities.add(readQuantity);
}
}
catch (IOException e) {
e.printStackTrace();
}
l_lay.setVisibility(View.GONE);
scroll.setVisibility(View.VISIBLE);
listview.setVisibility(View.VISIBLE);
// after matching and verifying, adding "item" into the array list
adapter= new ItemSelected(getActivity(),listofIndexes,listofquantities,count);
listview.setAdapter(adapter);
}
btn.setOnClickListener(this);
//put intent
mCalendarView.setFirstDayOfWeek(Calendar.SUNDAY);
mCalendarView.setIsOverflowDateVisible(true);
mCalendarView.setCurrentDay(new Date(System.currentTimeMillis()));
mCalendarView.setNextButtonColor(R.color.colorAccent);
mCalendarView.refreshCalendar(Calendar.getInstance(Locale.getDefault()));
mCalendarView.setNextButtonColor(R.color.bg_for_selecte_dday);
mCalendarView.setBackButtonColor(R.color.bg_for_selecte_dday);
//get current date
Date date=new Date(System.currentTimeMillis());
mCalendarView.setCurrentDay(date);
mCalendarView.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
#Override
public void onDateSelected(#NonNull Date selectedDate) {
Toast.makeText(getActivity(), "second date is selected", Toast.LENGTH_SHORT).show();
mCalendarView.setSelectedDayBackground(getResources().getColor(R.color.white));
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
}
});
mCalendarView.setOnMonthChangedListener(new CalendarView.OnMonthChangedListener() {
#Override
public void onMonthChanged(#NonNull Date monthDate) {
SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy", Locale.getDefault());
}
});
final DayView dayView = mCalendarView.findViewByDate(new Date(System.currentTimeMillis()));
return myFragmentView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.try_it_now:
Intent i=new Intent(getActivity(),ListItemsActivity.class);
i.putExtra("flag", 3);
startActivity(i);
}
}
}
I am unable to comment due to low reputation. Kindly post the layout files. Also, instead of using two arraylists and a count variable, create a model class. It will make your code clean and easy to manage.
Refer point no. 12 and 13 from this link http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
I am trying to get an index of a item in an array that is selectable in a list view. The only issue is that when i click on the item, it only returns the index of -1 which means that it doesnt match when in fact there should be a match. Thanks in advanced!
package com.goldleaf.branden.goldleafcomics;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.kosalgeek.android.json.JsonConverter;
import com.kosalgeek.genasync12.*;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GlimpseListFragment extends ListFragment {
List<String> glimpse = new ArrayList<String>();
List<String> titles = new ArrayList<String>();
List<UniverseListing> universalListings = new ArrayList<UniverseListing>();
public GlimpseListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_glimpse_list, container, false);
return rootView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "http://goldleafcomics.com/application/UniverseGlimpse.JSON";
PostResponseAsyncTask task = new PostResponseAsyncTask(getActivity(), new AsyncResponse() {
#Override
public void processFinish(String s) {
universalListings = new JsonConverter<UniverseListing>().toArrayList(s, UniverseListing.class);
Toast.makeText(getActivity(), "Application Data Refreshed", Toast.LENGTH_LONG).show();
ArrayList<String> glimpse = new ArrayList<String>();
for(UniverseListing value: universalListings){
glimpse.add(value.universeGlimpse);
}
ArrayList<String> titles = new ArrayList<String>();
for(UniverseListing value: universalListings){
titles.add(value.universeId);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
}
});
task.execute(url);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String value = (String)getListAdapter().getItem(position);
int index = this.titles.indexOf(value);
String value2 = Integer.toString(index);
Toast.makeText(getActivity(), value2, Toast.LENGTH_LONG).show();
}
}
you define glimpse two times, could you try to make those changes,
List<String> glimpse;
and inside onCreate initialize it
glimpse = new ArrayList<>();
and do the same for titles and universalListings.
Try using these two sections of code. You are shadowing the member variables with local variables of the same name.
public class GlimpseListFragment extends ListFragment {
List<String> glimpse;
List<String> titles;
List<UniverseListing> universalListings;
Later...
glimpse = new ArrayList<String>();
for(UniverseListing value: universalListings){
glimpse.add(value.universeGlimpse);
}
titles = new ArrayList<String>();
for(UniverseListing value: universalListings){
titles.add(value.universeId);
}
You don't need to initialize Arraylists with the class. You should typically lazily initialize them (in other words, when you need to)
I have been searching about this issue but still I am not very clear on how to use a click listener with an array adapter.
I need a click listener for each item of the list.
Codes:
The Area item:
package fogames.tamagomonsters;
public class Area {
public String name;
public String number;
public Area(String name, String number) {
this.name = name;
this.number = number;
}
}
The array adapter:
package fogames.tamagomonsters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class AreasAdapter extends ArrayAdapter<Area> {
public AreasAdapter(Context context, ArrayList<Area> Areas) {
super(context, 0, Areas);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Area Area = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_area, parent, false);
}
// Lookup view for data population
TextView tvname = (TextView) convertView.findViewById(R.id.tvName_area);
TextView tvnumber = (TextView) convertView.findViewById(R.id.tvNumber_of_beasts);
// Populate the data into the template view using the data object
tvname.setText(Area.name);
tvnumber.setText(Area.number);
// Return the completed view to render on screen
return convertView;
}
}
The activity:
package fogames.tamagomonsters;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import java.util.ArrayList;
public class PlayMenuActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
FrameLayout fl = new FrameLayout(this);
fl.setBackgroundColor(Color.argb(255, 0, 0, 0));
// Construct the data source
ArrayList<Area> arrayOfAreas = new ArrayList<Area>();
// Create the adapter to convert the array to views
AreasAdapter adapter = new AreasAdapter(this, arrayOfAreas);
// Attach the adapter to a ListView
ListView lv = new ListView(this);
lv.setAdapter(adapter);
// Restore preferences
SharedPreferences prefs = getSharedPreferences(PreferenceConstants.PREFERENCE_NAME, MODE_PRIVATE);
int mlen = prefs.getInt(PreferenceConstants.MLEN, 0);
long money = prefs.getLong(PreferenceConstants.MONEY, 0);
int mall = 6; //hay que ver que hacer con esto...
int eqall = 3; //igual
boolean[] mgot = new boolean[mall];
int[] exp = new int[eqall];
int[] lvl = new int[eqall];
int[] at = new int[eqall];
int[] en = new int[eqall];
for (int i = 0; i < mall; i++) {
mgot[i] = prefs.getBoolean(PreferenceConstants.MGOT[i], false);
}
for (int i = 0; i < eqall; i++) {
exp[i] = prefs.getInt(PreferenceConstants.EXP[i], 0);
lvl[i] = prefs.getInt(PreferenceConstants.LVL[i], 0);
at[i] = prefs.getInt(PreferenceConstants.AT[i], 0);
en[i] = prefs.getInt(PreferenceConstants.EN[i], 0);
}
String name[] = {getString(R.string.a001)};
int prado_got = 0;
if (mgot[0]) {
prado_got += 1;
}
if (mgot[3]) {
prado_got += 1;
}
String prado = String.valueOf(prado_got) + " / 2";
String number[] = {prado};
// Add item to adapter
Area a001 = new Area(name[0], number[0]);
adapter.add(a001);
this.setContentView(fl);
}
}
Thank you in advance.
You can do something like that:
•First insert in your adapter this method
#Override
public Area getItem(int position) {
return [yourArrayAreas].get(position);
}
•Then, in your Activity...
final AreasAdapter adapter = new AreasAdapter(this, arrayOfAreas);
ListView lv = new ListView(this);
lv.setAdapter(adapter);
mListStopsMuni.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id{
Area yourClickArea = adapter.getItem(position);
//Rest of code...
}
});
Good luck ;)
Something like this:
ArrayList<Area> arrayListAreas;
public AreasAdapter(Context context, ArrayList<Area> Areas) {
super(context, 0, Areas);
this.arrayListAreas = Areas;
}
//And then....
#Override
public Area getItem(int position) {
return arrayListAreas.get(position);
}
I have a ListFragment that contains a list of items. I would like to load say 9 items at a time and when i scroll and reach the bottom of the listview i want to load another 9 items in background.
I make 2 request to my web server:
1) to get all the item id's of the items, by a searh() method
2) to get all the item details of a specific item though its id, by getId(id) method
The version i have implemented gets all the ids and then loads all the items at once in the doInBackground method of AsyncTask and it works. and it takes very long (i dont want a button because its really ugly).
I'd like to introduce this thing about the onScrollListener so that when i first open my app, in background i get all the ids, and then i get the first 9 items and show them. then when i scroll to the end i want to load the next 9 items. How do i do this?
I have read a few posts but it not clear to me, especially due to the fact that i have 2 functions that need to be run in background, 1 function needs to be run once while the other many times and i need to keep track of which id's i getting.
I would also if possible like to add the function that if i pull the ListView a little then it should update my view.
Here is my code:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.adapter.ListViewAdapter;
import com.prjma.lovertech.util.MVPFunctions;
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
return rootView;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//Here i get all the id's
ArrayList<Long> ids = MVPFunctions.getMioSingolo().search();
//for each id get all its details and put it in a map
items = new ArrayList<HashMap<String, Object>>();
for(int i=0; i < ids.size(); i++){
items.add(MVPFunctions.getMioSingolo().getItem(ids.get(i)));
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
// dismiss the dialog after getting all products
progressDialog.dismiss();
//showProgress(false);
if (items.get(0).get("status error")!= null){
Toast.makeText(getActivity(), "status error = " + items.get(0).get("status error"), Toast.LENGTH_LONG).show();
Log.i("status error put toast", (String) items.get(0).get("status error"));
//fai qualcosa, tipo torna indietro, ecc
}
// updating UI from Background Thread
ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
// updating listview
listView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
mDownloadTask = null;
//showProgress(false);
}
}
}
Adapter class:
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.activity.DettagliActivity;
import com.prjma.lovertech.model.Item;
public class ListViewAdapter extends ArrayAdapter<String> {
private static LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
//public ImageLoader imageLoader;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<HashMap<String, Object>> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = new ViewHolder();
if (row == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listview_item_row, null);
viewHolder.ic_thumbnail = (ImageView)row.findViewById(R.id.ic_thumbnail);
viewHolder.scadenza = (TextView)row.findViewById(R.id.tvScadenza);
viewHolder.prezzo = (TextView)row.findViewById(R.id.tvPrezzo);
viewHolder.followers = (TextView)row.findViewById(R.id.tvFollowers);
viewHolder.hProgressBar = (ProgressBar)row.findViewById(R.id.hProgressBar);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)row.getTag();
}
HashMap<String, Object> item = items.get(position);
viewHolder.ic_thumbnail.setImageBitmap((Bitmap) item.get("pic1m"));
viewHolder.scadenza.setText((CharSequence) item.get("scadenza"));
viewHolder.prezzo.setText((CharSequence) item.get("prezzo"));
viewHolder.followers.setText((CharSequence) item.get("followers"));
viewHolder.hProgressBar.setProgress((Integer) item.get("coefficient"));
//row.onListItemClick(new OnItemClickListener1());
row.setOnClickListener(new OnItemClickListener(position));
return row;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
static class ViewHolder {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
}
}
In your adapter, check how close the user is from the bottom of the data set. When they get to the end, call a method that fetches more items from the network. I normally use a "REFRESH_THRESHOLD" integer to prefetch items before they're needed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item current = getItem(position);
//Pre-fetch
if(getCount() - position <= REFRESH_THRESHOLD){
//If there are more items to fetch, and a network request isn't already underway
if(is_loading == false && has_remaining_items == true){
getItemsFromNetwork();
}
}