Adapter_Android listview [duplicate] - android

This question already has an answer here:
Setting more than one adapter for a single list view
(1 answer)
Closed 8 years ago.
My problem is that I have two classes and I want to show them in a ListView. I want to merge between those ones into one list view in AsyncTask, there is my code and I need a help.
protected Void doInBackground(Void... params) {
twitt = Services.getTwitterTv();
twittns = Services.getTwitter();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
for (Twitter twitts : twitt)
for(Twitter twittn: twittns)
{
System.out.println(twitts.getTexte());
System.out.println(twittn.getTexte());
}
progressDialog.dismiss();
twitt.addAll(Services.getTwitter());
twitt.addAll(Services.getTwitterTv());
TwitterAdapter adapter = new TwitterAdapter(TwitterTv.this, R.layout.twitts_item, twitt );
TwitterAdapter adapter2 = new TwitterAdapter(TwitterTv.this, R.layout.twitts_item, twittns );
twitterlist.setAdapter(adapter);
twitterlist.setAdapter(adapter2);
}
}

So marge the date and in your addapter ask what data is it. If its data1 then infalte view number one, if it's data2 then inflate view number2.
Then just populate the view with the data and you are done.

Related

How to prevent listArray from populating multiple times?

I have a spinner populated from an API call.
At first loading of fragment, the list is correctly populated, with differents items, one for row.
After a submit (I need a submit in this fragment) the List is re-populated several times.
This is the onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
mItemSubscriptionList = new ArrayList<>();
super.onCreate(savedInstanceState);
}
And this is the method that populate the array list
private void loadItemSubscription() {
ApiMapper mapper = new ApiMapper();
mapper.getBalance(new ApiMapper.VolleyCallback<JSONArray>() {
#Override
public void onSuccess(JSONArray balance) {
if (balance != null) {
Log.d(LOGTAG , balance.toString());
mItemSubscriptionList.clear();
for (int i = 0; i < balance.length(); i++) {
Log.d(LOGTAG , "Popolo lo spinner "+i);
try {
JSONObject obj = balance.getJSONObject(i);
String quantity = obj.getString("balance");
quantity = quantity.replace(".00","");
int id_item = obj.getInt("id_item");
String item = obj.getString("item");
item = item + ' '+'('+quantity+')';
Log.d(LOGTAG , quantity);
Log.d(LOGTAG , item);
ModelItemSubscription modelItemSubscription = new ModelItemSubscription();
modelItemSubscription.setMItemId(id_item);
modelItemSubscription.setMItemName(item);
modelItemSubscription.setMItemQuantity(quantity);
mItemSubscriptionList.add(modelItemSubscription);
mBaseApp.setItemSubscription(modelItemSubscription);
mLoadingDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
mItemSubscriptionList = mBaseApp.getItemSubscription();
if ( mItemSubscriptionList!=null ) {
renderSpinnerItemSubscription(mItemSubscriptionList);
}
}
}, mToken, mIdMemberCard, mIdCampaign);
}
In real scenario, I have 4 items to populate. The Log "Popolo lo spinner" is printed exactly 4 times, but this is the ugly finaly result.
Instead this is the right behaviour after the first loading (only 1 item for type)
Fyi this is the array that populates:
[{"balance":"0.00","item":"Lampada","id_item":"540"},{"balance":"0.00","item":"Taglio","id_item":"541"},{"balance":"1.00","item":"Piega","id_item":"542"},{"balance":"11.00","item":"Gelati","id_item":"543"}]
Thank you very much
The problem with your code is the list is getting populated every time the API call is made. Means if the call is made 4 times then your list would be populated 4 times with the same data.
mItemSubscriptionList.add(modelItemSubscription); will not override but it will add the items no matter it the items are already present in the list.
Now what I suggest is you should clear your list before you make a call to API. Just add mItemSubscriptionList.clear() after ApiMapper mapper = new ApiMapper();
I can't see where you are populating your Spinner adapter so I will describe how it should be done with no code.
First everytime you fetch your data from you API you should clear your main ArrayList which holds the data and update the Spinner's adapter:
adapter.notifySetDataChanged(); // Depending on the adapter
After that populate your ArrayList with the new fetched data and call
adapter.notifySetDataChanged();
again so your data get refreshed.
Try this and tell if it works. If not, please add more code so we can see how you are populating your adapter after fetching the data.

Error in showing data in custom listview from SQL database [duplicate]

This question already has answers here:
Android column '_id' does not exist?
(8 answers)
Closed 5 years ago.
I want to get data from database and show this data into a custom listview. I have made a custom list view with two textviews and I have an id autoincremented and name and a value in a database.
I want to display that name and the value in the custom listview textview. I am new in Android.
public class List_View_Data extends AppCompatActivity {
database db;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list__view__data);
db=new database(this);
show_data_sql();
}
private void show_data_sql(){
listView= (ListView) findViewById(R.id.activity_list__view__data);
ArrayList<String> thelist=new ArrayList<>();
Cursor data=db.show_data();
if(data.getCount()==0){
Toast.makeText(this,"Data Not Found",Toast.LENGTH_LONG).show();}
else{
while (data.moveToNext()){
thelist.add(data.getString(1));
thelist.add(data.getString(2));
}
//BaseAdapter is a very generic adapter that allows you to do pretty much whatever you want.
//using baseadapter which have listadapter and spinneradapter
Adapter listAdapter=new Adapter(this,data);
{
listView.setAdapter(listAdapter);
}
}
}
}
https://i.stack.imgur.com/b7bDS.png
Please can you link the trace for the error ?
I think you have issue with your index :
thelist.add(data.getString(1));
The index start at 0
Second, are you sure it's a String you get ?

Update a listview item row but on scroll the modifications don't remain

I have a ListView in an Android Activity and a custom adapter for that listview.
I want to be able to edit a row item and update that row instantly. This works, the modifications of the row is seen But, on scroll i loose all data.
This is my Asynk task from where i get the data and update the list row item:
/**
*
*/
public class EditNewsFeedPostAsyncTask extends AsyncTask<Void, Void, Boolean> {
public Activity context;
public String content;
public int rowPosition;
public ListView listView;
public TextView decriptionTxt;
#Override
protected Boolean doInBackground(Void... params) {
try {
token = Utils.getToken(context);
if (token != null) {
....
// {"status":"true"}
if (result != null) {
....
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
if (success) {
updateListView(rowPosition, content);
}
}
public boolean updateListView(int position, String content) {
int first = listView.getFirstVisiblePosition();
int last = listView.getLastVisiblePosition();
if (position < first || position > last) {
return false;
} else {
View convertView = listView.getChildAt(position - first);
decriptionTxt.setText(content);
listView.invalidateViews();
return true;
}
}
private void updateView(int index, TextView decriptionTxt) {
View v = listView.getChildAt(index - listView.getFirstVisiblePosition());
if (v == null)
return;
decriptionTxt.setText(content);
listView.invalidateViews();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onCancelled() {
}
}
What am i missing? shouldn't the data be persistent?
Thx
You must update the object in your listView adapter, not only the views!
after scrolling, the getView method inside your list's adapter will call and you will return the default view for that.
if you want to change that item permanent, you should update your data set and call notifyDataSetChanged on your adapter.
Make sure you're updating the data, not just the view.
When you modify the row, are you changing the underlying data or just the view? If just the view...
You're probably running into ListView recycling issues. This answer has a great explanation. Basically, ListViews are about efficiency in displaying views based on data, but are not good for holding new data on screen. Every time a ListView item is scrolled out of view, its View is recycled to be used for the item that just scrolled into view. Therefore, if you put "hi" in an EditText and then scroll it off screen, you can say goodbye to that string.
I solved this in my app by ditching ListView altogether and using an array of LinearLayouts (probably a clunky approach, but I had a known list size and it works great now). If you want to continue using a ListView, you'll have to approach it from a "data first" perspective. Like I said, ListViews are great at showing info from underlying data. If you put "hi" in an EditText and simultaneously put that string in the underlying data, it would be there regardless of any scrolling you do. Updating onTextChanged might be cumbersome, so you could also let each row open a dialog in which the user enters their data which then updates the underlying dataset when the dialog closes.
These are just some ideas, based on some assumptions, but editing views in a ListView is, in general, not very in line with how ListViews work.

ListView update after complete AsyncTask [duplicate]

This question already has answers here:
Android Updating ListView
(2 answers)
Closed 7 months ago.
I want to update TextView's text using AsyncTask.
I have list view in that there is Two TextView and one is ImageView
When user press ImageView button the Song will be played from server side. So i have put code in AsyncTask task
This is an custom Adapter from that i am calling ImageView's on Click event below is my code sample like this
public View getView(final int position, View convertView,
ViewGroup parent) {
holder.imgPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
and onclick event i am passing textview in asynctask, that i want to change after getting data from internet so below is my code
new MetadataTask2().execute(holder.txtMetadata);
now AsyncTask's Code is below
class MetadataTask2 extends AsyncTask<TextView, Void, IcyStreamMeta> {
TextView txtView;
#Override
protected IcyStreamMeta doInBackground(
TextView... arg0) {
//SOME OPERATION
txtView = arg0[0];
return streamMeta;
}
#Override
protected void onPostExecute(IcyStreamMeta result) {
txtView.setText("Hiiiiiiii");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = ProgressDialog.show(CompaniesList.this, "Tuning...",
"Please Wait...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now here u can see that with textView.setText("Hiii") the text will be updated but it will not reflect in Listview for that i have to update ListView or Adapter but do not know how to do that so i can see text on listview can any body help me
i have used below code for updating listview but still does nothing
adapter.notifyDataSetChanged();
mainListView.setAdapter(adapter);
mainListView.invalidate();
Have your adapter be a member variable of your activity class. Then you will be able to reference it from onPostExecute.
Also, from your code it's not clear to me if your TextView is actuallly the one that you intend to modify (the one that you inflated presumably) just in case, remember that you have to call setContentView in the main thread before doInBackground attempts to modify any component. Make sure that this Textview variable (arg0[0]??) is the one that you are inflating

after refreshing listview it shows first position data

I have a long ListView that the user can scroll around. I am refreshing this listview after every 30 seconds, listview refresh succesfully. But there is one issue that I want the list to be scrolled to the same point that it was previously before refreshing. Because now if list refresh then it shows the first position.
I am updating list through AsynchronousTask as:
private class HttpTask extends AsyncTask<String, Boolean, String> {
#Override
protected String doInBackground(String... params) {
System.out.println("inside doInBackground>>!!>>> ");
getResponse();
return "Executed";
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
// publishProgress(false);
System.out.println("post excute funt***********");
setListAdapter(new ListAdapter(getApplicationContext(),
R.layout.mylist, dataArr));
}
}
Any help will be appreciated.Thanks in advance
try to use setSelectionFromTop() to set the position to the previously visible state.
You would just have to do this :
listView.setSelection(position) // position is the item on the listView
I think when your listview is going to be refreshed the get the position of item which is first visible at that time then refresh your listview and set the position which you got before refreshing
int firstPosition = mEventListView.getFirstVisiblePosition();
EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
mEventListView.setAdapter(eventLogAdapter);
mEventListView.setSelection(firstPosition);
Instead of set a new ListAdapter, do listAdapter.notifyDataSetChanged() this will refresh the contents of view instead of create new ones and the listview will not scroll up
What you are doing is you are assigning adapter to your list view when you call refresh
setListAdapter(new ListAdapter(getApplicationContext(),
R.layout.mylist, dataArr));
Which is wrong
You have to refresh your adapter
dataArr.notifyDataSetChanged();
Hope this will work

Categories

Resources