I Want to select various dishesh from MenuCard Activity
Here is my ProductAdapter
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import com.beans.Product;
import com.vinayak.hk.MenuCard;
import com.vinayak.hk.R;
public class ProductAdapter extends ArrayAdapter<Product> {
ArrayList<Product> allProducts;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ProductAdapter (Context context , int resource ,ArrayList<Product> objects)
{
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
allProducts = objects;
}
#Override
public View getView(int position ,View convertView,ViewGroup parent)
{
View v = convertView;
if(v==null)
{
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.name = (TextView) v.findViewById(R.id.tv1);
holder.price = (TextView) v.findViewById(R.id.price);
holder.checkbox = (CheckBox) v.findViewById(R.id.cb1);
v.setTag(holder);
}
else{
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.ic_launcher);
holder.name.setText(allProducts.get(position).getProduct_name());
int s = allProducts.get(position).getProduct_price();
//Log.d("********************",Integer.toString(s));
holder.price.setText(Integer.toString(s));
//final ListView lv = (ListView) parent;
//holder.checkbox.setChecked(lv.isItemChecked(position));
//holder.checkbox.setChecked(false);
return v;
}
static class ViewHolder {
public TextView name;
public TextView price;
public CheckBox checkbox ;
}
}
And my ListActivity is:
MenuCard.java
public class MenuCard extends ListActivity {
ListView list;
Button btn1;
String url="";
private ArrayList <Product> allProducts = new ArrayList<Product>();
private ProductAdapter adapter;
public static boolean[] arrBoolean = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_card);
btn1 = (Button) findViewById(R.id.btn);
list = getListView();
Bundle d = getIntent().getExtras();
url="http://10.0.2.2:8084/Hotelkart/Product?id="+d.getInt("id");
try{
ConnectivityManager c =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo n =c.getActiveNetworkInfo();
if (n!= null && n.isConnected()){
Log.d("url*********",url);
new Background().execute(url);
}
}catch(Exception e){}
//Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
adapter = new ProductAdapter(getApplicationContext(),R.layout.productrow,allProducts);
setListAdapter(adapter);
list.setItemsCanFocus(false);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checked = list.getCheckedItemPositions();;
ArrayList<String> selectedItems = new ArrayList<String>();
ArrayList<Integer> selectedItemsPrice = new ArrayList<Integer>();
ArrayList<Integer> selectedItemsId = new ArrayList<Integer>();
Log.d("**************",Integer.toString(checked.size()));
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
{
selectedItems.add(adapter.getItem(position).getProduct_name());
selectedItemsPrice.add(adapter.getItem(position).getProduct_price());
selectedItemsId.add(adapter.getItem(position).getProduct_id());
}
}
int k = selectedItems.size();
int[] outputStrArrId = new int[k];
int[] outputStrArrPrice = new int[k];
String[] outputStrArrItem = new String[k];
for (int i = 0; i < k; i++) {
outputStrArrItem[i] = selectedItems.get(i);
outputStrArrId[i] = selectedItemsId.get(i);
outputStrArrPrice[i] = selectedItemsPrice.get(i);
}
Intent intent = new Intent(getApplicationContext(), AddOrder.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("st3", outputStrArrItem);
b.putIntArray("st1",outputStrArrId );
b.putIntArray("st2",outputStrArrPrice );
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
});
}
but i get an error at
02-01 00:39:08.579: E/AndroidRuntime(1619): java.lang.NullPointerException
02-01 00:39:08.579: E/AndroidRuntime(1619): at com.vinayak.hk.MenuCard$1.onClick(MenuCard.java:95)
02-01 00:39:08.579: E/AndroidRuntime(1619): at android.view.View.performClick(View.java:4438)
02-01 00:39:08.579: E/AndroidRuntime(1619): at android.view.View$PerformClick.run(View.java:18422)
02-01 00:39:08.579: E/AndroidRuntime(1619): at android.os.Handler.handleCallback(Handler.java:733)
I have problem retriving checked item
when i press btn1 i get above message
on ***************
for (int i = 0; i < checked.size(); i++)
.Please help me,
Getting NullPointerException because getCheckedItemPositions() return null because you are using custom layout for ListView and customized ArrayAdapter for creating ListView row.
To get all checked item from ListView:
Option 1. Use android.R.layout.simple_list_item_multiple_choice layout and default ArrayAdapter implementation :
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
<price_list>);
and make sure choiceMode mode is enabled in ListView using android:choiceMode="multipleChoice"
Now use getCheckedItemPositions() to get set of checked items in the list.
Option 2. if custom layout and adapter is necessary for application then customize ProductAdapter to save and retrieve checked checkbox positions.
See following example:
Implement custom multi select ListView with custom ArrayAdapter
Related
In my program I have fetched the data's from the server and view it in a listview. Then from those retrieved data in listview I have to select a string and that string will be passed on to another activity. My data's are retrieved and showed in listview but when I select an item(String) and try to send it to the next activity then instead of that string the package name is passed.
The layout code for retrieving and sending selected String is given below:
public class Doctors_layout extends Fragment implements
AdapterView.OnItemSelectedListener{
public final static String Message = "Sohan";
View myView;
Spinner spinner;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
String JSON_String;
ContactAdapter contactAdapter;
ListView listView;
Button button;
String send;
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.doctors_directory, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
spinner.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("Choose a City");
city.add("Chittagong");
city.add("Dhaka");
ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item ,city);
aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// here we have to select medical name and intent viewDoctor page
Intent intent = new Intent(myContext, viewDoctor.class);
send = listView.getItemAtPosition(position).toString(); // doesn't retrieve the selected text, intead chooses package name
intent.putExtra(Message, send);
Toast.makeText(myContext, "Listview item "+send, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
return myView;
}
And my custom contact adapter class is given below:
package com.example.sohan.patient;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
View row;
ContactHolder contactHolder;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.MedicalName.setText(contacts.getMedicalName());
return row;
}
static class ContactHolder{
TextView MedicalName;
}
}
Try this, I hope it work...
send = ((TextView) view.findViewById(R.id.textView5)).getText().toString();
or
send = (String) parent.getItemAtPosition(position);
thanks..
send = listView.getItemAtPosition(position).toString();
you are sending a listView object and not actual string.
use:
send = yourListOfStrings.get(position)
UDP:
You are trying to create an adapter with onItemClick listener attacked to it:
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
right?
So you are suppose to fill(But I haven't found where you are doing this) this adapter with some data:
public void add(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
and you want to send a string from from the element of this list to another acitvity, right?
So you need to select an element of this list
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
send = updatedList.get(position).getYourString
inside onItemClickListener
I have been searching about this issue but still I am not very clear on how to use a click listener with an array adapter.
I need a click listener for each item of the list.
Codes:
The Area item:
package fogames.tamagomonsters;
public class Area {
public String name;
public String number;
public Area(String name, String number) {
this.name = name;
this.number = number;
}
}
The array adapter:
package fogames.tamagomonsters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class AreasAdapter extends ArrayAdapter<Area> {
public AreasAdapter(Context context, ArrayList<Area> Areas) {
super(context, 0, Areas);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Area Area = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_area, parent, false);
}
// Lookup view for data population
TextView tvname = (TextView) convertView.findViewById(R.id.tvName_area);
TextView tvnumber = (TextView) convertView.findViewById(R.id.tvNumber_of_beasts);
// Populate the data into the template view using the data object
tvname.setText(Area.name);
tvnumber.setText(Area.number);
// Return the completed view to render on screen
return convertView;
}
}
The activity:
package fogames.tamagomonsters;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import java.util.ArrayList;
public class PlayMenuActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
FrameLayout fl = new FrameLayout(this);
fl.setBackgroundColor(Color.argb(255, 0, 0, 0));
// Construct the data source
ArrayList<Area> arrayOfAreas = new ArrayList<Area>();
// Create the adapter to convert the array to views
AreasAdapter adapter = new AreasAdapter(this, arrayOfAreas);
// Attach the adapter to a ListView
ListView lv = new ListView(this);
lv.setAdapter(adapter);
// Restore preferences
SharedPreferences prefs = getSharedPreferences(PreferenceConstants.PREFERENCE_NAME, MODE_PRIVATE);
int mlen = prefs.getInt(PreferenceConstants.MLEN, 0);
long money = prefs.getLong(PreferenceConstants.MONEY, 0);
int mall = 6; //hay que ver que hacer con esto...
int eqall = 3; //igual
boolean[] mgot = new boolean[mall];
int[] exp = new int[eqall];
int[] lvl = new int[eqall];
int[] at = new int[eqall];
int[] en = new int[eqall];
for (int i = 0; i < mall; i++) {
mgot[i] = prefs.getBoolean(PreferenceConstants.MGOT[i], false);
}
for (int i = 0; i < eqall; i++) {
exp[i] = prefs.getInt(PreferenceConstants.EXP[i], 0);
lvl[i] = prefs.getInt(PreferenceConstants.LVL[i], 0);
at[i] = prefs.getInt(PreferenceConstants.AT[i], 0);
en[i] = prefs.getInt(PreferenceConstants.EN[i], 0);
}
String name[] = {getString(R.string.a001)};
int prado_got = 0;
if (mgot[0]) {
prado_got += 1;
}
if (mgot[3]) {
prado_got += 1;
}
String prado = String.valueOf(prado_got) + " / 2";
String number[] = {prado};
// Add item to adapter
Area a001 = new Area(name[0], number[0]);
adapter.add(a001);
this.setContentView(fl);
}
}
Thank you in advance.
You can do something like that:
•First insert in your adapter this method
#Override
public Area getItem(int position) {
return [yourArrayAreas].get(position);
}
•Then, in your Activity...
final AreasAdapter adapter = new AreasAdapter(this, arrayOfAreas);
ListView lv = new ListView(this);
lv.setAdapter(adapter);
mListStopsMuni.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id{
Area yourClickArea = adapter.getItem(position);
//Rest of code...
}
});
Good luck ;)
Something like this:
ArrayList<Area> arrayListAreas;
public AreasAdapter(Context context, ArrayList<Area> Areas) {
super(context, 0, Areas);
this.arrayListAreas = Areas;
}
//And then....
#Override
public Area getItem(int position) {
return arrayListAreas.get(position);
}
This is my first post on stack overflow so apologies if confusing.
I am getting nullpointer on foodListAdapter.notifyDatasetChanged() in my onClick method.
I am using a custom adapter. My onClick method is in my MainActivity class below. Also, please note that if I comment out the foodListAdapter.notifyDataSetChanged in my onClick method and uncomment out the other 3 lines, my code works fine. But I think this is not the cleanest way.
public class MainActivity extends Activity implements View.OnClickListener
{
Button mainButton;
ListView mainListView;
ArrayAdapter spinnerDataAdapter;
FoodListAdapter foodListAdapter;
ArrayList newFoodList = new ArrayList();
ShareActionProvider mShareActionProvider;
private static final String PREFS = "prefs";
private static final String PREF_NAME = "name";
SharedPreferences mSharedPreferences;
Spinner mainSpinner;
TextView foodTextView;
CharSequence currentDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Access button in activity_main and set onClickListener
mainButton = (Button) findViewById(R.id.main_button);
mainButton.setOnClickListener(this);
//Access edit text in activity_main
foodTextView = (TextView) findViewById(R.id.food_textview);
//Access list view in activity_main
mainListView = (ListView) findViewById(R.id.main_listview);
mainSpinner = (Spinner) findViewById(R.id.main_spinner);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
//Create an array foodListAdapter for the spinner
spinnerDataAdapter = ArrayAdapter.createFromResource(this, R.array.food_types, android.R.layout.simple_spinner_item);
mainSpinner.setAdapter(spinnerDataAdapter);
//Set this listview to react to items being pressed
// mainListView.setOnItemClickListener(this);
//Greet the user or ask for their name if they are new
displayWelcome();
//create food list and create foodListAdapter then set the foodListAdapter
newFoodList.add(new FoodItem(R.drawable.ic_chicken, "Chicken"));
FoodListAdapter adapter = new FoodListAdapter(this,
R.layout.listview_item_row, newFoodList);
mainListView.addHeaderView(header);
mainListView.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);
//Access the Share Item defined in the menu XML
MenuItem shareItem = menu.findItem(R.id.menu_item_share);
//Access the object responsible for
//putting together the sharing submenu
if(shareItem !=null) {
mShareActionProvider = (ShareActionProvider)shareItem.getActionProvider();
}
return true;
}
public CharSequence getFormattedDate(){
Date d = new Date();
CharSequence s = DateFormat.format("MMMM d, yyyy ", d.getTime());
return s;
}
#Override
public void onClick(View v) {
currentDate = getFormattedDate();
foodTextView.setText(mainSpinner.getSelectedItem().toString());
newFoodList.add(new FoodItem(R.drawable.ic_chicken, mainSpinner.getSelectedItem().toString() + " was stored on: " + currentDate ));
foodListAdapter.notifyDataSetChanged();
// FoodListAdapter foodListAdapter = new FoodListAdapter(this,
// R.layout.listview_item_row, newFoodList);
// mainListView.setAdapter(foodListAdapter);
}
And here is my full custom adapter code:
package com.vintage.freshulator;
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;
import java.util.ArrayList;
public class FoodListAdapter extends ArrayAdapter<FoodItem> {
Context context;
int layoutResourceId;
ArrayList<FoodItem> data;
public FoodListAdapter(Context context, int layoutResourceId, ArrayList data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
FoodListHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new FoodListHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (FoodListHolder)row.getTag();
}
FoodItem foodItem = data.get(position);
holder.txtTitle.setText(foodItem.title);
holder.imgIcon.setImageResource(foodItem.icon);
return row;
}
static class FoodListHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
First of all you are using a variable that will not be reachable later by other methods. Instead create your adapter in onCreate like this:
foodListAdapter = new FoodListAdapter(this, R.layout.listview_item_row,
newFoodList);
mainListView.setAdapter(foodListAdapter);
Second of all changing the array in your activity won't change it inside of the adapter. So make the data variable inside of the adapter public:
public ArrayList<FoodItem> data;
Then in your onClick method, you can manipulate the adapters data like this:
foodListAdapter.data.add(new FoodItem(R.drawable.ic_chicken,
mainSpinner.getSelectedItem().toString()+" was stored on: "+currentDate));
foodListAdapter.notifyDataSetChanged();
Use
foodListAdapter = new FoodListAdapter(this,
R.layout.listview_item_row, newFoodList);
for creating FoodListAdapter object. getting NullPointer Exception because foodListAdapter is null(creating new adapter object of FoodListAdapter ).
Your foodListAdapter is null, because you are initializing it with adapter and using notifyDatasetChanged with foodListAdapter,so
change
FoodLisAdapter adapter = new FoodListAdapter(this,
R.layout.listview_item_row, newFoodList);
mainListView.addHeaderView(header);
mainListView.setAdapter(adapter);
to
foodListAdapter = new FoodListAdapter(this,
R.layout.listview_item_row, newFoodList);
mainListView.addHeaderView(header);
mainListView.setAdapter(foodListAdapter);
I try to show something into listview using arraylist and simple adapter.
I tried something like below but in my result shows the last names of the arraylist.
What is my wrong i cant understand.
final ListView listView = (ListView) findViewById(R.id.mylist);
ArrayList<HashMap<String, String>> list_of_bookmarks = new ArrayList<HashMap<String, String>>();
HashMap<String, String> b = new HashMap<String, String>();
String[] from = { "php_key","c_key","android_key","hacking_key" };
String[] name_of_bookmarks = { "php","c","android","hacking" };
for(int i=0;i<4;i++)
{
b.put(from[i],name_of_bookmarks[i]);
list_of_bookmarks.add(b);
}
};
int[] to = { R.id.txt1,R.id.txt1,R.id.txt1,R.id.txt1};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), list_of_bookmarks, R.layout.list_layout, from, to);
listView.setAdapter(adapter);
I just want to show "php","c","android","hacking" in a listview.
And what should be more efficient way to do that.I am a beginner so you may suggest a better way which should i follow
My advice to you would be to create a separate class that extends the Adapter(or some subclass of it)
Here is a simple example of a String array adapter.
package ro.gebs.captoom.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import antistatic.spinnerwheel.adapters.AbstractWheelTextAdapter;
import com.example.captoom.R;
public class LanguagesAdapter extends AbstractWheelTextAdapter {
// Countries names
private String languages[];
public LanguagesAdapter(Context context) {
super(context, R.layout.lang_item, NO_RESOURCE);
languages = context.getResources().getStringArray(R.array.lang_array);
setItemTextResource(R.id.language_txt);
}
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
return view;
}
#Override
public int getItemsCount() {
return languages.length;
}
#Override
protected CharSequence getItemText(int index) {
return languages[index];
}
}
and the usage is simple just use the method .setAdapter();
Or another example which uses an arrayAdapter:
package apc.example;
import java.util.ArrayList;
import utils.BitmapManager;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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 PersonAdapter extends ArrayAdapter<Person> {
Context context;
int layoutResourceId;
ArrayList<Person> data = null;
public PersonAdapter(Context context, int layoutResourceId,
ArrayList<Person> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ItemHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ItemHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.icon);
holder.txtName = (TextView) row.findViewById(R.id.title);
holder.txtDescription = (TextView) row.findViewById(R.id.desc);
row.setTag(holder);
} else {
holder = (ItemHolder) row.getTag();
}
Person bean = data.get(position);
holder.txtName.setText(bean.getName());
holder.txtDescription.setText(bean.getDescription());
Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.user);
BitmapManager.INSTANCE.setPlaceholder(b);
BitmapManager.INSTANCE.loadBitmap(bean.getUrl(), holder.imgIcon, 80, 80);
return row;
}
public static class ItemHolder {
public ImageView imgIcon;
TextView txtName;
TextView txtDescription;
}
public void updateAdapter(ArrayList<Person> pers){
this.data = pers;
}
}
This is an example of an adapter for a more complex class that has more fields rather than a simple string. But that can easily be modified to ArrayAdapter<String> and then go from there.
Anyways i think it's always a best practice to write your custom adapters for listviews.
Hope this helps!
Main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60dp" >
<ListView
android:id="#+id/zone_list"
android:layout_marginBottom="70dp"
android:background="#drawable/batteryborder"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
setlanguage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60dp">
<TextView
android:id="#+id/tvName"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18dp"
android:gravity="center_vertical" />
</LinearLayout>
add in onCreate() of your activity file
ListView listView;
String[] from = { "php_key","c_key","android_key","hacking_key" };
ArrayAdapter arrayAdapter;
listView = (ListView) findViewById(R.id.zone_list);
arrayAdapter = new ArrayAdapter<>(this,R.layout.setlanguage, R.id.tvName, from);
listView.setAdapter(arrayAdapter);
You're reusing the same view in your int[] object.
int[] to = { R.id.txt1,R.id.txt1,R.id.txt1,R.id.txt1};
It looks like it's treating them all as the same object, so each time it adds a new item it changes the previous ones.
In order to use the SimpleAdapter you will need to define each view in the XML with different IDs.
int[] to = { R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4};
The SimpleAdapter may be simpler in regard to it's internal complexity, but it's definitely not simpler to actually use. With an ArrayAdapter you can just pass it the list of items and let it generate views automatically. It can be any size you need it to be so long as you don't run out of memory. (See below for example)
Once you start working with custom adapters I highly recommend you watch Romain Guy & Adam Powell's I/O talk. It's all a lot to take in when learning, but they do a great job of explaining how ListViews work.
//List of Items
String[] name_of_bookmarks = { "php","c","android","hacking" };
//Create your List object for the ArrayAdapter
//and make it the same size as name_of_books
List<String> listBookmarks = new ArrayList<String>(Array.getLength(name_of_bookmarks));
//Add name_of_bookmarks contents to listBookmarks
Collections.addAll(listBookmarks, name_of_books);
//Create an ArrayAdapter passing it the Context, a generic list item and your list
//An alternative to "this" would be "getApplicationContext()" from your main activity
//or "getActivity()" from a fragment. "getBaseContext()" is not recommended.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_item_text, listBookmarks);
//Set the adapter to your ListView
final ListView listView = (ListView) findViewById(R.id.mylist);
listView.setAdapter(arrayAdapter);
Try this one
public class MyFragment extends ListFragment{
String[] from = { "php_key","c_key","android_key","hacking_key" };
String[] name_of_bookmarks = { "php","c","android","hacking" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
List<HashMap<String, String>> list= new ArrayList<HashMap<String,String>>();
for (int i = 0; i < name_of_bookmarks.length; i++) {
HashMap<String, String> map= new HashMap<String, String>();
map.put("key", name_of_bookmarks[i]);
list.add(map);
}
String[] from = { "key" };
int[] to = { R.id.txt};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), list, R.layout.list_layout, from, to);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Whatever You Are Face Problem Exactly I Am Face Of The Problem Called "List
View Display Last Position Of Data Of An Array..."
The Problem Is Generated With Hash Map
final ListView listView = (ListView) findViewById(R.id.mylist);
ArrayList<HashMap<String, String>> list_of_bookmarks = new ArrayList<HashMap<String, String>>();
String[] from = { "php_key","c_key","android_key","hacking_key" };
String[] name_of_bookmarks = { "php","c","android","hacking" };
for(int i=0;i<4;i++)
{
HashMap<String, String> b = new HashMap<String, String>();
b.put(from[i],name_of_bookmarks[i]);
list_of_bookmarks.add(b);
}
};
int[] to = { R.id.txt1,R.id.txt1,R.id.txt1,R.id.txt1};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), list_of_bookmarks, R.layout.list_layout, from, to);
listView.setAdapter(adapter);
Try Out This One If Any Doubt Created In Your Mind Then Ask Me Whatever Question Again
Simply You Have To Declared Your Hash Map Inside Your For Loop ...
Using Hash Map Inside Your For Loop Variable 'b' Created Each & Every Time With Considered As An Different Object. And Then Simply Array List Display Different Object Of Hash Map.
You Are Using Same Object To Store Value Of Hash Map And That Variable Was Override With Same Name That's Why you Are Faced The Problem
Thank You...
getting compile error for the "CheckBoxInfo" variable in the code below, it is correct yet i get the error,
listview = (ListView) findViewById(R.id.listView);
myAdapter = new MyAdapter(this, R.layout.row_layout, CheckBoxInfo);
listview.setAdapter(myAdapter);
from the documents it says: "the objects to represent in the Listview", however CheckBoxInfo IS the objects to represent in the listview. what is wrong here?
the rest of the code:
public class MainActivity extends Activity {
CheckBoxInfo cbr;
private ListAdapter MyAdapter;
ListView listview;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbr = new CheckBoxInfo();
cbr.checkBoxName = "dfdjklfjdkljf";
cbr.checkBoxState = true;
listview = (ListView) findViewById(R.id.listView);
myAdapter = new MyAdapter(this, R.layout.row_layout, CheckBoxInfo);
listview.setAdapter(myAdapter);
}
public class MyAdapter extends ArrayAdapter<CheckBoxInfo> {
private List<CheckBoxInfo> checkBoxList;
private Context context;
public MyAdapter(List<CheckBoxInfo> infoList, Context context) {
super(context, R.layout.row_layout, infoList);
this.checkBoxList = infoList;
this.context = context;
for(int i = 0; i <=12; i++){
checkBoxList.add(cbr);
}
}
public View getView(int position, View convertView, ViewGroup parent) {
// First let's verify the convertView is not null
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_layout, parent, false);
}
// Now we can fill the layout with the right values
TextView tv = (TextView) convertView.findViewById(R.id.textView1);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
CheckBoxInfo cbi = checkBoxList.get(position);
tv.setText(cbi.checkBoxName);
return convertView;
}
} // end MyAdapter
}
the other class, representing objects to populate the listview:
public class CheckBoxInfo {
Boolean checkBoxState;
String checkBoxName;
public CheckBoxInfo(){
checkBoxState = false;
checkBoxName = "";
}
}
The error in the arguments you pass to the constructor
listview = (ListView) findViewById(R.id.listView);
List<CheckBoxInfo> ls = new ArrayList<CheckBoxInfo>();
ls.add(cbr);
myAdapter = new MyAdapter(ls, this);
listview.setAdapter(myAdapter);
And the override of toString function in CheckBoxInfo class
public String toString(){
return "Name : " + checkBoxName + " , Checked : " + checkBoxState;
}
You should pass a list of CheckBoxInfo elements in the ArrayAdapter constructor.
ArrayList<CheckBoxInfo> items = new ArrayList<CheckBoxInfo>();
// add elements to the list
(...)
myAdapter = new MyAdapter(this, R.layout.row_layout, items);
See constructor of myAdapter class is having only 2 argument.and in your code you are calling constructor with 3 arguments.