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.
Related
i am attempting to create this app which has a listView and when i click on an item in the listView it displays more information about the clicked item. I dont know how to fix this problem. i am getting the following from my log
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.velvetdev01.parselistclick.MainActivity$1.onItemClick(MainActivity.java:50)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
and here is my code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;
import java.util.List;
//import android.widget.ArrayAdapter;
public class MainActivity extends Activity {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
List<ParseObject> object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
mainAdapter = new ParseQueryAdapter<ParseObject>(this, "RestaurantDetail");
urgentTodosAdapter = new CustomAdapter(this);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
// Binds the Adapter to the ListView
listView.setAdapter(urgentTodosAdapter);
// Capture button clicks on ListView items
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(MainActivity.this, SingleItemView.class);
// Pass data "name" followed by the position
intent.putExtra("Name", object.get(i).getString("Name"));
// Open SingleItemView.java Activity
startActivity(intent);
}
});
}
}
and my custom adapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.ParseFile;
import com.parse.ParseImageView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
public class CustomAdapter extends ParseQueryAdapter<ParseObject> {
public CustomAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("RestaurantDetail");
/* query.whereEqualTo("Name", true);*/
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.activity_main, null);
}
super.getItemView(object, v, parent);
ParseImageView todoImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile imageFile = object.getParseFile("Logo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
TextView titleTextView = (TextView) v.findViewById(R.id.textView3);
titleTextView.setText(object.getString("Name"));
return v;
}
}
Here is the class i am trying to display the detailed information
#ParseClassName("RestaurantDetail")
public class SingleItemView extends Activity {
// Declare Variables
protected TextView txtname;
String Name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.single_item_view);
txtname = (TextView) findViewById(R.id.name);
// Retrieve data from MainActivity on item click event
Intent random1 = getIntent();
// Get the name
Name = random1.getStringExtra("Name");
// Locate the TextView in singleitemview.xml
txtname = (TextView) findViewById(R.id.name);
// Load the text into the TextView
txtname.setText(Name);
}
}
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 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 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've written a big code and I've used a list view within one of my task layouts :
I want to know how I can make a listener for each update button in this case in order to move to another activity , I know how to use more than one activity and moves between them But I want to know how to make a listener only .
The custom adapter code :
package com.example.task_9;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TempLyaout extends ArrayAdapter<String> {
Context context;
ArrayList<String> sa;
public TempLyaout(Context context , ArrayList<String> sa) {
super(context,R.layout.temp,sa);
this.context=context;
this.sa = sa;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater l = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView = l.inflate(R.layout.temp, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button update = (Button) rowView.findViewById(R.id.button1);
// myDb.open();
// Cursor cursor= myDb.getRowByName(sa.get(position));
// myDb.updateRowByName(cursor.getInt(DBAdapter.COL_ROWID), sa.get(position), cursor.getString(DBAdapter.COL_PASSWD), cursor.getInt(DBAdapter.COL_AGE), isAdmin);
// myDb.close();
textView.setText(sa.get(position));
return rowView;
}
}
This is the related class :
package com.example.task_9;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class UsersActivity extends Activity {
Intent redirect;
ListView list;
ArrayList<String> sa;
DBAdapter myDb;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.users);
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
openDB();
/*********************************************/
Cursor cursor = myDb.getAllRows();
cursor.moveToFirst();
ArrayList<String> ha = new ArrayList<String>();
while(cursor.moveToNext()) {
ha.add(cursor.getString(DBAdapter.COL_NAME));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ha);
list.setAdapter(new TempLyaout(UsersActivity.this,ha));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
} // end onStart method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
} // end openDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void closeDB() {
myDb.close();
} // end closeDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}// end main class
In your getView
Button update = (Button) rowView.findViewById(R.id.button1);
update.setOnClickListener(mClickListener);
Then
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ListActivtiy.this,SecondActivity.class);
startActivity(intent);
}
};
Also use a viewholder for smooth scrolling and performance
http://developer.android.com/training/improving-layouts/smooth-scrolling.html