I'm trying to create put a ListView with 2 TextViews in each row on an Activity and populate it. The thing about the data ListView to be populated with is that it's not a "table" data, meaning the amount of the records can change frequently, but it's almost static, that is all the amount of rows are definite and known at compile time. So it's pretty much like this sort of data
What I'll need to update is only the 2nd TextView in each row when the certain menu item is pressed in a toolbar.
I can't figure out how to do that because pretty much all the examples out there assume the data to populate the ListView with is dynamic which isn't the case for me.
Do I still need to create a custom adapter inherited from BaseAdapter? And "one row xml layout" and put it into layouts?
Or should I create the ListView and all the TextViews statically in the layouts like this and then set up their values from the Activity?
<ListView .....
<TextView ..... />
<TextView ..... />
<TextView ..... />
</ListView>
I made a simple example based on what I understood from your description. Here is the full code :
MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.myapplication.R.array.staticText1Elements;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
ListView myListView = (ListView) findViewById(R.id.listViewId);
List<String> dynamicText2Elements;
dynamicText2Elements = new ArrayList<String>();
dynamicText2Elements.add("element1 of text2");
dynamicText2Elements.add("element2 of text2");
dynamicText2Elements.add("element3 of text2");
dynamicText2Elements.add("element4 of text2");
dynamicText2Elements.add("element5 of text2");
List<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> element;
int length = getResources().getStringArray(staticText1Elements).length;
for (int i = 0; i < length; i++) {
element = new HashMap<String, String>();
element.put("text1", getResources().getStringArray(staticText1Elements)[i]);
element.put("text2", dynamicText2Elements.get(i));
dataList.add(element);
}
ListAdapter myAdapter = new SimpleAdapter(this, dataList, android.R.layout.simple_expandable_list_item_2, new String[]{"text1", "text2"}, new int[]{android.R.id.text1, android.R.id.text2});
myListView.setAdapter(myAdapter);
}
}
activity_main.xml
<RelativeLayout 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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">My Application</string>
<array name="staticText1Elements">
<item>GPS version</item>
<item>Wi-FI version</item>
<item>Bluetooth version</item>
<item>Touch panel version</item>
<item>Battery version</item>
</array>
</resources>
You need an adapter to fill the list view, inside the adapter you set the two textviews and fill the list view with a static array of strings of resources or arraystrings in java see this link Populating a ListView using an ArrayList?
this is the adapter
public class AdapterAlumnos extends ArrayAdapter<Object> {
private LayoutInflater inflate;
private List<Object> listSolcitudes;
Context context;
public AdapterAlumnos(Context context, List<Object> listSolcitudes) {
super(context, R.layout.item_estudiante, listSolcitudes);
inflate = LayoutInflater.from(context);
this.listSolcitudes = listSolcitudes;
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflate.inflate(R.layout.item_estudiante, parent, false);
TextView txtNombreEstudianteItem = (TextView) convertView.findViewById(R.id.txtNombreEstudianteItem);
TextView txtGradoEstudianteItem = (TextView) convertView.findViewById(R.id.txtGradoEstudianteItem);
HashMap<String, Object> obj = (HashMap<String, Object>) getItem(position);
String genero = (String) obj.get("YourKEY");
txtNombreEstudianteItem.setText(nombre);
in the activity
ArrayList arrayArray = new ArrayList<Object>(); // your list key-value
adapter = new AdapterAlumnos(getApplicationContext(),arrayArray);
ListView listEstudiantes =(ListView)findViewById(R.id.listEstudiantes);
listEstudiantes.setAdapter(adapter);
Related
enter image description hereThis is my list_item layout and i think there may be some problem with this layout
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/colorAccent"
android:textSize="18sp"
tools:text="india china tension" />
<TextView
android:id="#+id/summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/colorPrimaryDark"
android:textSize="22sp"
tools:text="Modi silent on china issue" />
</LinearLayout>
This is main activity
package com.example.android.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating fake news reports
ArrayList<News> news = QueryWeb.extractNews();
//finding a layout reference{#link ListView}in the layout
ListView newsListView = (ListView) findViewById(R.id.list);
// Create a new adapter that takes list of earthquakes
final NewsAdapter adapter = new NewsAdapter(this, news);
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
newsListView.setAdapter(adapter);
}
}
This is the array adapter
package com.example.android.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by ammulu on 22-07-2017.
*/
public class NewsAdapter extends ArrayAdapter<News> {
/**
* Constructs a new {#link NewsAdapter}.
*
* #param context of the app
* #param news is the list of earthquakes, which is the data source of the adapter
*/
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
/**
* Returns a list item view that displays information about news at the given position
* in the list of news
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if there is an existing list item view (called convertView) that we can reuse,
// otherwise, if convertView is null, then inflate a new list item layout.
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.newslist_item, parent, false);
}
// Find the news at that position
News currentNews = getItem(position);
// Find the TextView with view ID title
TextView titleView = (TextView) listItemView.findViewById(R.id.title);
//Display the title
titleView.setText(currentNews.getTitle());
// Find the TextView with view ID summary
TextView summaryView = (TextView) listItemView.findViewById(R.id.summary);
//Display the summary
summaryView.setText(currentNews.getSummary());
//Return the list item that is showing the appropriate data
return listItemView;
}
}
Json parsing code i think the problem is here
package com.example.android.myapplication;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public final class QueryWeb {
/**
* sample json response for news query
*/
private static final String SAMPLE_JSON_RESPONSE = "{\\\"status\\\":\\\"ok\\\",\\\"source\\\": \\\"techcrunch\\\",\\\"sortBy\\\": \\\"top\\\",\"articles\": [{\\\"author\\\": \\\"Alexandra Ames\\\",\\\"title\\\": \\\"Coverage\\\",\\\"description\\\":\\\"Coverage | Sessions: Robotics - Cambridge, MA - July 17, 2017\\\",\\\"url\\\": \\\"https:\\/\\/techcrunch.com\\/events\\/sessions-robotics\\/coverage\\/\\\",\\\"urlToImage\\\": \\\"https:\\/\\/s0.wp.com\\/wp-content\\/themes\\/vip\\/techcrunch-2013\\/assets\\/images\\/techcrunch.opengraph.default.png\\\",\\\"publishedAt\\\": \\\"2017-07-14T00:02:35Z\\\"},\n" +
"{\\\"author\\\": \\\"Matthew Lynley\\\",\\\"title\\\": \\\"Dropbox CTO Aditya Agarwal is leaving\\\",\\\"description\\\": \\\"Aditya Agarwal, who came to Dropbox via its acquisition of Cove way back in 2012 and was given the CTO role last year, will be leaving the company. Agarwal..\\\",\\\"url\\\": \\\"https:\\/\\/techcrunch.com\\/2017\\/07\\/21\\/dropbox-cto-aditya-agarwal-is-leaving\\/\\\",\\\"urlToImage\\\": \\\"https:\\/\\/tctechcrunch2011.files.wordpress.com\\/2017\\/07\\/dropbox-fb-departure.jpg?w=764&h=400&crop=1\\\",\\\"publishedAt\\\":\\\"2017-07-21T17:18:11Z\\\"}],\n" ;
/**
* Create a private constructor because no one should ever create a {#link QueryWeb} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryWeb is not needed).
*/
private QueryWeb() {
}
/**
* Return a list of {#link News} objects that has been built up from
* parsing a JSON response.
*/
public static ArrayList<News> extractNews() {
// Create an empty ArrayList that we can start adding earthquakes to
ArrayList<News> newsArray = new ArrayList<>();
// Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// TODO: Parse the response given by the SAMPLE_JSON_RESPONSE string and
// build up a list of Earthquake objects with the corresponding data.
JSONObject baseJsonResponse = new JSONObject(SAMPLE_JSON_RESPONSE);
JSONArray titleArray = baseJsonResponse.getJSONArray("articles");
for(int i=0; i < titleArray.length(); i++ ){
JSONObject newRead = titleArray.getJSONObject(i);
String title = newRead.getString("title");
String summary = newRead.getString("description");
// Create a new {#link News} object with the magnitude, location, time,
// and url from the JSON response.
News news = new News( title, summary);
newsArray.add(news);
}
} catch (JSONException e) { // If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryWeb", "Problem parsing news JSON results", e);
}
// Return the list of earthquakes
return newsArray;
}
}
activty main xml layout
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for a list of news-->
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="1dp"/>
How many items are in the data set represented by this Adapter.
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
#Override
public int getCount() {
return news.size();
}
Okay, first you need to create a local list in adapter.
List<News> news = new ArrayList();
Then in your constructor try this
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
this.news = news
}
then override this
#Override
public int getCount() {
return news.size();
}
This is how you set values in model class.
News news = new News( title, summary);
news.setTitle(title);
news.setSummary(summary);
Then finally you add them to list of News type
newsArray.add(news)
And finally in adapter
titleView.setText(news.get(position).getTitle));
summaryView.setText(news.get(position).getSummary);
The LayoutInflater is not working properly with parent in some cases. So change string
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.newslist_item, parent, false);
to:
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.newslist_item, null);
There are no errors in the message console when I run my project but it keeps crashing. I couldn't spot the reason. I tried to go through some of the similar questions asked and did implement the given solutions but it still didn't help me. Here is my code.
package com.example.omar.quakereport;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class EarthquakeActivity extends AppCompatActivity {
ListView earthquakeListView;
ArrayList<String> earthquakes;
ArrayAdapter<String> adapter;
// public static final String LOG_TAG = EarthquakeActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
// Create a fake list of earthquake locations.
earthquakes = new ArrayList<>();
earthquakes.add("San Francisco");
earthquakes.add("London");
earthquakes.add("Tokyo");
earthquakes.add("Mexico City");
earthquakes.add("Moscow");
earthquakes.add("Rio de Janeiro");
earthquakes.add("Paris");
// Find a reference to the {#link ListView} in the layout
earthquakeListView = (ListView) findViewById(R.id.list);
// Create a new {#link ArrayAdapter} of earthquakes
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, earthquakes);
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
earthquakeListView.setAdapter(adapter);
}
}
This is the class that houses my getters:
package com.example.omar.quakereport;
public class Earthquakes {
private String mMagnitude;
private String mLocation;
private String mDate;
public Earthquakes(String magnitude, String location, String date){
mMagnitude = magnitude;
mLocation = location;
mDate = date;
}
public String getMagnitude(){
return mMagnitude;
}
public String getLocation(){
return mLocation;
}
public String getDate(){
return mDate;
}
This is my activity xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And this is my list item xml
<?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>
ListViews do not have an orientation attribute.
You should wrap the ListView in a Relative/Linear/Frame-Layout
Then, you need to use an ArrayAdapter<Earthquake> adapter; (see here) (and make your class name singular). Alternatively, you need to implement toString() on the Earthquake class, as that is what the ArrayAdapter<String> uses to display the data.
And, then edit the item layout to add TextViews to display and EarthQuake data, and finally use the earthquake item xml layout, not android.R.layout.simple_list_item_1
Once you have that adapter, you can actually do this to add and display data
adapter.add(new Earthquake("magnitude", "location", "date"));
I am trying to create ListView with custom data set as follows:
String superType = "random1";
String superTypea = "random12";
String superType12 = "random2";
String superType_amount = "child1";
String childtype_calulated = "2323";
String superType_amount = "child2";
String childtype_calulated = "23223";
String superType_amount = "child2";
String childtype_calulated = "amount3";
Now I want to create ListView with this set of data how to do that?
Here is the list structure...
row1=superType |superType_amount |childtype_calulated
row2=superTypea |superType_amount |childtype_calulated
row3=superType12|superType_amount |childtype_calulated
Is there any solution of this?
It is absolutely possible to do this. First, I would recommend putting your data into a collection. It would be preferable to put them into an object and then a collection of those objects. From there you can add a ListView to your main layout, define a custom layout for your list items, and populate your ListView using an ArrayAdapter.
Here is a really good example of how you can do this well. It includes examples of loading data from an external source, which you don't need.
However, if you're getting into development now I would suggest you look into RecyclerView as well. RecyclerView is new and included in the AppCompat v7 library for use on pre-Lollipop Android. A RecyclerView will be a little more complicated to implement for a simple list but is significantly more scalable and efficient. I believe it is Google's intention to replace ListView with RecyclerView entirely in the future.
Here is a pretty simple introduction to making a list with RecyclerView.
EDIT
Using an ArrayAdapter with a ListView. First you need to create a model to store your data, some kind of class that you can put into a collection, for example:
public class Item {
public String title;
public String sub1;
public String sub2;
public void Item(String t, String s1, String s2) {
title = t;
sub1 = s1;
sub2 = s2;
}
}
Then you need to define the layout for the item in your list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sub1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sub2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Then in you need to make your custom ArrayAdapter by extending the ArrayAdapter class:
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView sub1 = (TextView) convertView.findViewById(R.id.sub1);
TextView sub2 = (TextView) convertView.findViewById(R.id.sub2);
title.setText(item.title);
sub1.setText(item.sub1);
sub2.setText(item.sub2);
return convertView;
}
}
Then all you need to do is create an instance of the adapter in your main class and attach your collection to it:
ArrayList<Item> data = new ArrayList<Item>();
ItemAdapter adapter = new ItemAdapter(this, data);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
This should populate your ListView with all the items that you need in your list. I haven't run any of this code so there might be one or two small bugs for you to fix.
I am new in android and i am using list view that is coming from the database . Now , I want to add two icons in it , one for edit and one for delete. Here is my java code that is currently working
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("cat_name");
number = jsonChildNode.optString("cat_id");
String outPut = name /*+ "-" + number*/;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
can anyone tell me how to edit it to add the icons ?
As you told you are new so I am creating a listview similar to your needs. If you are still facing any problem then you can ask. There can be other methods also but I have followed below one.
I have created it in three steps:
1. Create a listview layout in XML.
2. Create a layout for your row which you will inflate and set on listview row.
3. Create a custom adapter by extending arrayadapter.
4. Setting custom adapter.
Step 1: Create a listview layout in XML.
Below given XML code will create a listview for you.
<RelativeLayout 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: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=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Step 2: Create a layout for your row which you will inflate and set on listview row.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="TextView" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="34dp"
android:layout_toRightOf="#+id/textView1"
android:src="#drawable/ic_launcher" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/imageButton1"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Step 3:Create a custom adapter by extending arrayadapter.
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class my_list_adapter extends ArrayAdapter<String> {
private Context context;
private ArrayList<String> labels;
public my_list_adapter(Context context, ArrayList<String> labels) {
super(context, R.layout.list_layout, labels);
this.context = context;
this.labels = labels;
}
static class ViewHolder {
public TextView textView1;
public ImageButton icon_1;
public ImageButton icon_2;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(R.layout.list_layout, null, true);
holder = new ViewHolder();
holder.textView1 = (TextView) rowView.findViewById(R.id.textView1);
holder.icon_1 = (ImageButton) rowView.findViewById(R.id.imageButton1);
holder.icon_2 = (ImageButton) rowView.findViewById(R.id.imageButton2);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.textView1.setText(labels.get(position));
holder.icon_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(), "bb icon 1 item clicked position = " + position, Toast.LENGTH_LONG).show();;
}
});
holder.icon_2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(), "bb icon 2 item clicked position = " + position, Toast.LENGTH_LONG).show();;
}
});
return rowView;
}
}
Step 4: Setting custom adapter.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list_view = (ListView) findViewById(R.id.listView1);
ArrayList<String> labels = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
labels.add ("item " + i);
}
my_list_adapter adapter = new my_list_adapter(this, labels);
list_view.setAdapter(adapter);
}
I think above example can help you. Try to get the concept. If you are facing any problem then you can ask. I will try to help you.
Use CustomArray adapter to add edit/delete button. This tutorial will help you. please check it.
For this scenario you have to use ur custom adapter
means extends BaseAdapter
and try to implement all methods in that adapter.
It is confusing if you're new to Android, but there's no shortcut in learning how to do it. Try this tutorial as well, I found it pretty helpful:
http://theopentutorials.com/tutorials/android/listview/android-custom-listview-with-image-and-text-using-baseadapter
None of the tutorials are going to help you, because none show how to put a listener on a button in a listview in the getView() method of a custom ArrayAdapter and show you how to figure out what item in the listviev owns that button. Even if there is a way to do this, you then have to figure out how (from the ArrayAdapter class) to call a method back in your Activity or Fragment, where you can then act on that item.
So, this leaves you with several options. Instead of buttons, you need to respond to clicks/presses on the list item itself. This is done by adding an OnItemClickListener or OnItemLongClickListener to the listview. You can then respond to these actions in several ways:
A context menu, where the user can select the option to delete or
edit the item (using a listview of menu options).
A pop-up Dialog that does the same thing with buttons. Ot it could put them in edit mode and have a delete button too.
Since you are going to need to write a Dialog for the editing of the item, I would go with the Dialog option.
I am working on an application in Android that works with 2 screens. The firsts creen is simple, it has a TextView initialzed to "Not Set" and a Button. When the user clicks on the button, he/she is taken to the 2nd screen which is one big ListView. The ListView is a list of all highest grossing movies of all time. It would be simple if it were to include just the title, but I need to create the listview such that it has multiple lines. The structure being, the title is oriented left, the gross earnings aligned right and the date released is located on a second row.
The important tidbit is that I need to use string arrays declared at the strings.xml. I have already declared all of them, however my problem is that I am stuck on how to make the Java portion. Here is what I have come up so far.
package com.android.rondrich;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Lab5_082588part2 extends ListActivity {
public static final String KEY = "KEY";
public static final String RETURN = "RETURN";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.lab5_082588part2, grossList)); //not sure if correct to have 2 setListAdapters
setListAdapter(new ArrayAdapter<String>(this,
R.layout.lab5_082588part2, titleList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = getIntent();
String title = ((TextView) view).getText().toString();
intent.putExtra(Lab5_082588part2.RETURN, title);
setResult(RESULT_OK, intent);
finish();
}
});
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
}
Some of the snippets I have researched are using this kind of approach (sample code)
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr = new SearchResults();
sr.setName("Justin Schultz");
sr.setCityState("San Francisco, CA");
sr.setPhone("415-555-1234");
results.add(sr);
However this method will prove very tedious for long lists. The question is that:
How do I incorporate using string arrays declared in strings.xml to have multi-line listview without resorting to hardcoding it like above?
You can't set the adapter two times to show the row like you want instead you have to implement a custom adapter(there are thousands of tutorials out there to look at so I'll leave this part out).
To extract the data from the strings arrays you would(almost) use the snippet you posted:
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
// ...
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
// make sure the arrays have the same length
for (int i = 0; i < titleList.length; i++) {
SearchResults sr = new SearchResults();
sr.setTitle(titleList[i]);
sr.setGross(grossList[i]);
results.add(sr);
}
return results;
}
Then you would use the list returned by this method to fill your custom adapter.
A layout example:
<?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" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="title" />
<TextView
android:id="#+id/gross"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/title"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Gross" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/title"
android:text="Date" />
</RelativeLayout>
How to make custom ListView items you can read in this tutorial: http://www.ezzylearning.com/tutorial.aspx?tid=1763429
If you want to get String from your strings.xml use that in your ativity class:
getContext().getResources.getString(R.string.your_text);