What I've done so far is detecting mp3 files and display it with a checkbox in lisview, my problem is once i checked the item and scrolled down, the item that i checked before is lost.
This is my code:
this is the adapter
package com.example.cameraapp;
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.CheckBox;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<Model>{
Model[] modelItems = null;
Context context;
public CustomAdapter(Context context, Model[] resource) {
super(context,R.layout.songlayout,resource);
// TODO Auto-generated constructor stub
this.context = context;
this.modelItems = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(R.layout.songlayout, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.songsTexView);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
name.setText(modelItems[position].getName());
if(modelItems[position].getValue() == 1)
cb.setChecked(true);
else
cb.setChecked(false);
return convertView;
}
}
and this is the mainactivity
package com.example.cameraapp;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.widget.ListView;
public class FinalChoice extends Activity {
ListView lv;
int chuba=0;
Model[] modelItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview1hold);
lv = (ListView) findViewById(R.id.listView1);
String mp3Directory = "/Music";
String directoryPath= Environment.getExternalStorageDirectory().getAbsolutePath()+mp3Directory;
List<File> list = getMP3Files(directoryPath);
modelItems = new Model[list.size()];
//print in LogCat the list of .mp3:
for(int a=0;a<list.size();a++){
modelItems[a]=new Model( list.get(a).getName(), 0);
}
CustomAdapter adapter = new CustomAdapter(this, modelItems);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public List<File> getMP3Files(String directory) {
List<File> files = new ArrayList<File>();
File folder = new File(directory);
for (File file : folder.listFiles()) {
if (file.isFile()) {
if (file.getName().endsWith(".mp3") || file.getName().endsWith(".MP3")) {
files.add(file);
}
}
}
return files;
}
}
Keep track of all the checked items and using that set selection of check boxes in getView method. Whenever the selection is changes update your values which keep track of all the selections.
This might help you...
When scrolling custom ListView, the checkbox value changes
Related
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>
main xml containing horizontallistview
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
>
<com.example.newomolistview.HorizontalScrollView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ddd"
/>
</LinearLayout>
contain three textviews-for product name,original rate and offer rate
app_custom_list.xml
I think in this java class i have gone wrong
ApplicationAdapter.java
package com.example.newomolistview;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.newomolistview.R;
import com.example.newomolistview.HorizontalScrollView;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
// private BaseAdapter mAdapter = new BaseAdapter() {
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_custom_list, null); //new code
// LayoutInflater li = LayoutInflater.from(getContext()); //original
// v = li.inflate(R.layout.app_custom_list, null); //original
// LayoutInflater li = (LayoutInflater) this._context
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.textView1);
TextView originalRate = (TextView)v.findViewById(R.id.textView2);
TextView offerRate = (TextView)v.findViewById(R.id.textView3);
if(productName != null) productName.setText(app.getProductName());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app.getOfferRate());
}
return v;
// View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem, null);
// TextView title = (TextView) retval.findViewById(R.id.title);
// title.setText(dataObjects[position]);
//
// return retval;
}
// };
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
in this section also, i have gone wrong
MainActivity.java
package com.example.newomolistview;
import java.util.List;
import com.example.newomolistview.HorizontalScrollView;
import com.example.newomolistview.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview);
// listview.setAdapter(mAdapter);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String cityid="1";
String url = "http://www.gooffers.in/omowebservices/index.php/webservice/Public_User/homePagepoffers?";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,key,cityid);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview); //new code
// create new adapter
ApplicationAdapter mAdapter = new ApplicationAdapter(this, data);
listview.setAdapter(mAdapter); //new code
// set the adapter to list
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
You can learn it from these tutorials :-
Populating a ListView from JSON
Loading Text in listview from http json data
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 was just wondering if I was able to start a new activity with the click of an item inside a ListView.
The code I have written so far:
package awad865.project.ContactManager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.contactmanager1.R;
import android.widget.AdapterView;
public class MainActivity extends Activity {
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <Contact> displayList = new ArrayList<Contact>();
displayList.add(new Contact("Anmol","Wadhwa","53743632"));
displayList.add(new Contact("Juhi","Goswami","4234232"));
displayList.add(new Contact("Laurence","Baldwick","243232"));
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this,displayList);
listView.setAdapter(listAdapter);
}
private class CustomListAdapter extends ArrayAdapter<Contact>{
private Context _context;
private List<Contact> _contacts;
public CustomListAdapter(Context context, List<Contact> contacts){
super(context,android.R.layout.simple_list_item_1,contacts);
_context = context;
_contacts = contacts;
}
public View getView(int position, View convertView,ViewGroup parent){
//Create a layout inflater to inflate our xml layout for each item in the list
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the list item layout. Keep a reference to the inflated view.
//No root view specified
View listItemView = inflater.inflate(R.layout.custom_list_item_layout,null);
//Access TextView elements inside the view (note we must specify the parent view
//to look in)
TextView firstName = (TextView)listItemView.findViewById(R.id.list_item_firstname);
TextView lastName = (TextView)listItemView.findViewById(R.id.list_item_lastname);
TextView number = (TextView)listItemView.findViewById(R.id.list_item_number);
//Set the text for each textview (use the position arugment to find the appropriate element in the list)
firstName.setText(_contacts.get(position).getFirstName());
lastName.setText(_contacts.get(position).getLastName());
number.setText(_contacts.get(position).getNumber());
return listItemView;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_groups:
Intent groupIntent = new Intent(this,Groups.class);
startActivity(groupIntent);
return true;
case R.id.action_favourites:
Intent favouriteIntent = new Intent(this,Favourites.class);
startActivity(favouriteIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
}
class listItemClickedListener implements AdapterView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parentView, View clickedView, int clickedViewPosition, long id) {
// TODO Auto-generated method stub
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
}
}
I was just wondering if I was able to start a new activity inside the method onItemClick() in the class listItemClickListener. Any help would be appreciated because the compiler doesn't allow me to start a new intent.
You can retrieve the Context you need from clickedView.
Intent contactInfoIntent = new Intent(clickedView.getContext(), ContactInformation.class);
clickedView.getContext().startActivity(contactInfoIntent);
start Activity on ListView item Click as:
STEP 1:
Add on OnItemClickListener by passing instace of listItemClickedListener class as:
....
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new listItemClickedListener());
STEP 2:
start Activity from onItemClick as:
Intent contactInfoIntent = new Intent(clickedView.getContext(),
ContactInformation.class);
clickedView.getContext().startActivity(contactInfoIntent);
you need to bind the click event to each item added to the listView
You could put the Data, in your case ContactDate, as a ContactData element onto your View (each cell) by calling convertView.setTag(contactData) in your getView() Method.
onItemClick wpuld then do something like this:
ContactData cd = (ContactData)clickedView.getTag();
Bundle b = new Bundle();
// put data from cd in that Bundle
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
startActivity(contactInfoIntent);
update:
try this:
package awad865.project.ContactManager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.contactmanager1.R;
import android.widget.AdapterView;
public class MainActivity extends Activity implements OnItemClickListener{
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <Contact> displayList = new ArrayList<Contact>();
displayList.add(new Contact("Anmol","Wadhwa","53743632"));
displayList.add(new Contact("Juhi","Goswami","4234232"));
displayList.add(new Contact("Laurence","Baldwick","243232"));
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this,displayList);
listView.setAdapter(listAdapter);
}
private class CustomListAdapter extends ArrayAdapter<Contact>{
private Context _context;
private List<Contact> _contacts;
public CustomListAdapter(Context context, List<Contact> contacts){
super(context,android.R.layout.simple_list_item_1,contacts);
_context = context;
_contacts = contacts;
}
public View getView(int position, View convertView,ViewGroup parent){
//Create a layout inflater to inflate our xml layout for each item in the list
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the list item layout. Keep a reference to the inflated view.
//No root view specified
if (convertView == null)
View convertView = inflater.inflate(R.layout.custom_list_item_layout,null);
//Access TextView elements inside the view (note we must specify the parent view
//to look in)
TextView firstName = (TextView)convertView.findViewById(R.id.list_item_firstname);
TextView lastName = (TextView)convertView.findViewById(R.id.list_item_lastname);
TextView number = (TextView)convertView.findViewById(R.id.list_item_number);
//Set the text for each textview (use the position arugment to find the appropriate element in the list)
firstName.setText(_contacts.get(position).getFirstName());
lastName.setText(_contacts.get(position).getLastName());
number.setText(_contacts.get(position).getNumber());
//TODO add your data to the View
convertView.setTag(yourData)
return convertView;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_groups:
Intent groupIntent = new Intent(this,Groups.class);
startActivity(groupIntent);
return true;
case R.id.action_favourites:
Intent favouriteIntent = new Intent(this,Favourites.class);
startActivity(favouriteIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
Override
public void onItemClick(AdapterView<?> parentView, View clickedView, int clickedViewPosition, long id) {
ContactData cd = (ContactData)clickedView.getTag();
Bundle b = new Bundle();
// TODO put data from cd in that Bundle
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
startActivity(contactInfoIntent);
}
}
besides, you usually do iOS development or am i wrong?
First argument of an Intent constructor requires an object of Context class. But you supplied an listItemClickedListener.class.
Intent constructor requeres:
Intent(Context, Class<?>)
you supplied:
Intent(listItemClickedListener, Class<?>)
I have defined onCheckedChanged for the checkbox in my listview.
When i click on the check box to check / uncheck it this function is getting invoked.
But when i setthe state of the check box from code like
check.setChecked(true);
the onCheckedChanged is not getting invoked.
Please help.
Adapter file :
package com.idg.project.adapters;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.idg.project.R;
import com.idg.project.activities.ScanListActivity;
import com.idg.project.activities.SearchResultActivity;
import com.idg.project.adapters.WishListAdapter.ViewHolder;
import com.idg.project.entity.ScannedProduct;
public class ScanListAdapter extends BaseAdapter {
private Context context;
private List<ScannedProduct> productList;
protected LayoutInflater mInflater;
Button showOrHideButton;
static public int count = 0;
String barcodeForSelectedRow;
String formatForSelectedRow;
OnItemClickListener rowListener;
Activity parentActivity;
boolean isWishList;
public ScanListAdapter(Context context, List<ScannedProduct> objects,
Button button, Activity parentActivity) {
super();
this.productList = objects;
this.context = context;
this.mInflater = LayoutInflater.from(context);
showOrHideButton = button;
this.parentActivity = parentActivity;
this.isWishList = isWishList;
}
public int getCount() {
return productList.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
Log.i("checkboxflag at : ", pos+"is"+(productList.get(pos).getCheckboxflag()));
Log.i("getview : fresh", "getview"+pos);
convertView = mInflater.inflate(R.layout.product_list_row, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.productid);
holder.text1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(parentActivity,
SearchResultActivity.class);
intent.putExtra("barcode", productList.get(pos)
.getBarcode());
intent.putExtra("format", productList.get(pos).getFormat());
intent.putExtra("IsScan", false);
Log.i("", "" + productList.get(pos).getBarcode());
parentActivity.startActivity(intent);
Log.i("", "" + pos);
}
});
holder.text2 = (TextView) convertView.findViewById(R.id.price);
// holder.text2.setOnClickListener(listener);
holder.image = (ImageView) convertView
.findViewById(R.id.productimageid);
convertView.setTag(holder);
// holder.image.setOnClickListener(listener);
holder.text1.setText(productList.get(position).getTitle());
holder.text2.setText(productList.get(position).getPrice().toString());
if (productList.get(position).getSmallImage() != null) {
byte[] bb = (productList.get(position).getSmallImage());
holder.image.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0,
bb.length));
} else {
holder.image.setImageBitmap(null);
holder.image.setBackgroundResource(R.drawable.highlight_disabled);
}
// holder.image.setImageBitmap(Utils.loadBitmap(productList.get(position).getSmallImage()));
final CheckBox check = (CheckBox) convertView
.findViewById(R.id.checkbox);
check.setClickable(true); // to remove anything carried over from prev convert view
if(productList.get(pos).getCheckboxflag()==1)
{
Log.i("CheckBox set checked",""+pos);
check.setChecked(true);
}
else{
Log.i("CheckBox set unchecked",""+pos);
check.setChecked(false);
}
setWishListItemsInScanList(pos, convertView);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i("OnclickListener","Current Position"+pos);
if (check.isChecked()
&& productList.get(pos).getWishListFlag() == 0) {
if(check.isClickable()){
Log.i("CheckBox check",""+pos);
ScanListActivity.updateCheckBoxSelection(1, pos);
ScanListAdapter.count++;
}
} else if (!check.isChecked()
&& productList.get(pos).getWishListFlag() == 0){
if(check.isClickable()){
ScanListActivity.updateCheckBoxSelection(0, pos);
ScanListAdapter.count--;
Log.i("CheckBox UNcheck",""+pos);
}
}
if (ScanListAdapter.count == 0) {
// showOrHideButton.setClickable(false);
// showOrHideButton.setVisibility(View.GONE);
showOrHideButton.setEnabled(false);
} else {
// showOrHideButton.setVisibility(View.VISIBLE);
showOrHideButton.setEnabled(true);
}
}
});
return convertView;
}
private void setWishListItemsInScanList(int pos, View convertView) {
if (productList.get(pos).getWishListFlag() == 1) {
Log.i("CheckBox set checked from wish list",""+pos);
CheckBox check = (CheckBox) convertView.findViewById(R.id.checkbox);
check.setClickable(false);
check.setChecked(true);
}
}
static class ViewHolder {
TextView text1;
ImageView image;
TextView text2;
}
}
List activity file :
package com.idg.project.activities;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.idg.project.R;
import com.idg.project.adapters.WishListAdapter;
import com.idg.project.adapters.ScanListAdapter;
import com.idg.project.entity.ScannedProduct;
import com.idg.project.services.ScannedProductDataAccessManager;
public class ScanListActivity extends BaseActivity {
static Button scanlist;
ScanListAdapter listAdapter;
static List<ScannedProduct> productList;
/* Notes for the Developer :
* For tracking the checked items Checkboxflag
* is maintained.
* Point1 : Select all will just set this flag in the local list and then call notifyDatachange of the adapter
* within adapter the check box is set or reset based on this flag for each row
*
* Point 2: When individual rows are selected , there is an onclick of the check box is invoked
* Here the Checkboxflag of the local list is set /unset . Also we need a way to knpw the select all button is
* to enabled or diabled. for that Count variable is updated here.
* Now Important point is these two actions shoulnt be taking place if the checkbox state change due to select all
* So there is a special check of isclickable in the onclicklistener
*
* Point 3: In scan list the items in the wish list are to be marked. This again needs special logic.
* This is done in the adapter code by checking all the rows whose wishListFlag is 1 and making it non clickable
*
* Important : Listview has the concept of ViewGroup and each view group is usually the rows fitting in the display screen
* so when we scroll, the viewGropu changes.
* Convertview is get reused for view groups. So need to careful undesired values that will be carried to next viewgroup*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.scan_list);
productList = new ArrayList<ScannedProduct>();
productList = getProductList();
for(int i=0;i<productList.size();i++){
Log.i("checkboxflag at : ", i+"is"+(productList.get(i).getCheckboxflag()));
}
final ListView lv = (ListView) findViewById(R.id.list);
scanlist = (Button) findViewById(R.id.addtowishlist);
scanlist.setEnabled(false);
listAdapter = new ScanListAdapter(this, productList, scanlist, this);
lv.setAdapter(listAdapter);
}
private List<ScannedProduct> getProductList() {
List<ScannedProduct> productList = new ArrayList<ScannedProduct>();
ScannedProductDataAccessManager productDataBaseManager = new ScannedProductDataAccessManager(
getApplicationContext());
String[] colList = { "title", "smallImage", "price" };
productList = productDataBaseManager.fetchAllProducts();
return productList;
}
static boolean selectFlag = false;
public void selectAll(View view) {
ListView listView = (ListView) findViewById(R.id.list);
view = findViewById(R.id.select_all);
if (selectFlag == false) {
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
productList.get(i).setCheckboxflag(1);
}
view.setBackgroundResource(R.drawable.login_remme_dwn_btn);
selectFlag = true;
TextView text=(TextView) findViewById(R.id.select);
text.setText("Unselect All");
scanlist.setEnabled(true);
} else {
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
productList.get(i).setCheckboxflag(0);
}
view.setBackgroundResource(R.drawable.login_remme_up_btn);
selectFlag = false;
TextView text=(TextView) findViewById(R.id.select);
text.setText("Select All");
scanlist.setEnabled(false);
}
((BaseAdapter)listView.getAdapter()).notifyDataSetChanged(); // we are only setting the flags in the list
// so need to notify adapter to reflect same on checkbox state
//listView.refreshDrawableState();
}
public void addToWishList(View view) {
ListView listView = (ListView) findViewById(R.id.list);
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
ScannedProduct product = productList.get(i);
if (product.getWishListFlag() == 0 && product.getCheckboxflag()==1) {
product.setWishListFlag(1);
new ScannedProductDataAccessManager(getApplicationContext())
.updateProduct(product, "title",
new String[] { product.getTitle() });
product.setCheckboxflag(0);
//ScanListAdapter.count--;
}
Log.i("ScanList selected", product.getTitle());
}
Toast.makeText(getApplicationContext(),
"Added selected items to Wish List", Toast.LENGTH_SHORT).show();
scanlist.setEnabled(false);
((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
}
static public void updateCheckBoxSelection(int flag,int pos){ // when individual row check box is checked/ unchecked
// this fn is called from adapter to update the list
productList.get(pos).setCheckboxflag(flag);
}
}
Since your checkbox is inside listview, so you need to call notifyDataSetChanged method on your list's adapter to refresh it's contents.
update
instead of ((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();, try calling listAdapter.notifyDataSetChanged();
I got the answer / bug in my code
i am not reusing convertview so its every time a new holder.
I am changing the flag of the checkbox and then assigning a statechange listener for the checkbox
thus its not getting invoked
when i changed the order to assign checkchangelistener before actually changing the state , its working as expected. The listener is getting called.
thanks all of you