NullPointer Exception on notifyDatasetChanged with custom Adapter - android

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);

Related

ListView Generated from SQLite onClickListener() to take me to another activity based on where i clicked

I'm creating an android app. In this app, I have a ListView populated with data from SQLite. I am trying to add an onClickEventListener to each row of the ListView so that when a menu item is clicked it opens up another Activity with more information from the Database about the item clicked. I have succeeded in adding an event listener to the ListView, but I am not sure how to pass on database information depending on the list item clicked.
Here is my code:
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbh;
private ArrayList listItems = new ArrayList();
ArrayList<String[]> noteList;
private ArrayAdapter adapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DatabaseHelper(this);
dbh.open();
lv = (ListView) findViewById(R.id.noteListView);
noteList = dbh.selectAll();
String id = "";
String content = "";
for(int i = 0; i < noteList.size(); i++){
content = noteList.get(i)[1];
id = noteList.get(i)[0];
listItems.add(id + ", " + content);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(MainActivity.this, EditNote.class);
//i.putExtra();
startActivity(i);
}
});
}
}
In your case list has strings, so here is what you need to do:
String yourString = listItem.get(position);
i.putExtra("KEY", yourString);
startActivity(i);
And at the receiving activity you can retrieve as
intent intent = getIntent();
String yourString = intent.getExtras().getString("KEY");
EDIT: If your list is having some POJO class or simple class objects
You can pass to second activity like this
intent.putExtra("Your class", obj);
To retrieve object in second Activity
getIntent().getSerializableExtra("Your class");
EDIT: One important thing to remember.
If you passing a class object it must implement Serializable or Parcelable interface.
For eg
class Student implements Serializable{
}
You should make a custom adapter that extends the arrayadapter. Load everything from your database into an arraylist and use something like this:
// CODE DOES NOT WORK WITH YOUR CODE, IT'S JUST AN EXAMPLE
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
...
lv.setAdapter(new MyClassAdapter(....));
In your OnItemClickListener you have the position of the clicked item so to get the object use MyClass object = lv.getItemAtPosition(position); and use that object to pass data to the new activity.
Intent intent = new Intent(getBaseContext(), my.class);
intent.putExtra("key", "value");
startActivity(intent);
To access
String s = getIntent().getStringExtra("key");
More: https://stackoverflow.com/a/2265712/2890156

Hello, I have been working on android project where I need to send the selected String from listview to another activity

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

Ckeckebale box in ListActivity

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

listview with arraylist,simple adapter in android

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 variable on ArrayAdapter method, Android

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.

Categories

Resources