This question already has an answer here:
Android System services not available to Activities before onCreate() [closed]
(1 answer)
Closed 10 years ago.
How could I add items from listView(on my layout) from array?
I tried multiple times, but everytime I get error: System services not avaliable before onCreate.();. Yes, I. know that this er.ror is shown when I try to access ArrayAdapter. Tried almost everything. .Full code is here: pastebin.com/Nv5BkcS7
UPDATE
I followed some other tutorials. My code works now, but there is no data. http://pastebin.com/D8UFKC7i and xml http://pastebin.com/mJfwjGcB
Could someone tell me why it doesn't work.? Debugger says that arrays have all entires
Your onCreate() method is blank in the addcontacts activity, thats the problem:
public class addcontacts extends ListActivity {
protected void onCreate() {
//set content here
setContentView(R.layout.activity_add_contact);
}
...
...
And Don't forget to create activity_add_contact.xml in Layout folder
with content :
<?xml version="1.0" encoding="utf-8"?>
<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="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
1.create a custom Adapter exteding BaseAdpter or ArrayAdpter and pass array or ArrayList in constructor.
2.Create the View in layout (of row )
3.inflate this xml in getview function of custom Adapter and set the data.
Activity XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lstText"
/>
</LinearLayout>
list row XML (in layout row.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="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txtAlertText" />
</LinearLayout>
</LinearLayout>
Create Adapter Class inside your activity
class JSONAdapter extends BaseAdapter implements ListAdapter {
private final Activity activity;
private final JSONArray jsonArray;
private JSONAdapter (Activity activity, JSONArray jsonArray) {
assert activity != null;
assert jsonArray != null;
this.jsonArray = jsonArray;
this.activity = activity;
}
#Override public int getCount() {
if(null==jsonArray)
return 0;
else
return jsonArray.length();
}
#Override public JSONObject getItem(int position) {
if(null==jsonArray) return null;
else
return jsonArray.optJSONObject(position);
}
#Override public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
#Override public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = activity.getLayoutInflater().inflate(R.layout.row, null);
TextView text =(TextView)convertView.findViewById(R.id.txtAlertText);
JSONObject json_data = getItem(position);
if(null!=json_data ){
String jj=json_data.getString("f_name");
text.setText(jj);
}
return convertView;
}
}
Then add this in your activity.
public class main extends Activity {
/** Called when the activity is first created. */
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
JSONAdapter jSONAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
jSONAdapter = new JSONAdapter (main.this,jArray);//jArray is your json array
//Set the above adapter as the adapter of choice for our list
lstTest.setAdapter(jSONAdapter );
}
And you are done.
Related
I am getting an error when trying to set my view to display the ListView for the file I want to display(text file). I am pretty sure it has something to do with the XML. I just want to display the information from this.file = fileop.ReadFileAsList("Installed_packages.txt");. My code:
public class Main extends Activity {
private TextView tv;
private FileOperations fileop;
private String[] file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.fileop = new FileOperations();
this.file = fileop.ReadFileAsList("Installed_packages.txt");
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
ListView lv = new ListView(this);
lv.setTextFilterEnabled(true);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
lv.setOnItemClickListener(new AdapterView.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();
}
});
setContentView(lv);
}
}
list_item.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="fill_parent"
android:orientation="vertical"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000">
</LinearLayout>
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5sp"
android:id="#+id/TextView01"
android:text="#string/hello"/>
</ScrollView>
</LinearLayout>
The ArrayAdapter requires the resource ID to be a TextView XML exception means you don't supply what the ArrayAdapter expects. When you use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)
R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
// other attributes of the TextView
/>
If you want your list row layout to be something a little different then a simple TextView widget use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file,
R.id.the_id_of_a_textview_from_the_layout, this.file)
where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.
Soution is here
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
</LinearLayout>
Java code :
String[] countryArray = {"India", "Pakistan", "USA", "UK"};
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.textview, countryArray);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
If you are getting that message when you are extending an ArrayAdapter, you are getting that error because you have not provided the correct resource id to display the item. Call the super class in the constructor and pass in the resource id of the TextView:
//Pass in the resource id: R.id.text_view
SpinnerAdapter spinnerAddToListAdapter = new SpinnerAdapter(MyActivity.this,
R.id.text_view,
new ArrayList<>());
Adapter:
public class SpinnerAdapter extends ArrayAdapter<MyEntity> {
private Context context;
private List<MyEntity> values;
public SpinnerAdapter(Context context, int textViewResourceId,
List<MyEntity> values) {
//Pass in the resource id: R.id.text_view
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
The problem is in the line:
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
Because when i change it to:
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.file));
It works!
I've investigated several SO answers on this question (here, here, and here) and none of the proposed solutions have worked. My problem is that my RecyclerView list items aren't being displayed. I've set breakpoints in MessengerRecyclerAdapter, onCreateViewHolder, onBindViewHolder, and getItemCount and only the first one is ever called. While in a breakpoint I've entered the expression evaluator and executed
MessengerRecyclerAdapter.getItemCount();
And received the expected answer of 20. The RecyclerView itself takes up the intended content area as demonstrated by the screenshot below (I turned the RecyclerView magenta to highlight the space it occupies).
My RecyclerView XML code is below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/thread_list"
android:background="#color/colorAccent"
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:name="com.jypsee.jypseeconnect.orgPicker.MessengerListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"
tools:context="com.jypsee.jypseeconnect.orgPicker.MessengerListFragment"
tools:listitem="#layout/fragment_messenger_cell"/>
</LinearLayout>
My RecyclerView Cell XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="#color/blueText"/>
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="#color/darkText"/>
</LinearLayout>
My ListFragment class:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
List<DummyContent.DummyItem> items = new ArrayList<>();
for (Integer i = 0; i<20; i++){
DummyContent.DummyItem item = new DummyContent.DummyItem(i.toString(),"Content","Details");
items.add(item);
}
View view = inflater.inflate(R.layout.fragment_messenger_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.thread_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerAdapter = new MessengerThreadRecyclerAdapter(items, mListener);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerAdapter.notifyDataSetChanged();
return view;
}
My Adapter class:
public class MessengerRecyclerAdapter
extends RecyclerView.Adapter<MessengerRecyclerAdapter.MessageThreadHolder>{
private final List<DummyItem> mValues;
private final RecyclerViewClickListener mListener;
public MessengerRecyclerAdapter(List<DummyItem> items, RecyclerViewClickListener listener) {
mValues = items;
mListener = listener;
}
#Override
public MessageThreadHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_messenger_cell, parent, false);
return new MessageThreadHolder(view);
}
#Override
public void onBindViewHolder(final MessageThreadHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.recyclerViewListClicked(v, position);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class MessageThreadHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyItem mItem;
public MessageThreadHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
}
}
As you can see I've set the linearLayout orientation to vertical and set the layout manager, which were the 2 most common solutions. I'm really at a loss as to what to try next, so any help is appreciated.
As I said in previous Answer edit. The issues was in your xml. The main reason it was not showing was because, You were trying to add the fragment using include tag instead of fragment tag thus respective fragment class was never getting called on the fragment layout being added to your activity.
Below is the code you needed to add the Fragment correctly.
<fragment
android:id="#+id/message_thread"
android:name="com.jypsee.jypseeconnect.orgPicker.MessengerThreadListFragment"
layout="#layout/fragment_messengerthread_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_messengerthread_list" />
And your fragment layout should be like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".orgPicker.MessengerThreadListFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/thread_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here is the screenshot of working
In my case , I was missing calling notifyDataSetChanged() after setting list in adapter.
I have the result of a sql query expressed in this way :
//The column attributes of a result table
ArrayList<String> columns_attributes;
// This contains the data of every row of the result
ArrayList<ArrayList<String>> rows_data;
How can i dinamically display it on an activity ? Thanks
MainActivity
public class MainActivity extends AppCompatActivity {
List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("Android");
list.add("iPhone");
list.add("Windows");
list.add("Blackberry");
list.add("Mac");
list.add("Laptop");
list.add("LCD");
list.add("Dell");
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_view_item, list);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Clicked: " + list.get(position), Toast.LENGTH_SHORT).show();
}
});
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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_width="match_parent"
android:layout_height="match_parent"
tools:context="com.vzw.www.listviewalert.MainActivity">
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
list_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
You can iterate over these list with simple for loops like this:
// for columns
for (String colAttr : columns_attributes) {
// do something with the string value
}
// for rows
for (List<String> row : rows_data) {
for (String rowAttr : row) {
// do something with the string value
}
}
To display a dynamic amount of data, a ListView is recommended to do the job. If you just want to display those strings, you can use a ListActivity and assign a ArrayAdapter to that ListView with the setListAdapter() method.
You may want to check this tutorial to get this done.
http://androidexample.com/Create_Listview_With_ListActivity_-_Android_Example/index.php?view=article_discription&aid=66
How do I create a working ListView in Android?
I am not looking for you to just fix my code, but am looking for a simple working example of a ListView in Android so I can understand the process of creating one and working with it. But I have included my code so you can see where I am coming from and what I have been trying.
I have done the following and had no success:
--
Made a xml layout with only a TextView item in it:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/dir_text_view"
/>
Created the following class as per the instructions at the following tutorial:
http://www.vogella.com/tutorials/AndroidListView/article.html
public class DataTempleArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public DataTempleArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
And in the main activity I have a snippet of code where I attempt to add a list of strings to the ArrayList associated with the DataTempleArrayAdapter here:
int i;
for (i=0;i<dirContents.length;i++) {
dirList.add(dirContents[i]);
//Toast.makeText(this, dirList.get(i), Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
dirList is successfully populated, while the adapter doesn't update the ListView at all.
--
Before you ask for it, here I am including the rest of the relevant code:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="org.hacktivity.datatemple.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/directory"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/dirEditText" />
<Button
android:text="→"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/dirButton"
android:onClick="populateDirList" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/dirListView" />
</LinearLayout>
</RelativeLayout>
And alas the MainActivity class:
public class MainActivity extends AppCompatActivity {
ListView dirListView;
EditText et;
DataTempleArrayAdapter adapter;
ArrayList<String> dirList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dirListView = (ListView) findViewById(R.id.dirListView);
et = (EditText) findViewById(R.id.dirEditText);
dirList = new ArrayList<String>();
dirListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
populateDirList(view);
}
});
ArrayList<String> dirList = new ArrayList<String>();
adapter = new DataTempleArrayAdapter(this,
R.id.dir_text_view, dirList);
dirListView.setAdapter(adapter);
}
public void populateDirList (View view) {
File f;
// NO INPUT.
if (et.getText().toString().equals("")) {
Toast.makeText(this, "empty string", Toast.LENGTH_SHORT).show();
return;
}
f = new File(et.getText().toString());
if (f == null) { return; }
String dirContents[] = f.list();
if (dirContents == null) { return; }
dirList = new ArrayList<String>(Arrays.asList(f.list()));
adapter.clear();
int i;
for (i=0;i<dirContents.length;i++) {
dirList.add(dirContents[i]);
//Toast.makeText(this, dirList.get(i), Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
}
}
One of the best resources for understanding ListView is indeed the
one you mentioned from Vogella
Another cool resource to understand how the the
notifyDataSetChanged() method works in ListView this post from StackOverflow
For a short, simple explanation of how to use CustomLayouts in
ListView (without the ViewHolder pattern) check another of the best
references available: Mkyong
Discussing the benefits of the ViewHolder pattern in ListView:
check this StackOverflow post
Concise example and explanation of the ViewHolder pattern in
ListView: check this example from JavaCodeGeeks
And to fix your code I think the answer given before is only part of the problem:
You must indeed comment the line
//ArrayList<String> dirList = new ArrayList<String>();
because, like #F43nd1r mentioned this would also be a different instance of a list passed into the adapter
but there is more, when you do this:
dirList = new ArrayList<String>(Arrays.asList(f.list()));
you are instantiating a new, different, list, the old reference held by the adapter will NOT be changed... it will still hold the OLD object list
you should perhaps substitute it for something like:
dirList.clear();
dirList.addAll(Arrays.asList(f.list()));
Hope this helps!
Excerpt from your code:
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
dirList = new ArrayList<String>();
//...
ArrayList<String> dirList = new ArrayList<String>();
adapter = new DataTempleArrayAdapter(this,
R.id.dir_text_view, dirList);
//...
}
I bet you already see what the problem is, but in case you don't: You have a field and a local variable with the same name. You pass the local variable to the adapter. It is only naturally that the adapter does not react to changes on the field, as it has no knowledge of its existence.
I think what you have done wrong is to supply a UI Component to the Array Adapter with:
adapter = new DataTempleArrayAdapter(this, R.id.dir_text_view, dirList);
The second item should not be an ID, but a layout file. Android have already implemented a List item layout with a textview that you can use: android.R.layout.simple_list_item_1.
so replace your row with
adapter = new DataTempleArrayAdapter(this, android.R.layout.simple_list_item_1, dirList);
and you are one step closer.
(This way you don't need your "xml layout with only a TextView item in it")
I just started learning Android and I am trying to create a simple view where a portion of the main XML is a listview.
Here is my main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="#+id/Menu">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/menu_item_1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="129dp" />
</RelativeLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_toEndOf="#+id/Menu"
android:layout_toRightOf="#+id/Menu"
android:layout_alignParentTop="true"
android:id="#+id/Banner">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Account Log"
android:layout_gravity="center"
android:inputType="none"
android:textStyle="bold"/>
</FrameLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Log"
android:layout_toRightOf="#+id/Menu"
android:layout_below="#+id/Banner"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:choiceMode="none"
android:clickable="false"
android:contextClickable="true"
android:fadeScrollbars="true" />
</RelativeLayout>
Assuming that I have a function called getDatafromFile() which returns an ArrayList of data, how do I put those data into my listView?
I've heard of using ArrayAdapter but the examples I've seen puts ListView to the entire layout.
The best way to put data in your ListView is by making an ArrayAdapter Class. I always recommend you to try using a custom adapter class so that you can change it as per your requirement. You can create a class that extends ArrayAdapter. Then pass the arraylist that you want inside your list view to that adapter constructor.
For Example, below is a custom adapter class
public class CustomAdapter extends ArrayAdapter<DataInfo> {
ArrayList<DataInfo> itemList =new ArrayList<>();
Context context;
LayoutInflater inflater;
public CustomAdapte(Context context, ArrayList<VegInfo> list) {
super(context, R.layout.list_item, list);
this.context = context;
itemList = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting an item from the list
DataInfo item = itemList.get(position);
if(convertView==null)
convertView = inflater.inflate(R.layout.list_item,parent,false);
//displaying some data from your data info in a textview
TextView textView = (TextView) convertView.findViewById(R.id.tv);
textView.setText(item.subitem);
return convertView;
}
}
Inside your Activity, You can set the data to that adapter.
CustomAdapter yourAdapter = new CustomAdapte(activity,yourArrayList);
yourListView.setAdapter(yourAdapter);
Now, your list view have the data inside the array list. Whenever there is a change in the array list, it can be reflected in the list view just by calling
yourAdapter.notifydatasetchanged();
Here list_item is a custom XML file that you should create for a single list item view.
Hope this helps you. If not please tell me and let me make it more clear. happy coding.
Full code of create list view
public class MainActivity extends AppCompatActivity {
ArrayList<String>arrayList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //here is the layout where your views exists
for (int i=0;i<=20;i++){
arrayList.add("List Items"+i); //assume we passed the data in arraylist
}
ListView listView=(ListView)findViewById(R.id.log); //your listview
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);//the second argument is a layout file that have a textview
listView.setAdapter(arrayAdapter);
}
}