Append array to already data bound ListView - android

Currently, I have a
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView android:id="#+id/listview1"></ListView>
<ListView android:id="#+id/listview2"></ListView>
</LinearLayout>
and on 2 of my button clicks events I publish data to the corresponding ListViews:
Button1 click:
List result = GetSomeDate();
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, result);
listview1.setAdapter(customAdapter);
Button2 click:
List result = GetSomeOtherDate();
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, result);
listview2.setAdapter(customAdapter);
I wonder, can I leave only one ListView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView android:id="#+id/universalListView"></ListView>
</LinearLayout>
and append List to it on my events, if the List type is the same?
The only rule is, that List from Button1 click should be always on top, no matter, if Button1 is clicked before or after Button2.
Thanks in advance!

create a method like that in your custom adapter : HERE data is your list in adapter.
public void addAll(List<mtItems> items)
{
if(item!=null && item.size()>0){
data.addAll(items);
notifyDataSetChanged()
}
}
call this method of adapter whenever you want to add some items in your already populated list. like
customAdapter.addAll(myItems);
thats all .

Related

How to create dialog box by clicking on specific ListView items?

I have a listview that has items added to it through other activities. My goal here is to make it where, when a specific listview item is clicked, it launches a dialog box specific to the item clicked.
Here's the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<ListView
android:id="#+id/inventoryListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:headerDividersEnabled="true"
android:onClick="f">
</ListView>
</LinearLayout>
</LinearLayout>]
And here is the activity with the adapter
public class inventory extends AppCompatActivity {
public static ArrayList<String> items;
public static ArrayAdapter<String> adapter;
public static ListView inventoryListView;
SharedPreferences sharedPreferences;
protected void onCreate(Bundle savedInstanceSate){
super.onCreate(savedInstanceSate);
setContentView(R.layout.inventory);
inventoryListView = (ListView)findViewById(R.id.inventoryListView);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,R.layout.inventory_list_view,items);
inventoryListView.setAdapter(adapter);
sharedPreferences = getSharedPreferences("my_prefs", 0);
updateInventory();
adapter.notifyDataSetChanged();
}
The list is not populated because it can only be populated through other activities, and not the one that holds the listview.
Use viewholder pattern
Example
And in your getView method you can set onclicklistener to your view and launch your dialog for each row.
First of all, you can use RecyclerView instead of Listview, it's more efficient in memory managing and performance.
as #ghost said, you can use ViewHolder Pattern and Push Your activity context to your view-holder and Adapter. You can simply put your clicking logic in your viewHolder (Inside of the Adapter).

Setting an Adapter to the ListView Android Studio

I'm trying to add some items in a ListView. When I swith the Layout (startActivity), I call the class Listing.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listing);
ListView lv = (ListView) findViewById(R.id.listViewLIST);
String[] items = {"Item1", "Item2", "Item3", "Item4"};
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(items));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.activity_listing, R.id.listViewLIST, arrayList);
lv.setAdapter(adapter);
}
I read some tutorials an followed every step but the app stops working always in the last line of code
lv.setAdapter(adapter);
What am I missing?
Edit 27.12.2015
The activity_listing.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context="cigarkings.cigarking.Listing">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewLIST"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="51dp" />
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView" />
<include layout="#layout/content_listing" />
</android.support.design.widget.CoordinatorLayout>
Assuming missing statement android:layout_width="match_parent" for your Coordinator Layout as a typographical error,the major error is in setting up array adapter.
In the statement : ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.activity_listing, R.id.listViewLIST, arrayList); the constructor parameters (2nd parameter:R.layout.activity_listing and 3rd parameter:R.id.listViewLIST) are incorrect.Array Adapter takes resource id of a textview as 3rd argument and not of a listview, and the layout resource id of the layout containing the textview is passed as 2nd argument.
So, one solution for this is to create a separate xml layout containing a textview and passing the layout resource id as 2nd argument and textview id as 3rd argument to the constructor of Array Adapter
First of all activity listing should not be in this pattern.
If you are at beginning stage then First try this Tutorial...
The best explanation ever for beginners.
Then you have to implement custom listView using BaseAdaptor class and custom XML.

Android ListView shows empty content

I have a fragment with a listview. The adapter only has one field: the item id.
When I add an item to the list using the adapter, the list shows the item id.
But if I put a simple item id check before (a for-cycle that checks if the item id is equals to one specific id, if so then adds the item id), the list shows an empty row (like it added something) but without showing the item id.
What could be? I'm sure that the "check part" works.
EDIT: I forgot to specify that the item id is a String.
EDIT 2: I added the check part of the code. It loops through list that contains the item ids that I want to add to the other fragment list. item is the item that I'm checking. blueF is the fragment.
for(int i=0; i<list.getCount();i++) {
if(list.getItem(i).equals(item.getId())) {
//send the item to the listview of the fragment
blueF.getArrayAdapter().addItem(item);
break;
}
}
EDIT 3: After some testing, I discovered that the listview inside the fragment have inside the item (I used getCount and also printed the item id), but it isn't showing the item id! My custom adapter have a notifyDataSetChanged() in the "add" method and I've also recalled the notifyDataSetChanged after the call to the add method in the activity...but nothing.
EDIT 4: Probably is some problem with the layout?
I have this layout for the list row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/inventory_item_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/inventory_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.4"
android:textSize="17sp"
android:typeface="monospace" >
</TextView>
<TextView
android:id="#+id/inventory_item_counter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="17sp"
android:typeface="monospace" />
</LinearLayout>
the fragment layout with the listview:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/listBlueTagView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Your filter code should be done before setting the Data of the Adapter, so the Adapter have only the items that it will show.
From your question, I understood this,
Try this in your main Activity, these are just Pseudo codes there may be some typos.
public class Main extends Activity{
EditText etID; //Your Item ID field.
ListView listView; // Listview in your XML.
int check_ID; // ID which you want to compare with Edit Texts' value.
List<String> arrayList= new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Your_Layout_XML);
etID = (EditText) findViewById(R.id.editTextID); //ITEM_ID editText id in XML
listView = (ListView) findViewById(R.id.your_ListView_ID);
check_ID = 1; // suppose you want to add into your list if user enters 1 in editText as Item ID
if(check_ID = Integer.parseInt(etID.getText().toString())) //get value from EditText then check it with your desired value and on being equal add item to list
// add item here and set it to listView
arrayList.add("Mango");
ArrayAdapter<String> array_Adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
arrayList);
listView .setAdapter(array_Adapter );
} else{
Toast.makeText(getApplicationContext(),"Wrong ITEM ID",Toast.LENGTH_SHORT).show();
}
}
I've resolved the problem.
It was a graphic problem generated in the getView of the adapter. Basically, some elements overwrote the color text of the ID, rendering it invisible.
I set the text color to Color.BLACK and now I can see the ID of the item.

ListView disappears when adding a view from CursorAdapter

My layout includes an unpopulated horizontal linear layout with a multicolumn listview below. The listview is populated from an sqlite table via a custom cursor adapter in a separate java file. each time a particular view in a listview row is tapped, a button is dynamically created and added to the linear layout. For reasons I don't understand, when this happens, the listview content disappears. If I change the orientation of the device, it goes through the onCreate and the display builds correctly with the linear layout buttons showing correctly over the listview.
The main layout file:
<?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="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/llRunnerList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<ListView
android:id="#+id/list_data"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
and the view listener code in the custom cursor adapter:
private OnClickListener strRunnerOnClickListener = new OnClickListener() {
#Override
//
// When the Runner field is clicked, add the Runner name to the Runner row.
//
public void onClick(View v) {
final DBAdapter databaseHelper = new DBAdapter(ctxThis);
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
TextView tvRunner = (TextView) v;
String strRunner = (String) tvRunner.getText();
if(RaceSheetActivity.blnRaceRunning) {
// get the ListView and the position in it.
ListView lv = (ListView) v.getParent().getParent();
final int position = lv.getPositionForView((View) v.getParent());
// get the cursor pointing to that row
Cursor c = (Cursor) lv.getItemAtPosition(position);
long lngCurrentId = c.getInt(0);
long lngRaceId = c.getInt(1);
c.close();
// Add to database if doesn't exist
Cursor cSNRec = databaseHelper.getSNRecByCompetitorId(lngCurrentId);
if(cSNRec.moveToFirst()) {
Toast.makeText(v.getContext(), strRunner + " already in preempt list!", Toast.LENGTH_SHORT).show();
}
else {
databaseHelper.insertSN(strRunner, lngCurrentId);
// Add a button and initialise it
ToggleButton btnRunner = new ToggleButton(ctxThis);
btnRunner.setText(strRunner);
btnRunner.setTextOn(strRunner);
btnRunner.setTextOff(strRunner);
btnRunner.setTag(lngCurrentId);
btnRunner.setLayoutParams(params);
btnRunner.setOnClickListener(RaceSheetActivity.btnRunnerOnClickListener);
RaceSheetActivity.llRunnerList.addView(btnRunner); // to delete view removeViewAt(int index)
changeCursor(databaseHelper.getRaceSheetDataForRace(lngRaceId));
notifyDataSetChanged();
}
}
}
};
Would really appreciate any ideas as to how I can keep the listview visible after tapping the runner field and the button appearing. I have tried notifyDatasetChanged without success, reread the database table into the cursor adapter.
Set your layout heights to wrap_content because your ItemList with the buttons will overlap your Listview if it's not empty.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/llItemList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/list_data"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
Actually you are not initializing the HorizontalScrll view And just close the Horizontalscrollview due to that App return this type of behaviour
Actually, solved the problem eventually. The listview was disappearing because I had used a cursor to get the adapter values for the row that was returned, and subsequently closing the cursor apparently cleared the listview.
Thanks to both those who offered solutions albeit they weren't the cause of the problem.

Display contents from ListView defined in regular Activity Android

I wanted to create a search view like the one Google uses. For this I created the following XML layout, which basically is a search bar and a button in the upper section of the screen and a ListView at the bottom of it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayoutSearch"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#FF394952">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<EditText android:layout_height="wrap_content" android:id="#+id/searchTextBar" android:layout_width="wrap_content" android:layout_weight="1">
<requestFocus></requestFocus>
</EditText>
<Button android:layout_height="fill_parent" android:layout_width="wrap_content" android:id="#+id/searchButton" android:text="Buscar"></Button>
</LinearLayout>
<ListView
android:id="#+id/searchResultList"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:layout_weight="1.0" />
</LinearLayout>
And this is the code of the textViewResource that the ArrayAdapter demands on its constructor:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
Now, this is the code of the activity. So far, I just want to display the view with the contents (that's why I'm using a static String array for now).
public class SearchActivity extends Activity{
static final String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item, COUNTRIES);
ListView lv = (ListView)this.findViewById(R.id.searchResultList);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
}
However, when I run the activity I see the search bar but it doesn't display the ListView.
I've tried changing the extension of SearchActivity to ListActivity, but the program just crashes when I try to start it. I'm also aware of the existence of the Search Interface, but I just want to see this particular method work.
Why it doesn't display the contents of the ListView? Is there a way to fix this?
Thanks in advance
If you are going to use ListActivity you should be aware that ListActivity already has a ListView instance. You need to call its setListAdapter method to set the adapter for its ListView instead of instantiating your own ListView and setting the adapter on it. You can call getListView to get a handle on ListActvity's ListView and then set the click listener on that.
If you want to extend ListActivity then you must have a ListView with id #android:id/list. Change the id of your ListView, that should fix the crash when extending ListActivity.

Categories

Resources