Getting reference for a inner control in a ListView - android

I am new in android and I have read some tutos about custom ListView and I am doing an app to manipulate data I resume my problem with this litte app. the screen is this:
in this there are a listview and each item have a TextView and a EditText the one last control is for the user input a amount I need when the user press the button clear first save de amount info in the arraylist and then clear the fields. how I approach this
my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.rimacy.preguntalistview.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView1"
android:layout_weight="1"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/btnClear"/>
</LinearLayout>
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="100dip"
android:layout_height="wrap_content"
android:text="item"
android:id="#+id/tv1" />
<EditText
android:layout_width="200dip"
android:layout_height="wrap_content"
android:hint="Input amount"
android:id="#+id/edit1"
android:layout_weight="1"
android:inputType="number"/>
</LinearLayout>
MainActivity.java
package com.rimacy.preguntalistview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Inventory> data = new ArrayList<>();
data.add(new Inventory("candies",0));
data.add(new Inventory("milk",0));
data.add(new Inventory("soda",0));
data.add(new Inventory("paper",0));
data.add(new Inventory("bags",0));
//... the items are unknow in run time
MyAdapter adp = new MyAdapter(this,R.layout.listview_item,data);
ListView listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(adp);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set de value of each EditText to "amount" field in each object in the ArrayList "data"
// perform a clear of all EditText in the listview
// set the focus in the firs EditText
}
});
}
class Inventory{
String name;
Integer amount;
public Inventory(String name, Integer amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
}
class MyAdapter extends ArrayAdapter<Inventory>{
private ArrayList<Inventory> items;
public MyAdapter(Context context, int resource, ArrayList<Inventory> items) {
super(context, resource, items);
this.items = items;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View v=convertView;
TextView editText;
if (v == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.listview_item, null);
}
editText = (TextView)v.findViewById(R.id.tv1);
editText.setText(items.get(position).getName());
return v;
}
}
}
update
I do this
**
package com.rimacy.preguntalistview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ArrayList<Inventory> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data.add(new Inventory("candies",0));
data.add(new Inventory("milk",0));
data.add(new Inventory("soda",0));
data.add(new Inventory("paper",0));
data.add(new Inventory("bags",0));
//... the items are unknow in run time
final MyAdapter adp = new MyAdapter(this,R.layout.listview_item,data);
final ListView listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(adp);
adp.notifyDataSetChanged();
Button btnClear = (Button) findViewById(R.id.btnClear);
if (btnClear!= null){
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set de value of each EditText to "amount" field in each object in the ArrayList "data"
// perform a clear of all EditText in the listview
// set the focus in the firs EditText
for (Inventory i:data){
i.getTxt().setText("");
}
adp.notifyDataSetChanged();
}
});
}
}
class Inventory{
String name;
Integer amount;
EditText txt;
public void setName(String name) {
this.name = name;
}
public EditText getTxt() {
return txt;
}
public void setTxt(EditText txt) {
this.txt = txt;
}
public Inventory(String name, Integer amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
}
class MyAdapter extends ArrayAdapter<Inventory>{
private ArrayList<Inventory> items;
public MyAdapter(Context context, int resource, ArrayList<Inventory> items1) {
super(context, resource, items1);
items = items1;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View v=convertView;
TextView editText;
EditText txt;
if (v == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.listview_item, null);
}
txt = (EditText)v.findViewById(R.id.edit1);
editText = (TextView)v.findViewById(R.id.tv1);
items.get(position).setTxt(txt);
editText.setText(items.get(position).getName());
return v;
}
}
}
added a new member in the Inventory Class to store a reference of the editText wich is assigned in the getView event and with the getTxt methos recall this reference and call the setText method with empty string but it only works when I press the button for twice time why??

Related

Dynamically displaying items in List View that is entered by User

I have two Edit Text, in which user enters their first name and surname.
I want to display the names and surnames below in a list view.
So, if users enters name and surname for the first time it should display in row 1 of list view, and for 2nd entry it should display in row 2 of the list veiw.
My problem is that when I am doing a new entry, it replaces the text in the 1st row of list view and doesn't display in 2nd or next rows in list view.
Please see my code.
It will be great if you can help me.
below is my Java code
''' package com.nitin.inflaterproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ListView list;
EditText editText1, editText2;
LinearLayout linearLayoutMain;
MyAdapter adapter;
int counter;
public void addData(View view){
String text1 = editText1.getText().toString();
String text2 = editText2.getText().toString();
if(text1.equals("") || text2.equals("")){
Toast.makeText(this, "Please enter required field", Toast.LENGTH_SHORT).show();
}else{
counter++;
Toast.makeText(this, "Counter value is " + counter, Toast.LENGTH_SHORT).show();
adapter = new MyAdapter(this, text1, text2,counter);
list.setAdapter(adapter);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayoutMain = (LinearLayout)findViewById(R.id.linearLayoutMain);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
list = (ListView)findViewById(R.id.listViewMain);
counter = 0;
}
}'''
And then Base Adapter Code
'''package com.nitin.inflaterproject;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
class MyList{
String text1;
String text2;
MyList(String text1, String text2){
this.text1 = text1;
this.text2 = text2;
}
}
class MyAdapter extends BaseAdapter {
ArrayList<MyList> list;
private Context context;
private int count;
MyAdapter(Context c, String text1, String text2, int counter){
count = counter - 1;
context = c;
list = new ArrayList<MyList>();
String[] textstring1 = new String[counter];
String[] textstring2 = new String[counter];
textstring1[count] = text1;
textstring2[count] = text2;
list.add(new MyList(textstring1[count], textstring2[count]));
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.myadapter, parent, false);
}
TextView text1 = (TextView)row.findViewById(R.id.textView1);
TextView text2 = (TextView)row.findViewById(R.id.textView2);
MyList temp = list.get(position);
text1.setText(temp.text1);
text2.setText(temp.text2);
return row;
}
}'''
my XML Code
Main Activity
'''<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="#string/enter_name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="#string/enter_surname"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText1" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="68dp"
android:onClick="addData"
android:padding="10dp"
android:text="#string/add"
android:textSize="20sp"
app:layout_constraintStart_toEndOf="#+id/editText1"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/linearLayoutMain"
android:layout_width="311dp"
android:layout_height="468dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:background="#77BBCC00"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText2">
<ListView
android:id="#+id/listViewMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
'''
XML code for Layout that needs to be inflated
'''<?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="wrap_content"
android:padding="16dp"
android:id="#+id/linearLayout">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp"
android:background="#99BBCC00"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="24sp"
android:background="#BBCC00"/>
</LinearLayout>'''
I solved it by changing the code:
'''package com.nitin.inflaterproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView list;
EditText editText1, editText2;
LinearLayout linearLayoutMain;
MyAdapter adapter;
int counter;
int count = 0;
ArrayList<MyList> list1;
public void addData(View view){
String text1 = editText1.getText().toString();
String text2 = editText2.getText().toString();
if(text1.equals("") || text2.equals("")){
Toast.makeText(this, "Please enter required field", Toast.LENGTH_SHORT).show();
}else{
//counter++;
//Toast.makeText(this, "Counter value is " + counter, Toast.LENGTH_SHORT).show();
// adapter = new MyAdapter(this, text1, text2,counter);
//list.setAdapter(adapter);
counter++;
count = counter - 1;
String[] textstring1 = new String[counter];
String[] textstring2 = new String[counter];
textstring1[count] = text1;
textstring2[count] = text2;
list1.add(new MyList(textstring1[count], textstring2[count]));
adapter = new MyAdapter(this, list1);
list.setAdapter(adapter);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1 = new ArrayList<MyList>();
linearLayoutMain = (LinearLayout)findViewById(R.id.linearLayoutMain);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
list = (ListView)findViewById(R.id.listViewMain);
counter = 0;
}
}
class MyList{
String text1;
String text2;
MyList(String text1, String text2){
this.text1 = text1;
this.text2 = text2;
}
}'''
'''package com.nitin.inflaterproject;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
class MyAdapter extends BaseAdapter {
ArrayList<MyList> list;
private Context context;
MyAdapter(Context c, ArrayList<MyList> list1){
context = c;
list = new ArrayList<MyList>(list1);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.myadapter, parent, false);
}
TextView text1 = (TextView)row.findViewById(R.id.textView1);
TextView text2 = (TextView)row.findViewById(R.id.textView2);
MyList temp = list.get(position);
text1.setText(temp.text1);
text2.setText(temp.text2);
return row;
}
}'''

Change color and size of Textview in custom Listview having custom adapter and custom layout file

I am having problem with changing color of Textview in custom Listview.
My xml file is column.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textSize="30dp"
android:visibility="gone"/>
<TextView
android:id="#+id/cname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25dp"
android:textColor="#f60505" />
<TextView
android:id="#+id/amt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textColor="#2ec31d"
android:textAlignment="center" />
</LinearLayout>
and ListViewAdapter.java goes like this
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by XYZ on 06-05-2016.
*/
public class ListViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String,String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String,String>>list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.colunm_row,null);
holder = new ViewHolder();
holder.textFirst=(TextView)convertView.findViewById(R.id.cid);
holder.textSecond=(TextView)convertView.findViewById(R.id.cname);
holder.textThird=(TextView)convertView.findViewById(R.id.amt);
txtFirst = (TextView) convertView.findViewById(R.id.cid);
txtSecond = (TextView)convertView.findViewById(R.id.cname);
txtThird = (TextView) convertView.findViewById(R.id.amt);
convertView.setTag(holder);
}else {
holder =(ViewHolder)convertView.getTag();
holder.textFirst.setText("");
holder.textSecond.setText("");
holder.textThird.setText("");
}
HashMap<String,String> map= list.get(position);
/* txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));*/
holder.textFirst.setText(map.get(FIRST_COLUMN));
holder.textSecond.setText(map.get(SECOND_COLUMN));
holder.textThird.setText(map.get(THIRD_COLUMN));
return convertView;
}
static class ViewHolder{
TextView textFirst;
TextView textSecond;
TextView textThird;
}
}
DisplayActivity :
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AccDisplay extends AppCompatActivity {
private ArrayList<HashMap<String,String>> arrayList;
Cursor c;
SQLiteDatabase db;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acc_display);
ListView listView = (ListView)findViewById(R.id.AcclistView);
arrayList = new ArrayList<HashMap<String, String>>();
db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);
c=db.rawQuery("select c.c_id ,c.c_name, ((select CASE WHEN (sum(cr.amount)) IS Null THEN 0 ELSE sum(cr.amount) END from credit_master cr where c.c_id=cr.c_id) ) - ((select CASE WHEN (sum(d.amount)) IS NULL THEN 0 ELSE sum(d.amount) END from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c ORDER BY c.c_name ASC",null);
//c=db.rawQuery("select c.c_id ,c.c_name, ((select sum(cr.amount) from credit_master cr where c.c_id=cr.c_id) ) - ((select sum(d.amount) from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c",null);
try {
if (c!=null){
if(c.moveToFirst()){
Map<String,String> tem = new HashMap<String ,String>();
tem.clear();
arrayList.clear();
listView.setAdapter(null);
int cnt = c.getCount();
Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
do {
tem = new HashMap<String,String>();
tem.clear();
tem.put(FIRST_COLUMN, c.getString(0));
tem.put(SECOND_COLUMN,c.getString(1));
tem.put(THIRD_COLUMN,c.getString(2));
arrayList.add((HashMap<String, String>) tem);
}while (c.moveToNext());
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),"Error"+e,Toast.LENGTH_LONG).show();
}
ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) (view.findViewById(R.id.cid));
int str = Integer.parseInt(tv.getText().toString());
Toast.makeText(AccDisplay.this,"Clicked"+str,Toast.LENGTH_LONG).show();
Intent intent = new Intent(AccDisplay.this,Details.class);
intent.putExtra("name",str);
startActivity(intent);
}
});
}
protected void onRestart(){
super.onRestart();
Intent inte = getIntent();
finish();
startActivity(inte);
}
}
I am using same layout file for three different activities.
I want to display different color of each TextView in Different Activity.
I have tried this but didn't work
LayoutInflator inflator = (LayoutInflator)getSystemService(Context.LAYOUT_INFLATOR_SERVICE);
View vi = inflator.inflate(R.layout.column,null);
TextView tv = (TextView) vi.findViewById(R.id.amt);
tv.setTextColor(Color.BLACK);
I can change color of TextView in OnItemClickListener but i want to display color while displaying data.
I am having Debit/Credit activity which uses same Adapter class and column.xml layout for displaying data in listview.
I want to display TextView1 in black color font and TextView2 in Green color with big font size in Activity 1. and different color in different activity.
You can pass different flags in adapter constructor to adapter for identifying activity if same adapter you are using for other activities, and can put conditions according to the flag set colors to the TextView in adapter programmatically. textView.setTextColor(put_your_color);

How to add Listeners of Dynamic Check Boxes in Simple Adapter

I have dynamic CheckBoxes and now I want to check which CheckBox clicked or not
AdditionalInformation.Java File Here Simple Adapter is defined :
package com.example.ahmad.cvbuilder21;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AdditionalInformation extends ActionBarActivity {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_infromation);
cb=(CheckBox)findViewById(R.id.additionalchk);
ABC s = ABC.getSingletonObject();
String[][] str = s.getString();
ListView lv=((ListView)findViewById(R.id.additionallist));
String[] additionalOptions={"Add your Picture","Add Experince / Project","Add Reference","Add Skills / Languages"};
String[] txtViewNames={"options"};
List<HashMap<String,String>>list=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < additionalOptions.length; i++) {
HashMap<String, String> map= new HashMap<String, String>();
map.put("options", additionalOptions[i]);
list.add(map);
}
SimpleAdapter simpleAdpt = new SimpleAdapter(this, list, R.layout.mylayout2,txtViewNames , new int[] {R.id.additionaltxt1});
lv.setAdapter(simpleAdpt);
}
public void additionalData(View view1)
{
if(cb.isChecked())
{
cb.findViewById(R.id.additionalchk).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast toast = Toast.makeText(getApplicationContext(), "Checked",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();
}
}
);
}
else{}
}
}
AdditionalInformation.xml file: where additionalData function is called to
check which CheckBox clicked.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Additional Options:"
android:id="#+id/additionalBtn"
/>
<ListView
android:layout_below="#id/additionalBtn"
android:layout_centerHorizontal="true"
android:id="#+id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
<Button
android:layout_below="#id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to CV"
android:onClick="additionalData"
/>
</RelativeLayout>
mylayout2.xml file where I define the controls for simple adapter:
<?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:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/additionaltxt1"
/>
<CheckBox
android:layout_alignParentRight="true"
android:layout_alignRight="#id/additionaltxt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="#+id/additionalchk"
/>
</RelativeLayout>
What you actually need to do is create a custom adapter. In that custom you could listen for checkbox event at the right position.
Here is an example:
public class ListEmployeesAdapter extends BaseAdapter {
public List<Employees> items;
Context c;
public ListEmployeesAdapter(Context c, List<Employees> items) {
this.c = c;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
c.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.employee_item, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(items.get(position).name);
name.setOnCLickListener(new OnClickListener(){
#Override
public void onClick(){
//listen to the click
}
});
return convertView;
}
}
Just replace the the layout with you layout and call checkbox instead of TextView and you are good to go.

Custom ListView not showing any items

I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}

How to use a layout as empty view for a listview when the adapter has zero elements

list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab on icon to start a Campaign" />
</LinearLayout>
Activity+list_demonstration.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="130dp" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
I m trying to make an listview that is empty in the starting of the application.in which a textview will give information to tab on icon..,and when user tab and create an app.the data shown in the listview..bt listview is giving an error ,how to solve it..
Demo.java // custom adapter
package com.example.smscampaign;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.text1);
ImageView btn=(ImageView)v.findViewById(R.id.imageView1);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.text1);
return v;
}
}
Campaign_Details.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
listview .setEmptyView(emptyText);
// listview.setEmptyView((LinearLayout) findViewById(R.id.emptyText));
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < data.length(); ++i) {
selectedAdapter = new Demo(this,values);
selectedAdapter.setNotifyOnChange(true);
listview.setAdapter(selectedAdapter);
list.add(data);
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE:
You have done everything wrong. you need to change as follows.
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, values);
this.context = context;
this.values = values;
}
In Campaign_Details Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
According to your question finally you need to change here from
ListView listview = (ListView) findViewById(R.id.listView1);
to
ListView listview = (ListView) findViewById(R.id.listView);

Categories

Resources