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/
Related
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)
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
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 need help on how I list my data in the ListView alphabetical. If I add more data to foldeData it would be nice if I didn't have to manually move the existing data in order to list them alphabetical.
I have copied part of the code from MainActivity:
import java.util.concurrent.TimeUnit;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.ads.*;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener {
TextView minPastaTimer, maxPastaTimer, tv_start, tv_stop, choice;
int minTid, maxTid;
private ListView listViewArticles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Folder[] folderData = new Folder[4];
folderData[0] = new Folder(R.drawable.icon_music_folder, "Acomo Pepe", (getString(R.string.acomo_pepe)), "Kogetid 9-10min");
folderData[1] = new Folder(R.drawable.icon_music_folder, "Bucatini", (getString(R.string.Bucatini)),"Kogetid 9-10min");
folderData[2] = new Folder(R.drawable.icon_music_folder, "Bumbola", (getString(R.string.Bumbola)),"Kogetid 9-10min");
folderData[3] = new Folder(R.drawable.icon_music_folder, "Cannelloni", (getString(R.string.Cannelloni)),"Kogetid 9-10min");
FolderAdapter adapter = new FolderAdapter(this,
R.layout.listview_item_row, folderData);
listViewArticles = (ListView) findViewById(R.id.listView1);
listViewArticles.setAdapter(adapter);
minPastaTimer = (TextView) findViewById(R.id.minPastaTimer);
minPastaTimer.setText("00:00:00");
maxPastaTimer = (TextView) findViewById(R.id.maxPastaTimer);
choice = (TextView) findViewById(R.id.tv_choice);
maxPastaTimer.setText("00:00:00");
Button btn_italy = (Button) findViewById(R.id.btn_italy);
Button btn_danish = (Button) findViewById(R.id.btn_danish);
tv_start = (TextView) findViewById(R.id.tv_start);
tv_start.setOnClickListener(this);
tv_stop = (TextView) findViewById(R.id.tv_stop);
tv_stop.setOnClickListener(this);
listViewArticles.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String listItemText = ((TextView) view
.findViewById(R.id.textViewFolderName))
.getText()
.toString();
Toast.makeText(MainActivity.this,
"You clicked: " + listItemText, Toast.LENGTH_LONG)
.show();
if (listItemText.equals("Acomo Pepe")){
minTid=10000;
maxTid=20000;
choice.setText("Acomo Pepe: " + (getString(R.string.acomo_pepe)));
minPastaTimer.setText("00:08:00");
maxPastaTimer.setText("00:09:00");
}
else if (listItemText.equals("Bucatini")){
minTid=540000;
maxTid=600000;
choice.setText("Bucatini - Kogetid: " + (minTid/60/1000) + ("-") +(maxTid/60/1000) + ("min"));
minPastaTimer.setText("00:09:00");
maxPastaTimer.setText("00:10:00");
}
else if (listItemText.equals("Bumbola")){
minTid=15000;
maxTid=30000;
minPastaTimer.setText("00:10:00");
maxPastaTimer.setText("00:11:00");
}
else if (listItemText.equals("Cannelloni")){
minTid=15000;
maxTid=30000;
minPastaTimer.setText("00:11:00");
maxPastaTimer.setText("00:12:00");
}
}
});
FolderAdapter:
import android.app.Activity;
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;
public class FolderAdapter extends ArrayAdapter<Folder> {
Context mContext;
int layoutResourceId;
Folder data[] = null;
// #mContext - app context
// #layoutResourceId - the listview_item_row.xml
// #data - the ListItem data
public FolderAdapter(Context mContext, int layoutResourceId, Folder[] data) {
super(mContext, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.data = data;
}
// #We'll overried the getView method which is called for every ListItem we have.
// #There are lots of different caching techniques for Android ListView to
// achieve better performace especially if you are going to have a very long ListView.
// #convertView - the cache of list item row layout, if it is null, inflate new
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
// inflate the listview_item_row.xml parent
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
}
// get the elements in the layout
ImageView imageViewFolderIcon = (ImageView) convertView.findViewById(R.id.imageViewFolderIcon);
TextView textViewFolderName = (TextView) convertView.findViewById(R.id.textViewFolderName);
TextView textViewFolderDescription = (TextView) convertView.findViewById(R.id.textViewFolderDescription);
TextView textViewFolderBoilTime = (TextView) convertView.findViewById(R.id.textViewFolderBoilTime);
// Set the data for the list item. You can also set tags here if you want.
Folder folder = data[position];
imageViewFolderIcon.setImageResource(folder.folderIcon);
textViewFolderName.setText(folder.folderName);
textViewFolderDescription.setText(folder.folderDescription);
textViewFolderBoilTime.setText(folder.folderBoilTime);
return convertView;
}
}
I think best practice would be sorting the list before the calling adaptor.notifyDataChanged() method. Good thing is you do not have to do it manually, just use comparator for sorting.
You can see a comparator example in this link
Instead of using an array as datasource for the list, first use a List. At least, this class extends Collection.
You can define a comparator (e.g define compareTo() on your custom type) and sort your collection before you show it:
Collections.sort(<your_list>);
EDIT: For general collection ordering, see Guava
I have the below ListView and would like to display only the item clicked in another activity.
package com.sclick.govlistview;
import android.content.Intent;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MyActivity extends ActionBarActivity {
private List<Madaxda> madaxdu = new ArrayList<Madaxda>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
MadaxList();
MadaxListView();
RegisterCallBack();
}
private void MadaxList() {
madaxdu.add(new Madaxda("Hassan Sheik","Madaxweyne","MSC", 2, R.drawable.hassan));
madaxdu.add(new Madaxda("Awali Sheik","Raysal wasaare","Doctor", 2, R.drawable.awali));
madaxdu.add(new Madaxda("Abdullahi Godah Barre","Ministry of Interior and Federalism","Degree", 2, R.drawable.mi));
madaxdu.add(new Madaxda("Abdirahman Duale Beyle","Ministry of Foreign Affairs","PHd", 2, R.drawable.ma));
madaxdu.add(new Madaxda("Mohamed Sheikh Hassan","Ministry of Defence","Degree", 2, R.drawable.eel));
}
private void MadaxListView() {
ArrayAdapter<Madaxda> adapter = new MyListAdapters();
ListView list = (ListView) findViewById(R.id.madaxdaListView);
list.setAdapter(adapter);
}
private void RegisterCallBack() {
ListView list = (ListView)findViewById(R.id.madaxdaListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
Madaxda m = madaxdu.get(position);
Intent intent = new Intent(MyActivity.this, Profile.class);
intent.putExtra("position", position);
startActivity(intent);
//String message = "You have clicked Mudanaha " + position +
// "oo magaciisu yahay " + m.getName() + "oo shaqadiisu tahay "
// + m.getBooska();
// Toast.makeText(MyActivity.this,message,Toast.LENGTH_SHORT).show();
}
});
}
private class MyListAdapters extends ArrayAdapter<Madaxda> {
MyListAdapters() {
super(MyActivity.this, R.layout.lists, madaxdu);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.lists, parent, false);
}
Madaxda m = madaxdu.get(position);
ImageView img = (ImageView) itemView.findViewById(R.id.item_icon);
img.setImageResource(m.getID());
TextView magaca = (TextView) itemView.findViewById(R.id.magaca_qofka);
magaca.setText(m.getName());
TextView shaqo = (TextView) itemView.findViewById(R.id.shaqada_qofka);
shaqo.setText(m.getBooska());
TextView sano = (TextView) itemView.findViewById(R.id.inta_sano);
sano.setText("" + m.getYearsInService());
TextView edu = (TextView) itemView.findViewById(R.id.education);
edu.setText(m.getEducation());
return itemView;
}
}
}
Here my receiving Activity
package com.sclick.govlistview;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by MacRail on 12/09/2014.
*/
public class Profile extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
String position = getIntent().getStringExtra("position");
}
public View getView(final int POSITION, View convertView,ViewGroup parent){
ImageView img;
TextView name;
TextView booskas;
TextView education;
TextView yearsInService;
View view = convertView;
Log.d("SCLICK","Here is ok");
if(view == null){
LayoutInflater la = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = la.inflate(R.layout.profile,null);
}
img = (ImageView) findViewById(R.id.imageView1);
name = (TextView)findViewById(R.id.magaca_qofkas);
booskas = (TextView)findViewById(R.id.shaqada_qofkas);
education = (TextView)findViewById(R.id.educationka);
yearsInService = (TextView)findViewById(R.id.inta_sanood);
img.setImageBitmap(BitmapFactory.decodeByteArray(img.get(POSITION),0,img.get(POSITION).length));
name.setText(name.get(POSITION));
booskas.setText(booskas.get(POSITION));
education.setText(education.get(POSITION));
yearsInService.setText(yearsInService.get(POSITION));
return view;
}
}
It seems that you are bundling an int, but unbundling a string.
Try this line:
int position = getIntent().getInt("position");
If I was you I would try to see what type of data I receive. Theoretically you should get an int but the safe way is to get the Bundle that is inside by calling getIntent().getExtras() and then next you try to see if by calling getInt("position") or get("position") you receive what you want.
If the Bundle is null then it is clear you have nothing.