I have a public method in DatabaseHelper.java class like below:
public List<Presentation> getAllPresentations() {
List<Presentation> presentations = new ArrayList<Presentation>();
//
//
// some code
//
//
return presentations;
}
In my MainActivity.java I have added this lines:
btnLoad.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
List list = db.getAllPresentations();
ListView l;
l=(ListView)findViewById(R.id.list);
l.setAdapter(new ArrayAdapter<List>(this,R.layout.view_presentation, list));
}
});
BUT, something is wrong on the line:
l.setAdapter(new ArrayAdapter<List>(this,R.layout.view_presentation, list));
Can someone help me?
There are at least two problems:
In the context of an anonymous inner class (like new View.OnClickListener()), this refers to the instance of the inner class. The ArrayAdapter constructor needs a Context, so you must use MainActivity.this instead.
The type parameter of ArrayAdapter<T> must be the item type. So in this case, it should be ArrayAdapter<Presentation>.
So:
List<Presentation> list = db.getAllPresentations();
ListView l = (ListView)findViewById(R.id.list);
l.setAdapter(new ArrayAdapter<Presentation>(MainActivity.this, R.layout.view_presentation, list));
Related
I have an custom adapter that is giving me problem. When I add or edit something it updates the listview but when I delete it doesn't.
Code when I remove something:
private ArrayList<Teams> m_orders = null;
private TeamsAdapter m_adapter;
private ListView lstv;
...
private void deleteTeam(int indexRemove){
hasKeys.remove(hasKeys.indexOf(m_orders.get(indexRemove).getTeamName()));
Menu.teams.remove(m_orders.get(indexRemove).getTeamName());
m_orders.remove(indexRemove);
m_adapter.notifyDataSetChanged();
}
I tried use a Runnable, but without success.
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_adapter.notifyDataSetChanged();
}
};
My onCreate method:
lstv = findViewById(R.id.teamsList);
m_orders = new ArrayList<Teams>();
this.m_adapter = new TeamsAdapter(this, R.layout.row, m_orders);
lstv.setAdapter(this.m_adapter);
You have to remove an item from the ArrayList which is inside the Adapter class. So you need to write your delete function inside the adapter class. In this way will able to delete items and update listview by calling notifyDataSetChanged() method.
You are creating an m_adapter with m_orders dataset, but you are removing item from m_teams dataset, make no sense, they are different instances.
final List<Teams> mTeams = new ArrayList<>();
TeamsAdapter mAdapter;
onCreate() {
mAdapter = new TeamsAdapter(this, R.layout.row, mTeams);
ListView listView = (ListView) findViewById(R.id.teamsList);
listView.setAdapter(mAdapter);
}
addTeams(Collection<Teams> items) {
mTeams.addAll(items);
mAdapter.notifyDataSetChanged();
}
deleteTeam(int index) {
mTeams.remove(index);
mAdapter.notifyDataSetChanged();
}
i don't know why but when i add items to listview i get only the last item. E.G. if i write apple and than pear i get only pear and not apple and pear.
Why?
CODE:
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("IDDD:"+iddd);
System.out.println("IDDD:"+video2.getPic());
//holder.lw.setA
String commento= (holder.tw.getText().toString());
// holder.lw.setAdapter(adapter);
ArrayList<String> arrayList= new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrayList);
arrayList.add(commento);
// next thing you have to do is check if your adapter has changed
holder.lw.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println("LISTVIEW:"+arrayList);
}
});
in every click you decalre new list ArrayList<String> arrayList= new ArrayList<String>(); and it's false
you need to declate it out of the listener and in your listener just add the new items and use adapter.notifyDataSetChanged();
You are creating new list and adapter during every click so move the declaration and initialization of both, outside that function
Declare them outside getView(if Base or ArrayAdaoter) or createViewHolder (RecyclerAdapter)
initialize them inside constructor
add data to list and notify adapter
Better use view holder pattern in here where you use Existing instance of listview rather than recreating the new one all the time.
You don't need to do anything special, inside of onClick you need to get a reference to your ArrayAdapter and call the method add(T...) on it.
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("IDDD:"+iddd);
System.out.println("IDDD:"+video2.getPic());
String commento= (holder.tw.getText().toString());
ArrayAdapter adapter = (ArrayAdapter) holder.lw.getAdapter();
adapter.add(commento);
}
});
No need to even call notifyDataSetChanged because add already does that internally.
if you use this you can solve your problem
yourAdapter.(getCount()-1-position);
and this if you want to see the last items in front
public yourPoJo getItem(int position) {
return super.getItem(getCount()-1-position);
}
I am new in Android. I need your help. My Problem is - I have 2 classes Nplist.java and Addcustomer.java. In my AddCustomer class,One TextView and one Button is there to go Nplist class. In my Nplist class there is checklist and this checklist is coming from database and all the checked values are stored in ArrayList<String> and one Button is used to go back to AddCustomer class. I want that ArrayList<String> which is in Nplist to by display in my AddCustomer class Textview . I haved tried these but my Addcustomer class crashed.
1.Nplist.class
add.setOnClickListener(new View.OnClickListener() {<br>
#Override<br>
public void onClick(View view) {<br>
Bundle extra=new Bundle();<br>
extra.putSerializable("objects",checkedList);<br>
Intent intent = new Intent(Nplist.this, AddCustomer.class);<br>
intent.putExtra("extra",extra);<br>
startActivity(intent);<br>
});
2.AddCustomer.class
onCrete()...{
Bundle extra = getIntent().getBundleExtra("extra");<br>
ArrayList<String> object = (ArrayList<String>)extra.getSerializable("objects");<br>
for (String str : object) {<br>
getnp.append(str + "\n");<br>
}
}
What do you expect the result to be?
- What is the actual result you get? (Please include any errors.)
When i go like this Nplist-->AddCustomer its working well but crash on ( AddCustomer-->Nplist-->AddCustomer)
It's because when you are coming back to your AddCustomer Activity the list is null . You can solve this problem by making a global class which will store the list in a Static Field , And You can access that list from any class or Activity you want to. Try out below solution .
Global.java Class is as below :
public class Global {
private static ArrayList<String> object = new ArrayList<>();
public static ArrayList<String> getObject() {
return object;
}
public static void setObject(ArrayList<String> object) {
Global.object = object;
}
}
From NpList.java class set the value of the list as below :
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.setObject(checkedList);
Intent intent = new Intent(Nplist.this, AddCustomer.class);
startActivity(intent);
}
});
Now Access in AdCustomer.java as below :
onCreate()...{
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<String> object = Global.getObject();
for (String str : object) {
getnp.append(str + "\n");
}
}
This maybe helpful for you.
Using putStringArrayListExtra method you can send an array list of strings along with the intent.
Sender side:
Intent intent = ...
intent.putStringArrayListExtra("THE_KEY", theList);
Receiver side:
ArrayList<String> theList = intent.getStringArrayListExtra("THE_KEY");
I have two classes , the first one is for the GUI , where I declared my listview and the adapter , and the setters , to call them from my second class .
public class AndroidGUIModifier implements IMyComponentGUIModifier, IFragmentEvents {
private transient ListView lv;
List<String> mydeviceslist;
ArrayAdapter<String> adapter ;
public void setAdapter(ArrayAdapter<String> adapter) {
this.adapter = adapter;
adapter.notifyDataSetChanged();
}
public void setMydeviceslist(List<String> mydeviceslist) {
this.mydeviceslist = mydeviceslist;
}
#Override
public void onCreateView() {
lv=(ListView) fragment.findViewById("xdevices") ;
mydeviceslist = new ArrayList<String>();
adapter = new ArrayAdapter<String>(fragment.getContext(),android.R.layout.simple_list_item_1,mydeviceslist);
lv.setAdapter(adapter);
In my second class I'll wait an event to receive the list that I want to load it in my listview , then I'll call the list setter to set the new received list and the adapter setter to update it , but it didn't work , nothing was displayed despite I receieved the list of devices in my log .
public class triprincipal extends BCModel {
public List<String> mydevices ;
BCEvent bcEvent;
final ArrayAdapter<String> adapter =guiModifier.getAdapter();
while (isRunning()) {
bcEvent = waitForBCEvent();
if (bcEvent.getID() == checkevent) {
mydevices = bcCommandSenderPlugin.getDevicesNames(); // here I get a list of my devices
Log.i("devices", mydevices.toString());
guiModifier.getFragment().getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
guiModifier.setMydeviceslist(mydevices);
guiModifier.setAdapter(adapter);
}
} );
In setMydeviceslist() do it like:
this.mydeviceslist.addAll(mydeviceslist);
adapter.notifyDataSetChanged();
Hope it will help you out.
adapter.notifyDataSetChanged() will not work in this case, as the value of the reference you have passed to the adapter doesn't actually change.
You will need to create a new Adapter and set it to the ListView to make it work. Change your setAdapter() to this :
public void setAdapter() {
this.adapter = new ArrayAdapter<String>(fragment.getContext(), android.R.layout.simple_list_item_1, mydeviceslist);
lv.setAdapter(adapter);
}
try to update the list in same fragment/activity and after update call notifyDataSetChanged() both in same activity/fragment ....donot set adapter on list repetedly......hope it helps
I have an activity Mainactivity, in this when a button is pressed then it will show a listview. But in
listAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, android.R.id.text1, value);
I am getting "Cannot resolve constructor ArrayAdapter (anonymous android view.View.OnClickListener, int, int, java.lang.String)"
My outer class is "Mainactivity" I tried "Mainactivity.this" instead of "this". But It is showing "cannot resolve constructor" error.
MainActivity class extends Actionbaractivity implements onItemelectedListner
My code is:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cnt.getText().toString().length() > 0 &&
number.getText().toString().length() > 0 &&
Integer.parseInt(number.getText().toString()) > 0 &&
Integer.parseInt(cnt.getText().toString()) > 0) {
number.requestFocus();
String[] value = new String{"hello","world"};
try {
temp_count = temp_count + Integer.parseInt(cnt.getText().toString());
count.setText(String.valueOf(temp_count));
temp_amt = temp_amt + (Integer.parseInt(cnt.getText().toString()) * tkt_rate);
amount.setText(String.valueOf(temp_amt));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, value);
lstView.setAdapter(listAdapter);
lstView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SparseBooleanArray checked = lstView.getCheckedItemPositions();
int size = checked.size(); // number of name-value pairs in the array
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value) {
row = lstView.getChildAt(i);
row.setBackgroundColor(Color.parseColor("#33B5E5"));
} else {
row = lstView.getChildAt(i);
row.setBackgroundColor(Color.parseColor("#F0F0F0"));
}
}
}
});
Please help...
The error shows that you are putting android view.View.OnClickListener as the first argument.
I know you said you have tried, but you really need to use Mainactivity.this. If it is not working please post the code of the start of your java file.
Also is your activity named as Mainactivity? Remember it is case sensitive, should it be MainActivity? If so, you have to use MainActivity.this
I think it's happening because your class implements onclicklistener. So can you try cast this to Activity? Like the code below:
listAdapter = new ArrayAdapter((Activity)this, android.R.layout.simple_list_item_1, android.R.id.text1, value);
ArrayAdapter needs Context as the first argument. What you can do is to have a field reference to your Context, like the followings.
Added a field to your Activity, private Context mContext;
Inside the onCreate() of your Activity, mContext = this;
Use the mContext to construct ArrayAdapter, listAdapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, android.R.id.text1, value);
Maybe this will help you:
listAdapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
Collections.singletonList(value));