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
Related
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/
New android programmer is here.
First : I dont know many things about list view and as I found out , its complicated to work with it.
So , I want to put my database data (Contains Id , Name) to a listview and get the Id of the item is clicked.
I have searched many but i just found this :
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class test extends Activity {
String[] wordlist = new String[] { "a", "b", "c" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wordlist[2] = "abds";
ListView list = new ListView(this);
list.setAdapter((ListAdapter) new MyAdapter(test.this, wordlist));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Object entry= parent.getItemAtPosition(position);
Toast.makeText(test.this, entry.toString(), Toast.LENGTH_SHORT).show();
}
});
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(test.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
TextView listText = new TextView(test.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
}
Just i can show strings , not Id.
Use SimpleCursorAdapter to populate ListView with data from database, for example - https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/ (first link from google).
How to get the item id in an onItemClick handler
Read more about ListView and Adapters, your code is awful )
I have a problem my custom List view.I have data in hash map and add into array list which is shown in below code.what is my problem is in my hash map contain 20 values and i try set into the list view but first data only display other or not.Thanks advance
This is my CustomAdapter
package com.example.node10.databasetesting;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.example.node10.databasetesting.DataBase.*;
public class ListViewEmployee extends AppCompatActivity implements View.OnClickListener {
private SimpleCursorAdapter dataAdapter;
private Button btn_view;
private Button btn_submit;
ArrayList<HashMap<Integer,String>> emp;
HashMap<Integer,String> map;
Set<Integer> keyValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_employee);
DataBase dataBase=new DataBase(this);
map=new HashMap<>();
map=dataBase.getValueEmpTable();
emp=new ArrayList<HashMap<Integer, String>>();
keyValue=map.keySet();
emp.add(map);
btn_view= (Button) findViewById(R.id.id_btn_emp_view);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.id_btn_emp_view){
displayList();
// selectItem();
}
}
private void displayList() {
//create the Arrayt adapter
ListView listview= (ListView) findViewById(R.id.id_listview);
final MyAdapter adapter=new MyAdapter(this,R.layout.custom_listview,emp);
listview.setAdapter(adapter);
}
public class MyAdapter extends ArrayAdapter<HashMap<Integer,String>>{
boolean[] checkBoxState;
ViewHolder viewholder;
public MyAdapter(Context context, int resource,ArrayList<HashMap<Integer,String>> map) {
super(context, resource, map);
// create the boolean array for check box selection
checkBoxState= new boolean[map.size()];
}
// create the class for caching the view
class ViewHolder{
TextView txtView;
CheckBox checkBox;
}
#Override
public View getView( final int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater objlayout= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=objlayout.inflate(R.layout.custom_listview,null);
viewholder=new ViewHolder();
viewholder.txtView= (TextView) convertView.findViewById(R.id.id_checkbox_textview);
viewholder.checkBox= (CheckBox) convertView.findViewById(R.id.id_checkbox);
convertView.setTag(viewholder);
}else{
viewholder = (ViewHolder) convertView.getTag();}
// viewholder.txtView.setText(emp.get(position).toString());
viewholder.txtView.setText(emp.get(position).get(position+1).toString());
viewholder.checkBox.setChecked(checkBoxState[position]);
viewholder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return convertView;
}
}
}
Now you put to your adapter ArrayList of HashMap. I don't know why are you doing that, but now your ArrayList emp contains ony one element - that was added in line
emp.add(map);
So, ArrayAdapter for array with size = 1 will show 1 elemet.
If you want to show in list all elements from your map. I suggest to use
ArrayList emp and comvert map to list by using map.values()
ArrayList<String> emp = (ArrayList<String>)map.values();
Then change your adapter to
public class MyAdapter extends ArrayAdapter<String>
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.
I have a problem by selecting CheckBoxes in my ListItems. Each ListItem has a CheckBox in it's layout and when the ListItem is clicked the CheckBox should be activated. The problem is that the CheckBoxes are randomly activated. For example: When i have 2 ListItems and click on ListItem1, it's CheckBox is activated. When i click again, CheckBox of ListItem2 is activated, too. When i click again, CheckBox of ListItem1 is deactivated. When i click again, CheckBox of ListItem2 is deactivated. When i click again it all starts from the beginning. I understand ListView reuses the Items and that i have to use getView() method, but i just can't make it work. I have to mention that I'm a bloody beginner, so please forgive me if some code doesn't make sense at all.
You need to create a Custom Array Adapter and all set.
Here is the Activity Class I created for ListView for ChekBoxList
ActivityGamesList.java
package com.rdc.gameListApp;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
public class ActivityGamesList extends Activity {
private ListView listGames = null;
private DBAdapter database = null;
private Context context = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_of_games);
final CheckBox favBox = (CheckBox) findViewById(R.id.favbuttonInList);
listGames = (ListView) findViewById(R.id.listViewGame);
context = getApplicationContext();
database = new DBAdapter(context);
//here I am getting the data from database and putting in to List
List<String> gamelistArrayR = database.selectAllName();
// custom adapter for adding fav box
//make sure here "gamelistArrayR" is List and type is String
listGames.setAdapter(new CustomAdapter(this, gamelistArrayR));
//listener for list view
listGames.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected: " +
position+" no row", Toast.LENGTH_SHORT).show();
}
});
}
}
and below is the Custom Array Adapter
CustomAdapter.java
package com.rdc.gameListApp;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final List<String> values;
public CustomAdapter(Context context, List<String> gamelistArrayR) {
super(context, R.layout.list_row_custom, gamelistArrayR);
this.context = context;
this.values = gamelistArrayR;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_row_custom, parent, false);
//Game Name Text in list
TextView textView = (TextView) rowView.findViewById(R.id.txtGameNameInList);
// Check Box in list
CheckBox favBox = (CheckBox) rowView.findViewById(R.id.favbuttonInList);
textView.setText(values.get(position));
//listener for check box
favBox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Boolean flag = isChecked;
if(flag){
Log.v("Debug", "step no 1");
Toast.makeText(context, "Marked as Favorite Game!", 1).show();
}
}
});
return rowView;
}
}
and i got the output like this way..
Edit:
When you scroll list, the chekboxrs gets uncheked because or recreate view.
so you need to store the state of checkbox for that you should check below links
this So thread or
this tutorial
Try using setOnItemSelectedListener instead of setOnItemClickListener . I believe the click event is getting invoked more often that you need.
You need to store the item states in your Adapter, not in the View itself, because it could be a reused one, just like you say. Your call to super.getView() will fill in the correct text for you, but not change the checkbox state. Keep a bool array reflecting the state of each checkbox, and in getView() apply the state before returning your view:
CheckBox cb = (CheckBox) view.findViewById(R.id.cb);
cb.setChecked(cbStates[position]);