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.
Related
It's my first time trying to make an App that is basically a checklist that helps me keep track of i.e. collected items. Much like a checklist in a game. I am veeeeery inexperienced with Android so I found some template that I modified for my own need. I'm basically using two .png files (checked and unchecked box) as ImageView which upon clicking change into one another, thus imitating a basic checkbox. Aparently this method worked best for me, even though I thought a normal checkbox object would be easier. When i used regular checkbox objects the status of 'checked' moved throughout the list... And with this ImageView method the checked boxes remained the same as the ones I really checked.
So I figured how to generate a List. Later on I will manually change the list to the Items/Names/etc. as I want that won't be a problem. The App also manages to let me select multiple Items and the items remain checked even after its onPause.
The problem I face now is that upon distroying the app on the device and on restarting the app, all the checked Items are now unchecked. That means that the information that the item was check was not stored at all.
I would be so happy if someone can help me with completing the code... I have no idea how to store the information of which Item in List was checked and let alone be reloaded upon onCreate.
Here is activity_main.xml, which is basically the ListView.
<?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"
android:paddingBottom="15dp"
android:paddingTop="15dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
tools:context="com.multiselect.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listview"
android:divider="#android:color/darker_gray"
android:dividerHeight="2dp"/>
</RelativeLayout>
Next up is the list_view_item.xml where the Name, Subtitle and Checkbox ImageView are declared.
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="60dp">
//NAME//
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_user_name"
android:gravity="center_vertical"
android:layout_toEndOf="#+id/iv_check_box"
android:paddingStart="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
//SUB
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_user_sub"
android:layout_alignStart="#+id/tv_user_name"
android:layout_below="#+id/tv_user_name"
android:paddingStart="10dp"
android:textColor="#color/sub"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="RtlSymmetry" />
//Checkbox
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:id="#+id/iv_check_box"
android:layout_alignParentStart="true"
android:onClick="onCheckboxClicked"
android:layout_centerVertical="true"
android:background="#drawable/check"/>
</RelativeLayout>
So then I have a basic UserModel.java with all the Getters and Setters.
package com.multiselect;
public class UserModel {
private boolean isSelected;
private String userName;
private String userSub;
//create constructor and getter setter
public UserModel(boolean isSelected, String userName, String userSub) {
this.isSelected = isSelected;
this.userName = userName;
this.userSub = userSub;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSub() {
return userSub;
}
public void setUserSub(String userSub) {
this.userSub = userSub;
}
}
Then I know I need an CustomAdapter.java for what I wanna do. I have a ViewHolder inside together with an updater for the checle items.
package com.multiselect;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
Activity activity;
List<UserModel> users;
LayoutInflater inflater;
//short to create constructer using alt+insert or rightclick - generate - constructor
public CustomAdapter(Activity activity) {
this.activity = activity;
}
public CustomAdapter(Activity activity, List<UserModel> users) {
this.activity = activity;
this.users = users;
inflater = activity.getLayoutInflater();
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder = null;
if(view == null){
view = inflater.inflate(R.layout.list_view_item, viewGroup, false);
holder = new ViewHolder();
holder.tvUserName = (TextView)view.findViewById(R.id.tv_user_name);
holder.tvUserSub = (TextView)view.findViewById(R.id.tv_user_sub);
holder.ivCheckBox = (ImageView) view.findViewById(R.id.iv_check_box);
view.setTag(holder);
}else
holder = (ViewHolder) view.getTag();
UserModel model = users.get(i);
holder.tvUserName.setText(model.getUserName());
holder.tvUserSub.setText(model.getUserSub());
if (model.isSelected()) {
holder.ivCheckBox.setBackgroundResource(R.drawable.checked);
}
else
holder.ivCheckBox.setBackgroundResource(R.drawable.check);
return view;
}
public void updateRecords(List<UserModel> users) {
this.users = users;
notifyDataSetChanged();
}
class ViewHolder{
TextView tvUserName;
TextView tvUserSub;
ImageView ivCheckBox;
}
}
...And MainActivity.java:
package com.multiselect;
import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.content.SharedPreferences;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final List<UserModel> users = new ArrayList<>();
for(int i = 0; i<20; i++) {
users.add(new UserModel(false, "Name "+(i), "Subtitle " + (i)));
}
final CustomAdapter adapter = new CustomAdapter(this, users);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
UserModel model = users.get(i);
if (model.isSelected())
model.setSelected(false);
else
model.setSelected(true);
users.set(i, model);
//now update adapter
adapter.updateRecords(users);
}
});
}
}
And now I know I should use SharedPreferences in the MainActivity.java but I don't know how in this specific example...
Especially when I try it out with what other people said the app just crashes either as soon as I check something or when I just try to Run the app. I'm literally not good enough for this and I really want to know how something I normally take for granted (that an app remembers whats been don in it) is done programmatically.
I hope that someone can complete my Code so that the app remembers which box was checked and reloads that upon onCreate...
First, u need to add a unique attribute to your user model. like userId
private int userId
then add setters and getters like other attributes. I think then u can use tinyDB to stores recent value of this userId. Then u can increment this userId when new user model added.
TinyDB tinydb = new TinyDB(context);
int recentid = tinydb.getInt(recentUserId) == null ? 0:tinydb.getInt(recentUserId)
tinydb.putInt("recentUserId",recentid++);
userModel1.setUserId(recentid)
After that, You can create array list with checked ids. If the user checked any post then update that list. If user unchecked that list then remove id from list.
List<int> checkedList = new ArrayList<>;
checkedList.add(..userid);
Then u can update TinyDb when you update that checked list using below command.
tinydb.putList("checkedIdList", chekcedList);
when app starting state u need to call this tinydb and get checked list using below command
tinydb.getList("checkedIdList");
then u can update your list with checked and unchecked states
PS: u can nevigate to https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo this and get idea about tinydb as well. It is kind of good improvement of shared preferences
You need to do following thing in onCrete method to avoid always update checkList.
List<int> checkedList = new ArrayList<>;
if(tinydb.getList("checkedIdList")!= null){
checkedList = tinydb.getList("checkedIdList")
}
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);
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 writing a code to show a multiple selection list (one having check boxes) and when the user checks an item i want to retrieve user's name and id from database table and display it in toast. Here's the code:
Activity code
public class Add_To_Circle extends Activity {
ListView lv;
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_to_circle);
// Get listview
lv = (ListView)findViewById(R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
... //all the other code,and then in another class in postexecute there is adapter:
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
Add_To_Circle.this, productsList,
android.R.layout.simple_list_item_multiple_choice, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
lv.setAdapter(adapter);
}
});
}
}
Code of XML file
<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">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
the output: a blank listview with only checkboxes as in the attched image. What am i doing wrong? i have followed same steps as in tutorials on web still no luck :((
you can use custom adapter that has one textview and checkbox.Here are the links,
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html
http://androidcocktail.blogspot.in/2012/04/adding-checkboxes-to-custom-listview-in.html
and if you want to use simple array adapter,
refer this link,
Selecting multiple items in ListView
Thanks
Ok, will try and give an answer but I have had to change the Adapter for the answer, so that part is untested.
Lets go bottom up, this is the XML layout for each single element in the list:
view_adapter_item_checklist.xml
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:textAppearance="?android:attr/textAppearanceLarge" />
Using CheckedTextView removes the need to handle the checkbox checked/unchecked handling ourselves.
Now the ListView, in my code it is placed inside a LinearLayout, hence the 0dp height. The important part is choiceMode:
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:choiceMode="multipleChoice"
android:drawSelectorOnTop="false" />
The adapter is really rather simple. It takes a list of Strings and inflate list rows based on the checktext XML above. The only task is to set the text of the view, actually:
SimpleChecklistAdapter:
public class SimpleChecklistAdapter extends ArrayAdapter<String> {
private final Context context;
private final List<String> values;
public SimpleChecklistAdapter(Context context, List<String> values) {
super(context, R.layout.view_adapter_item_checklist, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.view_adapter_item_checklist,
parent, false);
CheckedTextView text = (CheckedTextView)rowView.findViewById(R.id.item);
text.setText(values.get(position));
return rowView;
}
}
All there is left is to use the new fancy checklist adapter instead of SimpleAdapter in your code
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);