theList.add(data.getString(0));
theList.add(data.getString(1));
theList.add(data.getString(2));
theList.add(data.getString(3));
theList.add(data.getString(4));
I want to add all these indexes as a single row
I have Tried follwing code but it didn`t worked
theList.add(data.getString(0),data.getString(1),data.getString(2),data.getString(3),data.getString(4));
This is the Full Code of my Class. What i am trying to do is take data from my sqlite database and show in list view.
By this following code i am getting values in different rows but i want them in a single row
package com.example.project;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mitch on 2016-05-13.
*/
public class ViewListContents extends AppCompatActivity {
DBHelper myDB;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlistcontents_layout);
ListView listView = (ListView) findViewById(R.id.listView);
myDB = new DBHelper(this);
//populate an ArrayList<String> from the database and then view it
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.viewbuses();
if(data.getCount() == 0){
Toast.makeText(this, "There are no contents in this list!",Toast.LENGTH_LONG).show();
}else{
while(data.moveToNext()) {
theList.add(data.getString(0));
theList.add(data.getString(1));
theList.add(data.getString(2));
theList.add(data.getString(3));
theList.add(data.getString(4));
theList.add("");
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
Thanks in Advance
This is How I Resolved It
First of All Thanks to Mr. Zain He Helped me to get it done.
I Concatenated Strings and it worked.
I wanted to Give space Between Values so this is how I did it.
theList.add(data.getString(0)+" "+data.getString(1)+" "
+data.getString(2)+" " +data.getString(3)+" "+data.getString(4));
A Good Practice is to add .Concat() instead of "+"
Thank You!
I recommend using RecyclerView instead because it provides far more functionality than ListView. It also leads to better performance. You will have to extend RecyclerView.Adapter and RecyclerView.ViewHolder as shown below.
MyAdapter is similar to ArrayAdapter. It connects the RecyclerView to our data.
MyDataViewHolder stores all the views for a single item in the list. In our case that is a single TextView, but it could be more.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyDataViewHolder> {
private List<String> mList;
public MyAdapter(List<String> list){
this.mList = list;
}
protected static class MyDataViewHolder extends RecyclerView.ViewHolder{
protected TextView viewData;
public MyDataViewHolder(View itemView) {
super(itemView);
viewData = (TextView) itemView.findViewById(R.id.data);
}
}
}
You will also have to implement the following methods inside MyAdapter.
onCreateViewHolder creates a MyDataViewHolder from xml.
onBindViewHolder populates the MyDataViewHolder using our data.
returns the number of elements shown.
#Override
public MyDataViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.my_data, viewGroup, false);
return new MyDataViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyDataViewHolder viewHolder, int i) {
String string = mList.get(i);
viewHolder.viewData.setText(person.getLastName());
}
#Override
public int getItemCount() {
return mList.size();
}
Now use this inside your onCreate function.
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));
mAdapter = new MyAdapter(mList);
mRecyclerView.setAdapter(mAdapter);
Related
I am coming from a web development background (PHP). In my example, I retrieve a list of users, with their profile image, first and last name. Now I want each row of data (which represents a user), to open an activity to that clicked user profile.
On the web, it was simple by adding links with PHP. But how do I do that with Java and Android?
Right now, I managed to create a simple list that is fetched as a String array with simple text. But it's not clickable.
This is my current code: (I didn't include the XML files code, I don't think it's relevant)
**For test purpose, you see I use an array of Strings with 15 rows of data, and each String is acting as "first name" and "last name" - again, just for testings.
I want to know how to make those lines of data clickable and send to a new activity with the user's details. (If I can "mimic" data that will be sent to that new activity that would be great!)
MainActivity.java:
package com.example.recycleview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
String[] myDataset = new String[16];
myDataset[0] = "Data0";
myDataset[1] = "Data1";
myDataset[2] = "Data2";
myDataset[3] = "Data3";
myDataset[4] = "Data4";
myDataset[5] = "Data5";
myDataset[6] = "Data6";
myDataset[7] = "Data7";
myDataset[8] = "Data8";
myDataset[9] = "Data9";
myDataset[10] = "Data10";
myDataset[11] = "Data11";
myDataset[12] = "Data12";
myDataset[13] = "Data13";
myDataset[14] = "Data14";
myDataset[15] = "Data15";
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
}
MyAdapter.java:
package com.example.recycleviewe;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView upTv;
public TextView downTv;
public View layout;
public MyViewHolder(View v) {
super(v);
layout = v;
upTv = (TextView)v.findViewById(R.id.upTv);
downTv = (TextView)v.findViewById(R.id.downTv);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.upTv.setText(mDataset[position]);
holder.downTv.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
}
Android has this concept of intent. It is used to start activities as well as passing messages between components.
In your onBindViewHolder add:
holder.layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Main2Activity.class);
intent.putExtra("fname", mDataset[position]);
intent.putExtra("lname", mDataset[position]);
v.getContext().startActivity(intent);
}
});
cheers!
How to infinite scroll load more with Recycleview
how can i display result like infinite means when user scroll dynamic data automatically fetch and show. so loading time consume and application will work fine.
File Name: MainActivity.java //Main Java file that i want to show load more
package com.ejobbox.ejobbox;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ProgressBar progressBar;
private LinearLayoutManager mLayoutManager;
private RecyclerViewAdapter adapter;
private ArrayList<Model> list;
private String baseURL="http://mywebsite.com/";
public static List<WPPost> mListPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= findViewById(R.id.recycler_view);
progressBar=findViewById(R.id.progressbar);
mLayoutManager=new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(mLayoutManager);
list=new ArrayList<Model>();
// call retrofit
getRetrofit();
adapter=new RecyclerViewAdapter(list,MainActivity.this);
recyclerView.setAdapter(adapter);
}
private void getRetrofit(){
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
Call<List<WPPost>> call= service.getPostInfo();
call.enqueue(new Callback<List<WPPost>>() {
#Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.e("mainactivty","response"+ response.body());
progressBar.setVisibility(View.GONE);
for(int i=0; i<response.body().size();i++){
Log.e ("main","Title"+ response.body().get(i).getTitle().getRendered()+" "+
response.body().get(i).getId());
String tempdetails=response.body().get(i).getExcerpt().getRendered().toString();
tempdetails=tempdetails.replace("<p>","");
tempdetails=tempdetails.replace("</p>","");
String linkdetail=response.body().get(i).getLink().toString();
String date=response.body().get(i).getDate().toString();
list.add(new Model(Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
tempdetails,date,
response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref(),linkdetail) );
}
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
}
});
}
}
(This is RecyclearViewAdapter that i have define recyclear view Adapter.)
File Name: RecyclearViewAdapter.java //Recyclear View Adapter File
package com.ejobbox.ejobbox;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter{
private ArrayList<Model> dataset;
private Context mContext;
public RecyclerViewAdapter(ArrayList<Model> mlist, Context context) {
this.dataset=mlist;
this.mContext=context;
}
public static class ImageTypeViewHolder extends RecyclerView.ViewHolder{
TextView title,subtitle,link,date;
ImageView imageView;
public ImageTypeViewHolder(View itemView){
super(itemView);
this.title=(TextView)itemView.findViewById(R.id.title);
this.link=(TextView)itemView.findViewById(R.id.link);
this.subtitle=(TextView) itemView.findViewById(R.id.subtitle);
this.imageView=(ImageView) itemView.findViewById(R.id.icon);
this.date=(TextView)itemView.findViewById(R.id.date);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.postdetails,parent,false);
return new ImageTypeViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Model object=dataset.get(position);
((ImageTypeViewHolder) holder).title.setText(object.title);
((ImageTypeViewHolder) holder).subtitle.setText(object.subtitle);
//((ImageTypeViewHolder) holder).link.setText(object.link);
((ImageTypeViewHolder) holder).date.setText((CharSequence) object.date);
((ImageTypeViewHolder) holder).title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(mContext, WPPostDetails.class);
intent.putExtra("itemPosition",position);
intent.putExtra("link",object.link.toString());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() { return dataset.size();}
}
Do not use infinite scroll it does not work as expected.
You can use this
recyclerView.addOnScrollListener(new OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (isLastItemDisplaying())
{
scrollCount=scrollCount+10;
L.v("scroll count",""+recyclerView.getAdapter().getItemCount());
loadMoreItems(scrollCount);
}
}
});
private boolean isLastItemDisplaying()
{
if (storiesList.getAdapter().getItemCount()!=0) {
int last_visible_count=manager.findFirstCompletelyVisibleItemPosition();
if (last_visible_count!=RecyclerView.NO_POSITION && last_visible_count==storiesList.getAdapter().getItemCount()-1) {
return true;
}
}
return false;
}
Inside this loadMoreItems method call your api. Make sure to send this scroll count to your server on each api call .And in sql query you have to do this
EX:
For example on first time your count is 0;
SELECT * FROM posts LIMIT 0,10
On Scroll your scrollCount value will get increased by 10 (you can use your value scroll count values will fetch next 10 rows)
SELECT * FROM posts LIMIT 10,10
You only have to add your new data to the last position of list movies and everything will work fine. For this-
Create a new List of List<Model> newList and add your updated data to it. Now add newList into list and notify to adapter. Just like below-
List<Model> newList = new ArrayList<>();
// your code..
recyclerView.addOnScrollListener(new EndlessScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
loadingMore=true;
getRetrofit();
int currentSize = adapter.getItemCount();
list.addAll(newList);
adapter.notifyItemRangeInserted(currentSize, list.size() - 2);
}
});
And here you can find the EndlessScrollListener class.
please look at my other related answers to more details-
How to load more items in a ListView using AsyncTask or any other method
Continious scrolling in recyclerview by Json request and adding new item with previous
Hope it will help.
Here is example for Simple Implementation of Endless Scrolling RecyclerView using a Simple Library compiled from the various sources.
Add this line in build.gradle
implementation 'com.hereshem.lib:awesomelib:2.0.1'
Create RecyclerView Layout in Activity with
<com.hereshem.lib.recycler.MyRecyclerView
android:id="#+id/recycler"
app:layoutManager="LinearLayoutManager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Create a ViewHolder by passing the class that supports
public static class EVHolder extends MyViewHolder<Events> {
TextView date, title, summary;
public EVHolder(View v) {
super(v);
date = v.findViewById(R.id.date);
title = v.findViewById(R.id.title);
summary = v.findViewById(R.id.summary);
}
#Override
public void bindView(Events c) {
date.setText(c.date);
title.setText(c.title);
summary.setText(c.summary);
}
}
Create Items List variable and adapters with very few lines by passing items, class and layout in the adapter
List<Events> items = new ArrayList<>();
MyRecyclerView recycler = findViewById(R.id.recycler);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, items, EVHolder.class, R.layout.row_event);
recycler.setAdapter(adapter);
ClickListener and LoadMore Listener can be added with following lines
recycler.setOnItemClickListener(new MyRecyclerView.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Toast.makeText(MainActivity.this, "Recycler Item Clicked " + position, Toast.LENGTH_SHORT).show();
}
});
recycler.setOnLoadMoreListener(new MyRecyclerView.OnLoadMoreListener() {
#Override
public void onLoadMore() {
loadData();
}
});
loadData();
After the data is loaded this must be called
recycler.loadComplete();
When no LoadMore is required LoadMore layout can be hidden by calling
recycler.hideLoadMore();
More example can be found here
Hope this helps :)
I learned that in order to modify row in a listView I need to gain access eg via adapter.getItem(position) but I have no idea how to work this around. Should I post any code please let me know.
Here is my EditListItemDialog file:
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
private DiaryAdapter adapter;
// public EditListItemDialog(Context context, List<String> fragment_monday) { //first constructor
// super(context);
// this.fragment_monday = fragment_monday;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
private List<String> fragment_monday;
public EditListItemDialog(Context context, DiaryAdapter adapter) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
adapter.notifyDataSetChanged();
dismiss();
}
}
You will have to implement an OnItemClickListener which will be able to tell you what item has been clicked. For example:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
See the official Android documentation for more information.
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class EditListItemDialog extends Activity {
ListView listView ;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
listView = (ListView) findViewById(R.id.list)
String[] values = new String[] { "Automotive", "Banking", "Consumer Electronics",
"Education", "HealthCare and Life Sciences","Industrial Automation","Printing and
Imaging","Manufacturing","Media and
Entertainment","Networking","Retail","Telecom"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
Use This code for simple Listview..
I am using the library found at:
https://github.com/tjerkw/Android-SlideExpandableListView
to provide slidedown views on my listitems. The problem I am running into is that each of my list items has a delete button which will remove the item from the underlying adapter. When this happens if the item that was removed was expanded then the item below it will become expanded. After digging through the source for the expandablelistview library I found that the culprit is a BitSet which is being used to keep track of the states of the listviews ( expanded 1, not expanded 0 ). When I remove an item from the list the list of states does not get updated. It needs to shift all values down. The problem is I am not sure how to notify the library that my adapter has had an item removed from it.
My custom list adapter extends array adapter and when I remove an item I call notifyDataSetChanged. Somehow I need to detect that call in the slideExpandablelistview which wraps my adapter so that I can update the BitSet. IF anyone has worked with this library before or care to take a look I would love some help.
I create the expanandablelistview by doing
myAdapter= new SlideExpandableListAdapter(new CustomAdapter(getActivity(), new ArrayList<CustomObject>()), R.id.contact_row, R.id.expandable);
Thanks,
Nathan
"When this happens if the item that was removed was expanded then the item below it will become expanded."
After deleting the item from your ArrayList and then doing adapter.notifyDataSetChanged(), you can do something like:
((ActionSlideExpandableListView) list).collapse();
Here is a full example that I made by modifying the author's sample that comes with the library:
package com.tjerkw.slideexpandable.sample;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;
public class ExampleActivity extends Activity
{
PersonDB db;
ArrayList<String> people;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedData)
{
super.onCreate(savedData);
this.setContentView(R.layout.single_expandable_list);
final ActionSlideExpandableListView list = (ActionSlideExpandableListView) this.findViewById(R.id.list);
db = PersonDB.getInstance();
people = db.getPeople();
adapter = new PersonArrayAdapter(people);
list.setAdapter(adapter);
// listen for events in the two buttons for every list item.
// the 'position' var will tell which list item is clicked
list.setItemActionListener(new ActionSlideExpandableListView.OnActionClickListener() {
#Override
public void onClick(View listView, View buttonview, int position)
{
switch (buttonview.getId())
{
case R.id.buttonA:
people.remove(position);
((ArrayAdapter<String>) adapter).notifyDataSetChanged();
((ActionSlideExpandableListView) list).collapse();
break;
case R.id.buttonB:
Toast.makeText(ExampleActivity.this, "You pressed buttonB", Toast.LENGTH_SHORT).show();
}
}
// note that we also add 1 or more ids to the setItemActionListener
// this is needed in order for the listview to discover the buttons
}, R.id.buttonA, R.id.buttonB);
}
private class PersonArrayAdapter extends ArrayAdapter<String>
{
public PersonArrayAdapter(ArrayList<String> people)
{
super(ExampleActivity.this, R.layout.expandable_list_item, people);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// if we weren't given a view, inflate one
if (convertView == null)
{
convertView = getLayoutInflater().inflate(R.layout.expandable_list_item, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.text);
textView.setText(people.get(position));
return convertView;
}
#Override
public int getCount()
{
return people.size();
}
}
}
Here is the dummy database class:
package com.tjerkw.slideexpandable.sample;
import java.util.ArrayList;
public class PersonDB
{
private static PersonDB db = null;
private ArrayList<String> people;
private PersonDB()
{
people = new ArrayList<String>();
// fill "database" with dummy data
for (int i = 0; i < 20; i++)
people.add(i, "Person " + i);
}
public static PersonDB getInstance()
{
if (db == null)
db = new PersonDB();
return db;
}
public ArrayList<String> getPeople()
{
return people;
}
public String getPerson(int i)
{
return people.get(i);
}
public void deletePerson(int i)
{
people.remove(i);
}
}
EDIT: I noticed a bug with this code. When a row is deleted and the row below it moves up to fill that space, the text on the new row's buttonA appears left-justified. The only way I could think of to solve this was to replace this line:
((ArrayAdapter<String>) adapter).notifyDataSetChanged();
with these two lines:
adapter = new PersonArrayAdapter(people);
list.setAdapter(adapter);
If anyone has a better solution I would love to see it.
I would like to display the data in an array of string as the Subitems of the listview.
How exactly could I do it?
Is this what you are trying to achieve?
This is part of my code from an ap that uses fragments. One fragment is a list fragment.
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Category List extends ListFragment {
final static String[] CATEGORIES = {"String1","String2",
"String3","String4"};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1,
CATEGORIES));
Hope it helps.
Download the api demos from the Android Development site or open the SDK Manager and ensure you have downloaded Samples for your current SDK.
Then navigate to the samples folder and take a look at expandable lists. There are a few fully working examples there.
On my WinXP comp the files are located here:
C:\Program Files\Android\android-sdk\samples\android-16\ApiDemos\src\com\example\android\apis\view then look for the expandable lists.jar files
You need to create an Adapter class. Here is your solution:
First create a private class in your MainActivity class like this:
private class Adapter extends BaseAdapter
{
ArrayList<String> list;
public Adapter(ArrayList<String> list)
{
this.list=list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public String getItem(int index)
{
return list.get(index);
}
#Override
public long getItemId(int arg0)
{
return 0;
}
#Override
public View getView(int index, View view, ViewGroup arg2)
{
TextView tv_text = new TextView(MainActivity.this);
tv_text.setText(list.get(index));
tv_text.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
#SuppressWarnings("deprecation")
AbsListView.LayoutParams params =
new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT,
AbsListView.LayoutParams.FILL_PARENT);
tv_text.setLayoutParams(params);
tv_text.setHeight(60);
tv_text.setTextSize(18);
return tv_text;
}
}
then you need to put the Strings in ArrayList<String> :
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<yourArray.length(); i++) list.add(yourArray[i]);
after that you need to create an instance of the Adapter class:
Adapter adapter = new Adapter(list);
then you need to set the adapter as the main adapter of your ListView :
ListView lv_list = (ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
D