I have a listView and icon button in my Activity. When icon is clicked, it should go to Activity B and finally return Activity B value to A by adding a new list. But the problem now is I only can create one list. When it has another value return to A, it update the old list instead of add a new list.
I get the tutorial from here, the difference is I use startActivityForResult to return value from Activity B to A.
Please help me..I've been stuck at here for the whole day...
Activity A
int mClickedPosition; // add list
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDetails:
View menuItemView = findViewById(R.id.addDetails);
PopupMenu po = new PopupMenu(this, menuItemView); //for drop-down menu
po.getMenuInflater().inflate(R.menu.popup_details, po.getMenu());
po.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplication(), "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
if ("Add Work Details".equals(item.getTitle())) {
mClickedPosition = -1;
Intent intent = new Intent(getApplication(), Add_Details_Information.class); // go to Details class
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
return true;
}
});
po.show(); //showing popup menu
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Add_Details_Information
if(requestCode==PROJECT_REQUEST_CODE)
{
ReceiveProject = data.getStringExtra("Project");
ReceiveDescription = data.getStringExtra("Description");
ReceiveProgress = data.getIntExtra("progress",0);
ReceiveTimeIn = data.getStringExtra("TimeIn");
ReceiveTimeOut = data.getStringExtra("TimeOut");
ArrayList<SearchResults> searchResults = GetSearchResults(ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
(new MyCustomBaseAdapter(this,searchResults)).notifyDataSetChanged();
listview.setAdapter(new MyCustomBaseAdapter(this,searchResults));
}
else if(requestCode==CAMERA_REQUEST_CODE)
{
}
}
private ArrayList<SearchResults> GetSearchResults(String p, String d,int pro, String i, String o) {
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1=new SearchResults();
sr1.setProject(" Project/Service/Training : " + p);
sr1.setDescription(" Description : " + d);
sr1.setProgress(" Progress : " + pro);
sr1.setTimeIn(" Time In : " + i);
sr1.setTimeOut(" Time Out : " + o);
if(mClickedPosition==-1)
{
results.add(sr1);
}
return results;
}
MyCustomBaseAdapter
public class MyCustomBaseAdapter extends BaseAdapter{ // for ListView in WorkDetailsTable
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtProject= (TextView) convertView.findViewById(R.id.ListProject);
holder.txtDescription = (TextView) convertView.findViewById(R.id.ListDescription);
holder.txtProgress = (TextView) convertView.findViewById(R.id.ListProgress);
holder.txtIn=(TextView)convertView.findViewById(R.id.ListTimeIn);
holder.txtOut=(TextView)convertView.findViewById(R.id.ListTimeOut);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtProject.setText(searchArrayList.get(position).getProject());
holder.txtDescription.setText(searchArrayList.get(position).getDescription());
holder.txtProgress.setText(searchArrayList.get(position).getProgress());
holder.txtIn.setText(searchArrayList.get(position).getTimeIn());
holder.txtOut.setText(searchArrayList.get(position).getTimeOut());
return convertView;
}
static class ViewHolder {
TextView txtProject;
TextView txtDescription;
TextView txtProgress;
TextView txtIn;
TextView txtOut;
}
}
Currently instead of adding new item in ListView, passing new object of Adapter to setAdapter which will show only latest added item in ListView instead of add in current Adapter.
Do it as:
1. Create a method in MyCustomBaseAdapter class for adding new item in data-source which size is returned from getCount method:
public void addNewItem(String ReceiveProject,String ReceiveDescription,...){
// add ReceiveProject,ReceiveDescription
// in ArrayList which using in Adapter
SearchResults objSearchResults=new SearchResults();
objSearchResults.setProject(ReceiveProject);
....
searchArrayList.add(objSearchResults);
this. notifyDataSetChanged();
}
2. Use same object of MyCustomBaseAdapter class which passed first time in setAdapter method to call addNewItem method:
if(requestCode==PROJECT_REQUEST_CODE)
{
MyCustomBaseAdapter objMyCustomBaseAdapter=
(MyCustomBaseAdapter)listview.getAdapter();
}
Related
I've got the following Problem.
I have a ListView which displays me Articles with different Categories.
When I select a Category from my Dialog Window and press the PositiveButton "OK", I want to update my ListView, that it now lists only the Articles from the Category, selected in the Dialog Window.
I created an interface in the DialogFragment, which is a callback to get value from the Dialog.
This is the Class:
public class SelectFilterDialog extends DialogFragment implements DialogInterface.OnClickListener{
private static int mSelectedIndex;
private static String mSelectedCategory;
private String[] categories = {"All", "Announcements","Commerce","Development", "Distributions", "Front","Kernel","Legal", "Letters", "Press", "Security"};
static OnDialogSelectListener mDialogSelectorCallback;
//callback method to get values from a Dialog
public interface OnDialogSelectListener{
public void onSelectedOption();
}
public static SelectFilterDialog newInstance(int selected) {
final SelectFilterDialog dialog = new SelectFilterDialog();
mSelectedIndex = selected;
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Filter");
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Cancel", this);
builder.setSingleChoiceItems(categories, mSelectedIndex, this);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case Dialog.BUTTON_POSITIVE:{
dialog.dismiss();
mDialogSelectorCallback.onSelectedOption();
}break;
case Dialog.BUTTON_NEGATIVE:{
dialog.cancel();
}break;
default:
mSelectedIndex = which;
setSelectedCategory(categories[which]);
break;
}
}
public void setDialogSelectListener(OnDialogSelectListener listener){
this.mDialogSelectorCallback = listener;
}
public void setSelectedCategory(String category){
this.mSelectedCategory = category;
}
public static String getSelectedCategory(){
return mSelectedCategory;
}
public static int getSelectedIndex(){
return mSelectedIndex;
}
}
In my SearchFragment Class , i show the List and implement the Interface from the SelectFilterDialog Fragment.
In the Method, i update the selectedCategory, after pressing the OK button, and then update the adapter with notifyDataSetChanged()
SearchFragment:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_bar_filter: {
showDialog();
}
}
return super.onOptionsItemSelected(item);
}
void showDialog() {
SelectFilterDialog dialog = SelectFilterDialog.newInstance(preSelectedValue);
dialog.setDialogSelectListener(this);
dialog.show(getActivity().getFragmentManager(), "dialog");
}
#Override
public void onSelectedOption() {
selectedCategory = dialog.getSelectedCategory();
preSelectedValue = dialog.getSelectedIndex();
Log.i(TAG, "selectedCategory : " +selectedCategory);
article_list_adapter.updateCategory(selectedCategory);
}
In my Adapter, i receive the Category in my updateCategory and fill the currentArticle List with the Articles with the correct Category.
This works fine.
After that i call NotifyDataSetChanged to update the view.
public void updateCategory(String category) {
this.currentArticles.clear();
this.selectedCategory = category;
for (Article article : entireArticles) {
if (category.equals(article.getCategory())) {
currentArticles.add(article);
}
}
notifyDataSetChanged();
}
notifyDataSetChanged();
}
But in the getView it throws an IndexOutOfBounce exception.
After selecting a Category from the dialog, e.g "Kernel", it adds only my 3 Kernel Categories to the currentArticle List, which is fine.
But int the getView statement:
Article currentArticle = currentArticles.get(_position);
It points on index 3 , though there are only 3 elements in the list.
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at klinar.kronlachner.binder.app.Article_List_Adapter.getView(Article_List_Adapter.java:99)
Can you help me ? :)
public Article_List_Adapter(Context _c, int textViewResourceId, List<Article> articles) {
super(_c, textViewResourceId, articles);
this.entireArticles = new ArrayList<Article>();
this.currentArticles = new ArrayList<Article>();
entireArticles.addAll(articles);
currentArticles.addAll(articles);
this.storedArticles = new ArrayList<Article>(articles);
}
public View getView(int _position, View _convertView, ViewGroup _parent) {
View view = _convertView;
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.article_list_row, null);
viewHolder = new ViewHolder();
viewHolder.article_icon = (ImageView) view.findViewById(R.id.article_category_icon);
viewHolder.articleTitle = (TextView) view.findViewById(R.id.article_title);
viewHolder.articleCategory = (TextView) view.findViewById(R.id.article_category);
viewHolder.articleDate = (TextView) view.findViewById(R.id.article_date);
viewHolder.articleAuthor = (TextView) view.findViewById(R.id.article_author);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _convertView.getTag();
}
//Find the article to work with
Article currentArticle = currentArticles.get(_position);
//fill the Article_View
switch (currentArticle.getCategory()) {
case "Kernel": {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_k);
}
break;
case "Security": {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
break;
default: {
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
}
viewHolder.articleTitle.setText(currentArticle.getTitle());
viewHolder.articleCategory.setText(currentArticle.getCategory());
viewHolder.articleDate.setText(currentArticle.getDate());
viewHolder.articleAuthor.setText(currentArticle.getAuthor());
return view;
Do this in your adapter class
create two List one for AllCategoryArticle and another for currentCategoryArticle.
class ArticleAdapter{
ArrayList<Model> currentArticle;
ArrayList<Model> entireArticle;
String selectedCategory="all"; //setting default category as "all"
public ArticleAdapter(ArrayList<Model> categoryList){
this.entireList=categoryList;
this.currentList=this.entireList;
}
//create updateCategory in adapter
/*call this method(updateCategory()) in you frgament/activity to update the adapter
according to you category that is selected in dialog
*/
public void updateCategory(String category){
this.currentArticle.clear();
this.selectedCategory=category;
for(Model item: entireArticle){
if(category.equals(item.getCategory()))
{
currentArticle.add(item);
}
}
notifyDataSetChanged();
}
........
........
#Override
public View getView(int _position, View _convertView, ViewGroup _parent) {
View view = _convertView;
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.article_list_row, null);
viewHolder = new ViewHolder();
viewHolder.article_icon = (ImageView) view.findViewById(R.id.article_category_icon);
viewHolder.articleTitle = (TextView) view.findViewById(R.id.article_title);
viewHolder.articleCategory = (TextView) view.findViewById(R.id.article_category);
viewHolder.articleDate = (TextView) view.findViewById(R.id.article_date);
viewHolder.articleAuthor = (TextView) view.findViewById(R.id.article_author);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _convertView.getTag();
}
//Find the article to work with
Article currentArticle = articles.get(_position);
//just remove if condition because already you have filtered article by category in currentArticle
//fill the Article_View
switch (currentArticle.getCategory()) {
case "Kernel":
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_k);
break;
case "Security":
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
break;
default:
viewHolder.article_icon.setImageResource(R.drawable.ic_list_letter_s);
}
viewHolder.articleTitle.setText(currentArticle.getTitle());
viewHolder.articleCategory.setText(currentArticle.getCategory());
viewHolder.articleDate.setText(currentArticle.getDate());
viewHolder.articleAuthor.setText(currentArticle.getAuthor());
return view;
}
}
Do this in your Activity/Fragment which has tha ArticleAdapter
modification in onSelectedOption() method in your activity/Fragment
#Override
public void onSelectedOption() {
selectedCategory = dialog.getSelectedCategory();
preSelectedValue = dialog.getSelectedIndex();
Log.i(TAG, "selectedCategory : " +selectedCategory);
article_list_adapter.updateSelectedCategory(selectedCategory);
Log.i(TAG, "adapter Category : " +article_list_adapter.getSelectedCategory());
/*
call updateCategory() instead of notifyDataSetChanged()
updateCategory() will update your adapter
*/
//article_list_adapter.notifyDataSetChanged();
article_list_adapter.updateCategory(selectedCategory);
}
Problem in your code is
your trying to update the adapter using notifyDataSetChanged without updating your list.
notifyDataSetChanged() will work when there is an update in adapter model not in any variable in your adapter . see this how notifyDataSetChanged works in listView
EDIT:changes in adapter class
class Adapter{
ArrayList entireArticle;
ArrayList currentArticle;
public Adapter(Context context,ArrayList list){
this.entireArticle=new ArrayList();
this.currentArticle=new ArrayList();
entireArticle.addAll(list);
currentArticle.addAll(list);
}
public void updateCategory(String category){
this.currentArticle.clear();
this.selectedCategory=category;
if(category.equals("All")){ // add all article from entrieArticle if category=="all"
this.currentArticle.addAll(entireArticle);
}else{ //otherwise filter the article
for(Model item: entireArticle){
if(category.equals(item.getCategory()))
{
currentArticle.add(item);
}
}
}
notifyDataSetChanged();
}
...............
.................
}
do this changes in your adapter class and it will work i've checked this.
I hope this will help you.
I have one icon button and one listView in Activity A.
Icon button-----> intent to B, return value to A, add to new list
ListView click--> intent to B, return changed value back to listView
I use mClickedPosition=-1; to verify whether icon is clicked or listView,but it still add to new list even the listView is clicked.
Activity A
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDetails:
mClickedPosition=-1; // if icon is clicked
View menuItemView = findViewById(R.id.addDetails);
PopupMenu po = new PopupMenu(this, menuItemView); //for drop-down menu
po.getMenuInflater().inflate(R.menu.popup_details, po.getMenu());
po.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplication(), "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
if ("Add Work Details".equals(item.getTitle()))
{
Intent intent = new Intent(getApplication(), B.class); // go to Activity B
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
return true;
}
});
po.show(); //showing popup menu
}
return super.onOptionsItemSelected(item);
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition=position;
Object o = listview.getItemAtPosition(position);
SearchResults fullObject = (SearchResults) o;
String temp = fullObject.getDescription();
String Project=fullObject.getProject();
String [] ReceiveProject=Project.split(":");
String[] ReceiveDescription = temp.split(":");
Intent i = new Intent(getApplication(), B.class);
i.putExtra("ReceiveProject", ReceiveProject[1].trim());
i.putExtra("ReceiveDescription", ReceiveDescription[1]);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
ReceiveProject = data.getStringExtra("Project");
ReceiveDescription = data.getStringExtra("Description");
if(mClickedPosition==-1) { // if icon clicked
MyCustomBaseAdapter objMyCustomBaseAdapter = (MyCustomBaseAdapter) listview.getAdapter();
objMyCustomBaseAdapter.addNewItem(ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut); // add list
}
else
{
// change the current list
}
}
MyCustomBaseAdapter
public class MyCustomBaseAdapter extends BaseAdapter{ // for ListView in Activity A
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public void addNewItem(String P,String D,int Per,String I,String O)
{
SearchResults obj=new SearchResults();
obj.setProject(" Project/Service/Training : "+P);
obj.setDescription(" Work Description : " + D);
searchArrayList.add(obj);
this. notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtProject= (TextView) convertView.findViewById(R.id.ListProject);
holder.txtDescription = (TextView) convertView.findViewById(R.id.ListDescription);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtProject.setText(searchArrayList.get(position).getProject());
holder.txtDescription.setText(searchArrayList.get(position).getDescription());
return convertView;
}
static class ViewHolder {
TextView txtProject;
TextView txtDescription;
}
}
1.get the object of particular potion where you click
SearchResults obj=searchArrayList.get(postion);
2.now set the value like this way
obj.setProject(" Project/Service/Training : "+P);
obj.setDescription(" Work Description : " + D);
3.finally notify the adapter.
this. notifyDataSetChanged();
I'm trying to make an application that will show details of a ListView row on click. I added a filter and three EditTexts for search options.
I if I use all options for searching , my app shows one member three times, that's why I commented out two of the conditions in the filter() method.
But the main problem is while I'm searching for a member it searches well but when clicking on the search result it seems the position of the ListView row changed. For example, if I found three search results the first one is on position 0, second on position 1 , and third one on position 2.
The Listview click event works fine without searching.
I need the old position like it was before filtering to send it via an Intent to another Activity that will show different data for each member.
ListViewAdapter.java class
`
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context, List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, final ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position)
.getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Set the results into ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent summaryIntent = new Intent(mContext,
SecondActivity.class);
Bundle b = new Bundle();
b.putInt("Integer", position);
summaryIntent.putExtras(b);
mContext.startActivity(summaryIntent);
Toast.makeText(mContext, "Position:" + position,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(mContext, SecondActivity.class);
// Send single item click data to SingleItemView Class
// depending on "position", for example
// Pass all data rank
// intent.putExtra("rank",
// (worldpopulationlist.get(position).getRank()));
// ...likewise pass all other data ...
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText) ) {
worldpopulationlist.add(wp);
}
if(wp.getRank().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
if (wp.getPopulation().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
In order to get the "old" position of an item in the onCLick() method, use
arraylist.indexOf( getItem(position) )
Change your filter method like this to avoid multiple adding of the same item:
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else {
boolean addToList;
for (WorldPopulation wp : arraylist) {
addToList = false;
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText) ) {
addToList = true;
}
if(wp.getRank().toLowerCase(Locale.getDefault())
.contains(charText)) {
addToList = true;
}
if (wp.getPopulation().toLowerCase(Locale.getDefault())
.contains(charText)) {
addToList = true;
}
// now add the item to your list if it matches the search criteria
if (addToList) {
worldpopulationlist.add(wp);
}
}
notifyDataSetChanged();
}
}
I have a custom listView that is empty in first time , from other side i have an activity which contains a product details such as picture, title, model .in this activity there is a button , so when user press this button i want to add the product into my custom listView and shows all the product details there,
my listView is:
public class ListViewShoppingBasketActivity extends Activity {
BaseAdapter adapter;
ArrayList<SingleRow> list;
Context context;
String[] titles;
Bitmap[] images;
String[] descriptions;
TextView title;
TextView description;
ImageView image;
String rowTitles;
String rowDescription;
Bitmap rowImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_shopping_basket_layout);
final ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(new MyAdapter(this));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
if (id == 0) {
} else if (id == 1) {
} else if (id == 2) {
} else if (id == 3) {
} else if (id == 4) {
}
}
});
}
class SingleRow {
String rowTitles;
String rowDescription;
Bitmap rowImage;
public SingleRow(String rowTitles, String rowDescription, Bitmap rowImage) {
this.rowTitles = rowTitles;
this.rowDescription = rowDescription;
this.rowImage = rowImage;
}
}
class MyAdapter extends BaseAdapter {
public MyAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.shopping_basket_listview_row,
viewGroup, false);
title = (TextView) row.findViewById(R.id.textView1);
description = (TextView) row.findViewById(R.id.textView2);
image = (ImageView) row.findViewById(R.id.imageView1);
SingleRow temp = list.get(i);
title.setText(temp.rowTitles);
description.setText(temp.rowDescription);
image.setImageBitmap(temp.rowImage);
return row;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list_view_shopping_basket, menu);
return true;
}
// // **********baraye add kardane item jadid be listview
public void addItems(View v) {
list.add(new SingleRow(rowTitles, rowDescription, rowImage));
adapter.notifyDataSetChanged();
}
}
and this is implementation of my button in other activity
b_add_to_cart = (Button) findViewById(R.id.b_add_to_cart);
b_add_to_cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BarcodeDetailsActivity.this,
ListViewShoppingBasketActivity.class);
intent.putExtra("productID", proId);
intent.putExtra("productModel", proModel);
intent.putExtra("productTitle", proTitle);
intent.putExtra("productPictureUrl", mIcon11);
startActivity(intent);
}
});
my problem is , i dont know how and where i can assign my product details in my listview
You can put the next lines to the code of the ListViewShoppingBasketActivity:
Intent i = getIntent();
if (i.getExtras() != null){
int prodId = i.getExtras().getInt("productID");
....
}
You can put theese to an ArrayList, and use an BaseAdapter (http://developer.android.com/reference/android/widget/BaseAdapter.html) to display the data in the list.
My Search is done using a listView, so when the user key in the the first letter in the firstname, it will return the result, how can I make it display "no result found" in Android?
Please advise, do I need to create a a TextView?
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<User> namelist = null;
private ArrayList<User> arraylist;
public ListViewAdapter(Context context,
List<User> worldpopulationlist) {
mContext = context;
this.namelist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<User>();
this.arraylist.addAll(namelist);
}
public class ViewHolder {
TextView firstname;
TextView lastname;
TextView position;
TextView company;
ImageView pix;
TextView searchresult;
}
#Override
public int getCount() {
return namelist.size();
}
#Override
public User getItem(int position) {
return namelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.firstname = (TextView) view.findViewById(R.id.firstname);
holder.lastname = (TextView) view.findViewById(R.id.lastname);
holder.position= (TextView) view.findViewById(R.id.position);
holder.company = (TextView) view.findViewById(R.id.company);
// Locate the ImageView in listview_item.xml
holder.pix = (ImageView) view.findViewById(R.id.pix);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.firstname.setText(namelist.get(position).getFirstName());
holder.lastname.setText(namelist.get(position).getLastName());
holder.position.setText(namelist.get(position).getDesignation());
holder.company.setText(namelist.get(position).getCompanyName());
// Set the results into ImageView
holder.pix.setImageResource(namelist.get(position).getProfileImage());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data country
intent.putExtra("firstname",
(namelist.get(position).getFirstName()));
intent.putExtra("lastname",
(namelist.get(position).getLastName()));
// Pass all data rank
intent.putExtra("position",
(namelist.get(position).getDesignation()));
// Pass all data population
intent.putExtra("company",
(namelist.get(position).getCompanyName()));
// Pass all data flag
intent.putExtra("pix",
(namelist.get(position).getProfileImage()));
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
namelist.clear();
if (charText.length() == 0) {
namelist.addAll(arraylist);
} else {
for (User wp : arraylist) {
if (wp.getFirstName().toLowerCase(Locale.getDefault()).contains(charText)||wp.getLastName().toLowerCase(Locale.getDefault()).contains(charText) ) {
namelist.add(wp);
}
else
{
//what should I enter here?
}
}
}
notifyDataSetChanged();
}
}
In my App, for this case, I have an item in list which has a special type 'EMPTY_RESULT'.
Basically, after getting out result which is EMPTY, generate an item with specific type 'EMPTY_RESUT'in Adapter (means getCount() == 1 ), and notify dataset change.
Then, when getView be called, return the empty item and certainly you could design some UI for it to present empty result, such as an icon and text 'nothing found'.
Instead of creating a TextView, you can create a Toast, which is essentially a popup. You can create it like this:
Toast.makeText(mContext, "No Results Found", Toast.LENGTH_SHORT).show();
You can change the last parameter to Toast.LENGTH_LONG if you want the popup to last longer.