Android: archiving items in listview - android

I'm having a listview in which I'm displaying the text items. I want to display a checkbox along with the text for two type of actions to be performed. one is when the user click on the list item it should take to another activity and another is the user can select the checkbox of the list item and can move the items to some groups. As similar to that we do in the gmail inbox. how can i do it ? Any help ?
Here I attach my code.
keywords.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/keywordlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/category_title_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#fff"
>
<TextView
android:id="#+id/category_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="#+id/keywordslist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
>
</ListView>
</LinearLayout>
The xml file used for displaying list items layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<CheckBox
android:id="#+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"
>
</CheckBox>
<TextView
android:id="#+id/key_id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
</TextView>
<TextView
android:id="#+id/key_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#FFF">
</TextView>
</LinearLayout>
and my java code for the activity
package com.sample.epiphron;
public class KeywordsList extends Activity {
TextView category_title;
ListView keywords_list ;
String categoryid, categoryname;
private ArrayList<KeywordDetails> listItems = new ArrayList<KeywordDetails>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.keywords);
Bundle extras = getIntent().getExtras();
categoryid = extras.getString("category_id");
categoryname = extras.getString("category_name");
category_title = (TextView) findViewById(R.id.category_title);
category_title.setText(""+categoryname+"- Keywords");
keywords_list = (ListView) findViewById(R.id.keywordslist);
drawList(LoginScreen.user_credential, categoryid);
//Toast.makeText(this, chkbx.toString(), Toast.LENGTH_SHORT).show();
keywords_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView txtv1 = (TextView) arg1.findViewById(R.id.key_id);
Toast.makeText(KeywordsList.this, txtv1.getText(), Toast.LENGTH_LONG).show();
}
});
}
public void drawList(String userid, String cat_id){
WebServiceCall res = new WebServiceCall();
SoapObject result = res.fetchKeyword(userid, cat_id);
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i<result.getPropertyCount(); i++){
SoapObject obj = (SoapObject) result.getProperty(i);
al.add((String) obj.getProperty("keywordname"));
KeywordDetails object = new KeywordDetails(Integer.parseInt(obj.getProperty("keywordid").toString()), obj.getProperty("keywordname").toString());
listItems.add(object);
}
for ( int j = 0; j < result.getPropertyCount(); j++ ) {
}
keywords_list.setAdapter(new ListItemsAdapter(listItems));
}
public class KeywordDetails{
private int keyword_id;
private String keyword_name;
public KeywordDetails(int key_id, String key_name){
this.keyword_id = key_id;
this.keyword_name = key_name;
}
public int getId(){
return this.keyword_id;
}
public String getName(){
return this.keyword_name;
}
//...
}
private class ListItemsAdapter extends ArrayAdapter<KeywordDetails> {
ArrayList<KeywordDetails> obj = null;
KeywordDetails keyworddtls = null;
public ListItemsAdapter(ArrayList<KeywordDetails> items) {
super(KeywordsList.this, android.R.layout.simple_list_item_1, items);
this.obj = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.keyword_list_item, null);
final TextView text1 = (TextView) convertView.findViewById(R.id.key_id);
TextView text2 = (TextView) convertView.findViewById(R.id.key_name);
CheckBox chkbx = (CheckBox) convertView.findViewById(R.id.chk_box);
keyworddtls = obj.get(position);
text1.setText(Integer.toString(keyworddtls.getId()));
text2.setText(keyworddtls.getName());
chkbx.setVisibility(View.VISIBLE);
return convertView;
}
}
}

Add the CheckBox in the xml where is your <ListView > or in the xml which you use as item layout. Then in the getView() instantiate the CheckBox along the TextView. Implement listview.setOnItemClickListener() and based on which item was clicked (position) you start the activity [matter of logic] For the grouped of check items you can use getCheckedItemPositions(). I hope this will give you fire up idea.

Related

Create a List of Custom form Layout to enter details based on the count entered

I am a novice in Android App Development, learning through online materials, I am developing an app in which i'm stuck at one place, I enter the Number of Participants in layout1 based on the count i want to generate a custom form that i have designed (shown in layout2) to get the input of so many people. I tried using Array Adapter and Inflator concepts to display the custom layout in a ListView but i couldn't do it, or if it could be acheived please help me. My desired output is shown in layout3
After navigating from Layout1 with the No of Participants I'm doing this so that i create my desired ouput as attached in Layout3. These are the things i tried but am stuck, please forgive if the code is ameateur and help me find a way to complete this, your help would be appreciated.
Layout3Activity
public class Layout3Activity extends Activity{
//
//
//
ListView listView;
FriendsLayoutAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout3);
listView = (ListView) findViewById(R.id.listView1);
adapter = new FriendsLayoutAdapter(getApplicationContext(),R.layout.layout2);
listView.setAdapter(adapter);
}
//
//
//
//
}
layout2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="160dp"> <!-- setting layout height to 160dp so that it only fits in the box we have created-->
<TextView
android:text="Friend i"
android:textAppearance="?android:textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friendLabel"
android:layout_above="#+id/nameEditText"
android:layout_alignStart="#+id/nameTextView"
android:layout_marginBottom="15dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name here..!!"
android:id="#+id/nameEditText"
android:layout_toRightOf="#+id/nameTextView"
android:layout_alignBaseline="#+id/nameTextView"
android:layout_alignBottom="#+id/nameTextView"
android:layout_centerHorizontal="true"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Amount Spent..!!"
android:id="#+id/amountEditText"
android:layout_toRightOf="#+id/amountTextView"
android:layout_alignBaseline="#+id/amountTextView"
android:layout_alignBottom="#+id/amountTextView"
android:layout_centerHorizontal="true"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp" />
<TextView
android:text="Amount:"
android:textAppearance="?android:textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:id="#+id/amountTextView"
android:layout_marginTop="17dp"
android:layout_below="#+id/nameEditText"
android:layout_alignParentStart="true" />
<TextView
android:text="Name:"
android:textAppearance="?android:textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:id="#+id/nameTextView"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/amountTextView" />
<!--<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/amountEditText"
android:background="#color/jetBlack">
</View>-->
</RelativeLayout>
layout3.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
FriendsLayoutAdapter
public class FriendsLayoutAdapter extends ArrayAdapter{
String[] friends = {"Friend 1", "Friend 2","Friend 3","Friend 4"};
public FriendsLayoutAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.entries_layout,viewGroup,false);
TextView friendLabel = (TextView) view.findViewById(R.id.friendLabel);
TextView name = (TextView) view.findViewById(R.id.nameTextView);
TextView amount = (TextView) view.findViewById(R.id.amountTextView);
EditText nameEdit = (EditText) view.findViewById(R.id.nameEditText);
EditText amountEdit = (EditText) view.findViewById(R.id.amountEditText);
return super.getView(i, view, viewGroup);
}
//
//
//
}
You need to modify your adapter, you are displaying 0 elements.
Try this :
public class FriendsLayoutAdapter extends ArrayAdapter{
String[] friends = {"Friend 1", "Friend 2","Friend 3","Friend 4"};
public FriendsLayoutAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public int getCount() {
return friends.length();
}
#Override
public Object getItem(int i) {
return friends[i];
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
String value = friends[i];
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.entries_layout,viewGroup,false);
TextView friendLabel = (TextView) view.findViewById(R.id.friendLabel);
TextView name = (TextView) view.findViewById(R.id.nameTextView);
TextView amount = (TextView) view.findViewById(R.id.amountTextView);
EditText nameEdit = (EditText) view.findViewById(R.id.nameEditText);
EditText amountEdit = (EditText) view.findViewById(R.id.amountEditText);
friendLabel.setText(value);
return super.getView(i, view, viewGroup);
}
}

Retrieving Data from External Site using Asynctask

I'm new to Asynctask and JSon.
May i know how to start to retrieve the currency rates from this site?
http://api.fixer.io/latest?base=SGD
I did look at this post but i'm not too sure how to start..
AsyncTask Android example
From the rates retrieved, i'd like to add the values into this ListView, by using a custom ListView adapter class.
Codes for xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0.0dp"
android:orientation="horizontal"
android:layout_weight="0.4"
android:weightSum="1" >
<LinearLayout
android:layout_width="0.0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.8" >
<TextView
android:id="#+id/convertedAmtTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0.00"
android:textSize="70dp"
android:gravity="right" />
<EditText
android:id="#+id/inputAmtET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:textAlignment="textEnd" />
</LinearLayout>
<LinearLayout
android:layout_width="0.0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.2">
<TextView
android:id="#+id/convertedCurrTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SGD"
android:textSize="28dp"
android:paddingLeft="2dp"
android:paddingTop="29dp"
android:paddingBottom="19dp"
android:gravity="center_horizontal" />
<TextView
android:id="#+id/inputCurrTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="AUD"
android:textSize="28dp"
android:paddingLeft="2dp"
android:layout_marginTop="3dp"
android:gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_weight="0.6"
android:layout_width="match_parent"
android:layout_height="0.0dp">
<TextView
android:text="From"
android:textSize="21dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/currencyLV"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Codes for MainActivity.class
public class MainActivity extends AppCompatActivity {
CurrencyRatesDetails crd = new CurrencyRatesDetails();
CurrencyRates cr = new CurrencyRates();
TextView inputCurrTV, convertedAmtTV;
ListView currencyLV;
EditText inputAmtET;
ArrayAdapter<String> adapter;
String[] currNameArr = crd.getNames();
String[] currCodeArr = crd.getCodes();
String[] currRateArr = crd.getRates();
String[] dbName;
String[] dbCode;
String[] dbRate;
Context context;
int index = 0;
//String[] rateCurrArr = {"AUD", "BGN", "BRL", "CAD", "CHF", "CNY"};
//double[] rateArr = {0.944, 1.2824, 2.2842, 0.96158, 0.70946, 4.8624}
Menu myMenu = null;
double amtInput, finalConversion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
//context.deleteDatabase("currency.db");
inputAmtET = (EditText) findViewById(R.id.inputAmtET);
convertedAmtTV = (TextView) findViewById(R.id.convertedAmtTV);
inputCurrTV = (TextView) findViewById(R.id.inputCurrTV);
currencyLV = (ListView) findViewById(R.id.currencyLV);
/*for (int i = 0; i < currNameArr.length; i++) {
cr.addToDataBase(currNameArr[i], currCodeArr[i], currRateArr[i], getApplicationContext());
}*/
//cr.addToDataBase(currNameArr, getApplicationContext());
//Resources myRes = this.getResources();
//currArr = myRes.getStringArray(R.array.currencyList);
//adapter = ArrayAdapter.createFromResource(this, R.array.currencyList, android.R.layout.simple_selectable_list_item);
//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, currNameArr);
//currencyLV.setAdapter(adapter);
dbName = cr.retrieveAllName(getApplicationContext());
dbCode = cr.retrieveAllCode(getApplicationContext());
dbRate = cr.retrieveAllRate(getApplicationContext());
currencyLV.setAdapter(new CustomAdapter(this, dbName, dbCode, dbRate));
currencyLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
inputCurrTV.setText(dbCode[i]);
index = i;
//Getting rate based on selected currency code
//rate = rateArr[i];
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.myMenu = menu;
addMenuItems(menu);
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
private void addMenuItems(Menu menu) {
int index = 200;
menu.add(index, index, index, "Settings");
menu.add(index, index + 1, index + 1, "Add Custom Rate");
menu.add(index, index + 2, index + 2, "Load Default Rates");
}
public boolean onOptionsItemSelected(MenuItem item) {
//getOrder() to get Menu Item at this specific orderId
if (item.getItemId() == R.id.menu_convert) {
amtInput = Double.parseDouble(inputAmtET.getText().toString());
//finalConversion = amtInput / rate;
finalConversion = crd.conversion(amtInput, index);
//Formatting converted value to 2d.p
String finalValue = String.format("%.2f", finalConversion);
convertedAmtTV.setText(finalValue);
} else if (item.getItemId() == 201) {
Intent myIntent = new Intent(MainActivity.this, CustomXchangeRate.class);
startActivity(myIntent);
}
return true;
}
}
Custom ListView Adapter Class
public class CustomAdapter extends BaseAdapter{
String[] resultNames;
String[] resultCodes;
String[] resultRates;
Context context;
private static LayoutInflater inflater = null;
public CustomAdapter(CustomXchangeRate customXchangeRate, String[] names, String[] codes, String[] rates) {
resultNames = names;
resultCodes = codes;
resultRates = rates;
context = customXchangeRate;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter(MainActivity mainActivity, String[] names, String[] codes, String[] rates) {
resultNames = names;
resultCodes = codes;
resultRates = rates;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultNames.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder{
TextView tvName;
TextView tvCode;
TextView tvRate;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder vh = new ViewHolder();
View rowView;
rowView = inflater.inflate(R.layout.activity_custom_adapter, null);
vh.tvName = (TextView) rowView.findViewById(R.id.currencyNameTV);
vh.tvCode = (TextView) rowView.findViewById(R.id.currencyCodeTV);
vh.tvRate = (TextView) rowView.findViewById(R.id.currencyRateTV);
vh.tvName.setText(resultNames[position]);
vh.tvCode.setText(resultCodes[position]);
vh.tvRate.setText(resultRates[position]);
return rowView;
}
}
Would appreciate any help...
The best way to get this JSON inside ur app will be to use Volley :
https://developer.android.com/training/volley/simple.html
Check this link you will find what ur asking for.
Cheers

Android CardsLib, how to add and set custom values in list item?

I'm working with this library:
https://github.com/gabrielemariotti/cardslib
I'm trying to add some text views into cardslib layout item.
Custom text view in layout for single item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/card_main_inner_simple_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/card_main_inner_secondary_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/card_main_inner_name_to_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="THIS TEXT I WANT DYNAMICALLY CHANGE"
android:textColor="#color/list_gray"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
I would like to ask, how can i dynamically set and change this textview with id card_main_inner_name_to_call directly from the code?
CardsLIb Library offers only setTitle methods for header and card but nothing like the setTitleById or something similar.
How can I simple do it?
Thanks for any advice
If you would like to build a card with this layout you can do something like this.
You have to extend your class and override the setupInnerViewElements method
public MyCard extends Card{
public String title1; //just an example... use gettes and setters
public String title2;
public MyCard(Context context){
super(context, R.layout.your_layout);
}
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
TextView tx= (TextView)view.findById(R.id.card_main_inner_simple_title);
tx.setText(title1);
//.... set the other ui elements
}
}
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//......
MyCard card = new Mycard(this);
card.title1 = "....";
card.title2 = "....";
//Set card in the cardView
CardView cardView = (CardView) getActivity().findViewById(R.id.carddemo);
cardView.setCard(card);
}
}
If you are working with a List, you can use the same card class:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//......
ArrayList<Card> cards = new ArrayList<Card>();
for (int i=0;i<50;i++){
MyCard card = new Mycard(this);
card.title1 = "....";
card.title2 = "....";
cards.add(card);
}
CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(this,cards);
CardListView listView = (CardListView) this.findViewById(R.id.myList);
if (listView!=null){
listView.setAdapter(mCardArrayAdapter);
}
}
I've never used this library but from documentation I can suspect that it should be handled just like normal list. In adapter you should fill view and by notifydatasetchanged() you can refresh it.
https://github.com/gabrielemariotti/cardslib/blob/master/doc/QUICKUSAGE.md
EDIT:
I've created very primitive sample below.
Activity:
public class MyActivity extends Activity {
private static final int MAX_LENGTH = 20;
private ArrayList<Card> cards = new ArrayList<Card>();
private CardAdapter arrayAdapter;
private HashMap<Integer, String> optionalValues = new HashMap<Integer, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
arrayAdapter = new CardAdapter(getBaseContext(), cards, optionalValues);
for(int i = 0; i < 10; i++) {
Card card = new Card(getBaseContext());
CardHeader header = new CardHeader(getBaseContext());
header.setTitle("ASDF");
card.setInnerLayout(R.layout.card1_layout);
card.addCardHeader(header);
cards.add(card);
}
CardListView listView = (CardListView) findViewById(R.id.card_list);
listView.setAdapter(arrayAdapter);
Button btn = (Button) findViewById(R.id.btn_rand);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String rnd = random();
Toast.makeText(getBaseContext(), "Generated for 2nd card: " + rnd, Toast.LENGTH_SHORT).show();
optionalValues.put(1, rnd);
arrayAdapter.notifyDataSetChanged();
}
});
}
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++){
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}}
Adapter:
public class CardAdapter extends CardArrayAdapter {
private final LayoutInflater mInflater;
private HashMap<Integer, String> opts;
public CardAdapter(Context context, List<Card> cards, HashMap<Integer, String> optionalValues) {
super(context, cards);
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.opts = optionalValues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(R.id.text1);
if(position == 1 && opts.get(1) != null) {
tv.setText(opts.get(1));
} else {
//items are recycled so let's get back to default values
tv.setText("default");
}
return v;
}}
Main activity 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<Button
android:id="#+id/btn_rand"
android:layout_centerHorizontal="true"
android:text="Randomize 2nd text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<it.gmariotti.cardslib.library.view.CardListView
android:id="#+id/card_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="60dp"
/>
Card inner layout ("card1_layout.xml"):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/carddemo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="12dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:text="default"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text2"
android:text="default2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Unable to select an item in a ListView whose content is set by an Array Adapter

I couldn't select an item on ListView. I use Custom Adapter to set content of ListView. I have set OnItemClickListener of ListView. However, it didn't respond. I appriciate your help. Here is my code:
List Item (connections.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="6dip" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:orientation="vertical" >
<TextView
android:id="#+id/connname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/acc1" />
<TextView
android:id="#+id/conntype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="9sp"
android:text="#string/acctype1" />
</LinearLayout>
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The screen which containt ListView (groupconnections.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:orientation="vertical"
android:id="#+id/textOperLayout">
<TextView
android:id="#+id/connectionsLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/connections"
android:textColor="#color/conn_text"
android:textSize="25sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:background="#color/conn_back"/>
<EditText
android:id="#+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/searchhint"
android:layout_marginTop="10dp"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dip"
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_above="#+id/textOperLayout"
android:id="#+id/listviewlayout">
<ListView
android:id="#+id/connectionlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice" />
</LinearLayout>
<Button
android:id="#+id/addConnCommitButton"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:text="#string/commitToAdd" />
</RelativeLayout>
The related activity (AddMoreConnections.xml):
public class AddMoreConnections extends Activity implements OnItemClickListener{
private ListView mainListView ;
private ArrayAdapter<AbstractHolder> listAdapter ;
private TextView searchConnTextView;
private Button commitButton;
private ArrayList<AbstractHolder> connlist;
private ArrayList<AbstractHolder> listNotOnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Generate list View from ArrayLis
setContentView(R.layout.groupconnections);
addListenerOnSearchConnTextView();
//Initialize properties
mainListView = (ListView) findViewById( R.id.connectionlist );
mainListView.setOnItemClickListener(this);
// Create and populate a List of planet names.
listNotOnView = new ArrayList<AbstractHolder>();
connlist = new ArrayList<AbstractHolder>(5);
Iterator<AbstractHolder> iter = SocialRssModel.holders.values().iterator();
while(iter.hasNext())
connlist.add(iter.next());
// Create ArrayAdapter using the planet list.
listAdapter = new CustomAdapter(this,
R.layout.connlist, connlist);
mainListView.setAdapter( listAdapter );
}
public void addListenerToFinishButton(){
commitButton = (Button) findViewById(R.id.addConnCommitButton);
commitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void addListenerOnSearchConnTextView(){
searchConnTextView = (TextView) findViewById(R.id.searchEditText);
searchConnTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int listNotOnViewsize = listNotOnView.size();
int connlistsize = connlist.size();
for(int i= 0; i < connlistsize; i++){
if(!connlist.get(i).connNameContains(s.toString())){
listNotOnView.add(connlist.remove(i));
i--;
connlistsize--;
}
}
for(int i=0; i < listNotOnViewsize; i++){
if(listNotOnView.get(i).connNameContains(s.toString())){
connlist.add(listNotOnView.remove(i));
i--;
listNotOnViewsize--;
}
}
((CustomAdapter) listAdapter).updateList(connlist);
listAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
Intent i = new Intent(this, CategoryContentViewerController.class);
Bundle b = new Bundle();
b.putInt("AbstractHolderKey", temp.getId());
i.putExtras(b);
startActivity(i);
finish();
}
private class CustomAdapter extends ArrayAdapter<AbstractHolder> {
private ArrayList<AbstractHolder> connectionList;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<AbstractHolder> connList) {
super(context, textViewResourceId, connList);
this.connectionList = new ArrayList<AbstractHolder>();
this.connectionList.addAll(connList);
}
public void updateList(ArrayList<AbstractHolder> connList){
connectionList.clear();
connectionList.addAll(connList);
}
private class ViewHolder {
TextView name;
TextView acctype;
CheckBox sel;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
convertView = vi.inflate(R.layout.connlist, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.connname);
holder.acctype = (TextView) convertView.findViewById(R.id.conntype);
holder.sel = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
AbstractHolder conn = connectionList.get(position);
holder.name.setText(conn.getName());
holder.acctype.setText(conn.getConntype());
holder.sel.setChecked(conn.isSelected());
holder.sel.setTag(conn);
return convertView;
}
}
}
It is related to checkbox item in connections.xml which is the list row item. If I remove checkbox, related listeners responses. I think, it may be thought there is no need a setItemOnClickListener(..) method since each row has a checkbox. Or it is a bug.

ListView declared in layout is null in onCreateView

I'm trying to create a DialogFragment with a ListView and some Buttons. I'm declaring all of them i the layout file and the buttons are working fine but the ListView is null when i use fineViewByID().
Here's my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/category_picker"
android:layout_gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/lvCategorys"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.5" >
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="bottom"
android:layout_weight="0.5"
android:orientation="horizontal" >
<Button
android:id="#+id/btnAddNew"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/cpf_btnAddNew" />
<Button
android:id="#+id/btnConfig"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/cpf_btnConfig" />
</LinearLayout>
</LinearLayout>
And here is the FragmentDialog:
package com.example.spendo.fragments;
imports....
public class CategoryPickerFragment extends DialogFragment implements OnItemClickListener{
private CategoryGroup categoryGroup;
private ListView lvCategorys;
private ArrayAdapter<String> lvAdapter;
private Button btnAddNew, btnConfig;
public CategoryPickerFragment() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_picker, container);
getDialog().setTitle("Hello");
categoryGroup = General.getActiveCategoryGroup(this.getActivity());
System.out.println(categoryGroup);
btnAddNew = (Button) this.getActivity().findViewById(R.id.btnAddNew);
btnConfig = (Button) this.getActivity().findViewById(R.id.btnConfig);
lvCategorys = (ListView) this.getActivity().findViewById(R.id.lvCategorys);
if(lvCategorys == null){ //this returns "lvCategorys is null"
System.out.println("lvCategorys is null");
}else{
System.out.println(lvCategorys + " is not null");
}
lvAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1, categoryGroup.getNameArray());
System.out.println(lvAdapter);
ArrayList<String> nameArray = categoryGroup.getNameArray();
lvAdapter.clear();
for(int i = 0; i < nameArray.size(); i++){
lvAdapter.add((String) nameArray.get(i));
}
lvAdapter.notifyDataSetChanged();
lvCategorys.setAdapter(lvAdapter);
return view;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Does anyone see my problem. (I'm quite new to android, altho i've done some java in the past).
//Sverker
I think you need to replace
btnAddNew = (Button) this.getActivity().findViewById(R.id.btnAddNew);
btnConfig = (Button) this.getActivity().findViewById(R.id.btnConfig);
lvCategorys = (ListView) this.getActivity().findViewById(R.id.lvCategorys);
with
btnAddNew = (Button) view.findViewById(R.id.btnAddNew);
btnConfig = (Button) view.findViewById(R.id.btnConfig);
lvCategorys = (ListView) view.findViewById(R.id.lvCategorys);

Categories

Resources