Limit number of Items in ListView - android

I am developing an application where a user will be able to search their phone contacts through an AutocompleteTextView, then add those contacts to a ListView. So far I have been able to do this, but now I want to limit the amount of contacts the user can add to five. This way there will only be five contacts. How can I set the limit to five, and display an alert dialog if the user tries to upload more?
Here is my main java code that reads the users phone contacts and adds them to the listview after clicking the "add contact" button.
package com.example.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
final ArrayList<String> phoneList = new ArrayList<String>();
FancyAdapter aa=null;
//Sets contact array for autocomplete
private ArrayList<Map<String, String>> mPeopleList;
private SimpleAdapter mAdapter;
private AutoCompleteTextView mTxtPhoneNo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPeopleList = new ArrayList<Map<String, String>>();
PopulatePeopleList();
mTxtPhoneNo = (AutoCompleteTextView) findViewById(R.id.mmWhoNo);
mAdapter = new SimpleAdapter(this, mPeopleList, R.layout.custcontview ,new String[] { "Name", "Phone" , "Type" }, new int[] { R.id.ccontName, R.id.ccontNo, R.id.ccontType });
mTxtPhoneNo.setAdapter(mAdapter);
mTxtPhoneNo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View arg1, int index,
long arg3) {
Map<String, String> map = (Map<String, String>) av.getItemAtPosition(index);
String name = map.get("Name");
String number = map.get("Phone");
mTxtPhoneNo.setText(""+name+"\n"+number+"");
}
});
}
public void PopulatePeopleList()
{
mPeopleList.clear();
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (people.moveToNext())
{
String contactName = people.getString(people.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
String contactId = people.getString(people.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = people.getString(people.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ((Integer.parseInt(hasPhone) > 0))
{
// You now have the number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
//store numbers and display a dialog letting the user select which.
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
String numberType = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
Map<String, String> NamePhoneType = new HashMap<String, String>();
NamePhoneType.put("Name", contactName);
NamePhoneType.put("Phone", phoneNumber);
if(numberType.equals("0"))
NamePhoneType.put("Type", "Work");
else
if(numberType.equals("1"))
NamePhoneType.put("Type", "Home");
else if(numberType.equals("2"))
NamePhoneType.put("Type", "Mobile");
else
NamePhoneType.put("Type", "Other");
//Then add this map to the list.
mPeopleList.add(NamePhoneType);
}
phones.close();
}
}
people.close();
aa=new FancyAdapter();
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText mmWhoNo = (EditText)findViewById(R.id.mmWhoNo);
myListView.setAdapter(aa);
Button btnSimple = (Button) findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//adds contact
phoneList.add(0, mmWhoNo.getText().toString());
//update the view
aa.notifyDataSetChanged();
}
});
}
//ArrayAdapter is extended and this allows custom views and other more complicated functions
class FancyAdapter extends ArrayAdapter<String> {
FancyAdapter() {
super(MainActivity.this, android.R.layout.simple_list_item_1, phoneList);
}
public View getView(int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
//the if statement checks for recycled items and saves resources and processing
if (convertView==null) {
LayoutInflater inflater=getLayoutInflater();
convertView=inflater.inflate(R.layout.custom_list_item, null);
holder=new ViewHolder(convertView);
//caches the result of the findViewById function
holder.note = (TextView) convertView.findViewById(R.id.ccontName);
//stores tag on the view
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.note.setText(phoneList.get(position));
return(convertView);
}
}
class ViewHolder {
public TextView note=null;
ViewHolder(View row) {
note=(TextView)row.findViewById(R.id.ccontName);
}
void populateFrom(String r) {
note.setText(r);
}
}
}
Here is my main xml page with the AutoCompleteTextView, button, and listview
<?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" >
<AutoCompleteTextView
android:id="#+id/mmWhoNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Type Here to Add an Emergency Contact"
>
</AutoCompleteTextView>
<Button
android:id="#+id/btnSimple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/mmWhoNo"
android:text="Add Contact" />
<ListView
android:id="#+id/myListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/btnSimple" >
</ListView>
</RelativeLayout>
Here is my xml for my custom listview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="#+id/imageView01"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/ccontName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/ccontName"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/imageView01"
android:gravity="center_vertical"
android:text="Example application"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
And here is the xml for my custom view for the AutoCompleteTextView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ccontName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textColor="#A5000000"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/ccontNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/ccontName"
android:text="Medium Text"
android:textColor="#A5000000"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ccontType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/ccontNo"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:text="Small Text"
android:textColor="#A5000000"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>

call .setDropDownHeight(int height)

Related

Display single record from ListView / ListAdapter from sql database

I do a bit of travelling and I wanted to create an app that allowed me to save taxi bookings into a database. I have only added a few fields to give me an idea how this all works. I'm quite new to programming and followed a number of tutorials to create an app that allows me to take a csv file and upload it to the app database. This works well and I have no problems displaying the data.
I managed to get it to both use Toast and alert to bring up windows with data in, but only 6 fields... I need to have all 16 showing...
I have made some ground on this but still having the Application termination problems when I click on the list items.
I have tried to make an Intent to call the new view results table by new intent in TaxiDetails. no joy... All help appreciated.
Code as below - All help appreciated and thanks in advance....
MainActivity.java
package com.stravides.jdw;
import android.app.AlertDialog;
import android.content.Context;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
TextView lbl;
DBController controller = new DBController(this);
Button btnimport;
Button btnphone;
Button btnclear;
ListView lv;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;
final Context context = this;
protected Cursor kursor;
protected ListAdapter adapter;
protected SQLiteDatabase db;
public AdapterView.OnItemClickListener mMessageClickedHandler = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Intent intent = new Intent("com.stravides.jdw.TaxiDetails.class");
Cursor kursor = (Cursor) adapter.getItem(position);
intent.putExtra("TAXI_ID", kursor.getInt(kursor.getColumnIndex("_id")));
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lbl = (TextView) findViewById(R.id.txtresulttext);
btnimport = (Button) findViewById(R.id.btnupload);
btnphone = (Button) findViewById(R.id.btnphone);
btnclear = (Button) findViewById(R.id.btnclear);
lv = getListView();
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("gagt/sdf");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity that can handle file selection. Showing alternatives.");
}
}
});
btnclear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "taxiinfo";
db.execSQL("delete from " + tableName);
myList = controller.getAllProducts();
if (myList.size() == 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,R.layout.v, new String[]
{"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks"}, new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
setListAdapter(adapter);
lbl.setText("Data Cleared");
}
}
});
btnphone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uri = "tel:" + "0031251491418";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
myList= controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks"}, new int[]{
R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo, R.id.txttaxibFlightNum, R.id.txttaxibFlightDest, R.id.txttaxibPassenger, R.id.txttaxibEmail, R.id.txttaxibTelno, R.id.txttaxibMobNo, R.id.txttaxibCostCentre, R.id.txttaxibPersNo, R.id.txttaxibCombine, R.id.txttaxibNumPass, R.id.txttaxibRemarks});
setListAdapter(adapter);
lbl.setText("");
}
lv.setOnItemClickListener(mMessageClickedHandler);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "taxiinfo";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 16);
String bID = str[0];
String bDate = str[1];
String bTime = str[2];
String bFrom = str[3];
String bTo = str[4];
String bFlightNum = str[5];
String bFlightDest = str[6];
String bPassenger = str[7];
String bEmail = str[8];
String bTelno = str[9];
String bMobNo = str[10];
String bCostCentre = str[11];
String bPersNo = str[12];
String bCombine = str[13];
String bNumPass = str[14];
String bRemarks = str[15];
contentValues.put("bID", bID);
contentValues.put("bDate", bDate);
contentValues.put("bTime", bTime);
contentValues.put("bFrom", bFrom);
contentValues.put("bTo", bTo);
contentValues.put("bFlightNum", bFlightNum);
contentValues.put("bFlightDest", bFlightDest);
contentValues.put("bPassenger", bPassenger);
contentValues.put("bEmail", bEmail);
contentValues.put("bTelno", bTelno);
contentValues.put("bMobNo", bMobNo);
contentValues.put("bCostCentre", bCostCentre);
contentValues.put("bPersNo", bPersNo);
contentValues.put("bCombine", bCombine);
contentValues.put("bNumPass", bNumPass);
contentValues.put("bRemarks", bRemarks);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
}
} else {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
}
}
myList= controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"bID", "bDate", "bTime", "bFrom", "bTo","bFlightNum", "bFlightDest", "bPassenger", "bEmail", "bTelno", "bMobNo", "bCostCentre", "bPersNo", "bCombine", "bNumPass", "bRemarks"}, new int[]{
R.id.txttaxibID, R.id.txttaxibDate, R.id.txttaxibTime,R.id.txttaxibFrom, R.id.txttaxibTo, R.id.txttaxibFlightNum, R.id.txttaxibFlightDest, R.id.txttaxibPassenger, R.id.txttaxibEmail, R.id.txttaxibTelno, R.id.txttaxibMobNo, R.id.txttaxibCostCentre, R.id.txttaxibPersNo, R.id.txttaxibCombine, R.id.txttaxibNumPass, R.id.txttaxibRemarks});
}
}
}
DBController.java
package com.stravides.jdw;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public DBController(Context applicationcontext) {
super(applicationcontext, "jdwtaxi.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS taxiinfo ( Id INTEGER PRIMARY KEY, bID TEXT,bDate TEXT, bTime TEXT,bFrom TEXT, bTo TEXT, bFlightNum TEXT, bFlightDest TEXT, bPassenger TEXT, bEmail TEXT, bTelno TEXT, bMobNo TEXT, bCostCentre TEXT, bPersNo TEXT, bCombine TEXT, bNumPass TEXT, bRemarks TEXT)";
database.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase database, int version_old,int current_version) {
String query;
query = "DROP TABLE IF EXISTS taxiinfo";
database.execSQL(query);
onCreate(database);
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> taxiList;
taxiList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM taxiinfo";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("bID", cursor.getString(1));
map.put("bDate", cursor.getString(2));
map.put("bTime", cursor.getString(3));
map.put("bFrom", cursor.getString(4));
map.put("bTo", cursor.getString(5));
map.put("bFlightNum", cursor.getString(6));
map.put("bFlightDest", cursor.getString(7));
map.put("bPassenger", cursor.getString(8));
map.put("bEmail", cursor.getString(9));
map.put("bTelno", cursor.getString(10));
map.put("bMobNo", cursor.getString(11));
map.put("bCostCentre", cursor.getString(12));
map.put("bPersNo", cursor.getString(13));
map.put("bCombine", cursor.getString(14));
map.put("bNumPass", cursor.getString(15));
map.put("bRemarks", cursor.getString(16));
taxiList.add(map);
} while (cursor.moveToNext());
}
return taxiList;
}
}
TaxiDetails.java
package com.stravides.jdw;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
/**
* Created by Ken on 09/08/2015.
*/
public class TaxiDetails extends Activity {
protected TextView bID;
protected TextView bDate;
protected TextView bTime;
protected TextView bFrom;
protected TextView bTo;
protected TextView bFlightNum;
protected TextView bFlightDest;
protected TextView bPassenger;
protected TextView bEmail;
protected TextView bTelno;
protected TextView bMobNo;
protected TextView bCostCentre;
protected TextView bPersNo;
protected TextView bCombine;
protected TextView bNumPass;
protected TextView bRemarks;
protected int taxiPos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultstable);
taxiPos = getIntent().getIntExtra("TAXI_ID", 0);
SQLiteDatabase db = (new DBController(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT bID, bDate, bCombine FROM taxiinfo WHERE bID = ?", new String[]{""+taxiPos});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
bID = (TextView) findViewById(R.id.txttaxibID2);
bID.setText(cursor.getString(cursor.getColumnIndex("bID")));
bDate = (TextView) findViewById(R.id.txttaxibDate2);
bDate.setText(cursor.getString(cursor.getColumnIndex("bDate")));
bCombine = (TextView) findViewById(R.id.txttaxibCombine2);
bCombine.setText(cursor.getString(cursor.getColumnIndex("bCombine")));
}
}
}
activity_main.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"
android:orientation="vertical"
android:weightSum="9"
android:background="#FFC7C7C7"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Booking Details"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0.24" />
<!-- divider -->
<LinearLayout
android:id="#+id/lvcontainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:padding="1dp"
android:background="#FFC7C7C7"
android:weightSum="6">
<TextView
android:id="#+id/txttaxibID"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".8"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp"
android:clickable="false" />
<TextView
android:id="#+id/txttaxibDate"
android:layout_width="15dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:padding="3dp"
android:text="Date"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".8"
android:gravity="left"
android:text="Time"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibFrom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="From"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="To"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibCombine"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Combine"
android:padding="1dp"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/lvcontainer"
android:layout_weight="6.59"
android:clickable="false"></ListView>
<TextView
android:id="#+id/txtresulttext"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="5dp"
android:layout_below="#android:id/list"
android:layout_marginTop="2dp"
android:layout_weight="0.5"
android:gravity="left"
android:text=""
android:textColor="#FFF55F54"
android:textSize="10sp"
android:textStyle="italic|bold"></TextView>
<LinearLayout
android:id="#+id/lvbottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="1">
<Button
android:id="#+id/btnupload"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33"
android:gravity="center"
android:text="UPLOAD"
android:textColor="#ffffff"
android:background="#1083f5"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnclear"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.33"
android:gravity="center"
android:text="CLEAR"
android:textColor="#ffffff"
android:background="#1003f5"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnphone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.34"
android:gravity="center"
android:text="CALL JDW"
android:textColor="#ffffff"
android:background="#ffff0000"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
v.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="vertical" >
<LinearLayout
android:id="#+id/lvh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:scrollbars="horizontal"
android:background="#ffe6e6e6"
android:weightSum="5"
android:minHeight="30dp"
android:measureWithLargestChild="false"
android:longClickable="false">
<TextView
android:id="#+id/txttaxibID"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Ref"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibDate"
android:layout_width="15dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:padding="3dp"
android:text="Date"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTime"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="Time"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibFrom"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="From"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
<TextView
android:id="#+id/txttaxibTo"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="To"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
resultstable.xml
<TextLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/status2"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:text="Booking Details"
android:textColor="#890000"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/txttaxibID2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip"
/>
<TextView
android:id="#+id/txttaxibDate2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip" />
<TextView
android:id="#+id/txttaxibCombine2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_marginLeft="20dip" />
</TextLayout>
csv data for testing
372187,20/09/2015,20:00,Schiphol Taxi Counter Jan de Wit Group,Hotel Lion D'or Golden Tulip,KL1064,Cardiff,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,1,
372188,21/09/2015,08:00,Hotel Lion D'or Golden Tulip,3H.18 Dudokhuis Hoofdingang,None,None,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,1,Have to be in office by 8:30!!!
372189,21/09/2015,17:30,3H.18 Dudokhuis Hoofdingang,Hotel Lion D'or Golden Tulip,None,None,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,1,
372190,22/09/2015,08:00,Hotel Lion D'or Golden Tulip,3H.18 Dudokhuis Hoofdingang,None,None,Ken Midgley,me#home.com,Ken Midgley,441234567889,41024830,1044889,None,2,Mike Smith. Have to be in office by 8:30!!!
You need an OnItemClickListener set on your ListView. Here is a simple tutorial how this works - http://www.mkyong.com/android/android-listview-example/
After you learn to intercept and handle the event, you can start thinking about navigating to a details activity, or opening a details dialog.
I suggest you go through all of the basic tutorials in http://developer.android.com - all you need is there.
I do something like this:
public void onClickList(final ListView list) {
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setCancelable(false);
alert.setMessage("youre message");
final AlertDialog.Builder ok = alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
//add your code here
dialog.dismiss();
}
});
alert.show();
}
});
}
Where the list is the ListView object you create. You can send to this method onClickListener() your ListView to manage the popup. By the way, you can create your own xml layout to render a custom view.
Thank you for your assistance on the above - I managed now to resolve this issue.
The problem was thinking too hard about passing the position of the click....
The MainActivity.java needs the following...
public AdapterView.OnItemClickListener mMessageClickedHandler = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Intent intent = new Intent(MainActivity.this,TaxiDetails.class);
intent.putExtra("TAXI_ID", position);
startActivity(intent);
}
};
The TaxiDetails.java then can pick up the extra info in the intent
taxiPos = getIntent().getIntExtra("TAXI_ID", 0);
taxiPos=taxiPos+1;
SQLiteDatabase db = (new DBController(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM taxiinfo WHERE Id = ?", new String[]{""+taxiPos});
if (cursor.getCount() == 1)

ListviewArray Adaptor returns null pointer exception in customized layout

My problem is, I could not show the ArrayList data in ListView. My need is I have to show listview in my customized layout file center part. I have used custom adapter to show the listview. I am retrieving ListArray<String> data from my local database. Listview adapter does not receive my database ArrayList<String> item. I have created separate class for ListAdaptor and also created a constructor for ListAdaptor.
I can able to show by extending ListActivity, But I have use CustomAdaptor. The following are my code, Please tell me where I did wrong code
Layout file(Dashboard_Notify.xml)
This is my customized layout xml file, In this page center i want to show listview data
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="51dp"
android:background="#drawable/dash_nav_bg_widout_brk_line"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:src="#drawable/dash_nav_bg1_not_select" />
<ImageView
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:src="#drawable/dash_nav_sep1" />
<ImageView
android:id="#+id/imageButton1"
android:layout_marginLeft="5dp"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_marginTop="0dp"
android:src="#drawable/dash_nav_bg1_bday" />
<ImageView
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="4dp"
android:layout_marginTop="0dp"
android:src="#drawable/dash_nav_sep1" />
<ImageView
android:id="#+id/imageButton1"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginTop="0dp"
android:src="#drawable/dash_nav_bg1_sms" />
</LinearLayout>
<LinearLayout
android:layout_width="280dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="20dp"
android:background="#drawable/dash_midl_bg_notify"
android:layout_height="280dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:paddingTop="8dp"
android:layout_marginLeft="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="29 MAY" />
<View
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/btnAdd"
android:background="#8DB3E1" />
<ListView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/a"
android:divider="#8DB3E1"
android:dividerHeight="2dp"
android:headerDividersEnabled="true" />
</LinearLayout>
<ImageButton
android:layout_marginLeft="70dp"
android:layout_marginTop="30dp"
android:id="#+id/imageButton2"
android:layout_width="180dp"
android:layout_height="37dp"
android:src="#drawable/clear" />
</LinearLayout>
***//ListViewItem Row xml(BdayLlist.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"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="127dp"
android:layout_marginTop="60dp" >
<TableRow
android:layout_marginTop="20dp"
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/test_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="id" />
<TextView
android:id="#+id/test_name"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="vennila" />
<TextView
android:id="#+id/test_Loc"
android:layout_marginLeft="120dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
</LinearLayout>
</TableRow>
<TableRow
android:layout_marginTop="20dp"
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/test_BDay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bday" />
<TextView
android:id="#+id/test_Day"
android:layout_marginLeft="-60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wednessday" />
</TableRow>
<TableRow
android:layout_marginTop="20dp"
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/test_toDay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Today" />
<TextView
android:layout_marginLeft="-60dp"
android:id="#+id/test_Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="May 7" />
</TableRow>
</TableLayout>
</LinearLayout>
MainActivity class(TodayList.java)
package com.example.sampleparse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class TodayList extends Activity{
SQLiteDatabase db;
DbHelper dbh;
ListView lv;
private ArrayList<String> user_loc = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_id = new ArrayList<String>();
ArrayList<String> list= new ArrayList<String>();
TestAdaptor ta;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard_notify);
this.lv=(ListView) findViewById(R.id.List);
try{
// BdayList();
//Bname();
// displayData();
dbh=new DbHelper(this);
db=dbh.getWritableDatabase();
list=dbh.Bname();
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
// System.out.println(stockArr.toString());
/* user_loc=dbh.BLocation();
String[] loc = new String[user_loc.size()];
for(String l : loc)
System.out.println(l);*/
//ta = new TestAdaptor(TodayList.this, stockArr,loc );
ListAdapter la = new ListAdapter(getApplicationContext(), list);
lv.setAdapter(la);
/* ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.bdaylist, R.id.test_name, stockArr);*/
// setListAdapter(adapter);
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
public void Bname(){
dbh=new DbHelper(this);
db=dbh.getWritableDatabase();
list=dbh.Bname();
listAdapter = new ArrayAdapter<String>(this, R.layout.bdaylist, list);
Toast.makeText(getApplicationContext(), list.toString(), Toast.LENGTH_LONG).show();
lv.setAdapter(listAdapter);
}
#Override
protected void onResume() {
super.onResume();
//displayData();
}
//worked listView(){ code
//should extends listActivity
public void list(){
dbh=new DbHelper(this);
db=dbh.getWritableDatabase();
list=dbh.Bname();
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
// System.out.println(stockArr.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.bdaylist, R.id.test_name, stockArr);
//should uncomment the line
//setListAdapter(adapter);
}
public void displayData() {
db = dbh.getWritableDatabase();
Calendar c = Calendar.getInstance();
SimpleDateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate1 = df1.format(c.getTime());
String sub = formattedDate1;
String s1=sub.substring(0, 5);
ArrayList<String> test=new ArrayList<String>();
String selectQuery="SELECT * FROM " + dbh.TABLE_CONTACTS + " where dob = '" + s1 +"'";
Cursor mCursor = db.rawQuery(selectQuery, null);
user_id.clear();
user_loc.clear();
user_fName.clear();
if (mCursor.moveToFirst()) {
do {
user_id.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.EMP_NAME)));
user_loc.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.EMP_LOC)));
System.out.println("loc " + user_loc);
Toast.makeText(getApplicationContext(), user_id.toString()+" "+ user_fName.toString()+ " "+ user_loc.toString(), 1000).show();
//user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ASSID)));
//user_dob.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_DOB)));
//user_mobno.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_MOBNO)));
//user_email.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
} while (mCursor.moveToNext());
}
ListAdapter disadpt = new ListAdapter(TodayList.this, user_fName );
lv.setAdapter(disadpt);
mCursor.close();
}
public void BdayList(){
dbh=new DbHelper(this);
db=dbh.getWritableDatabase();
list= dbh.DOB();
// listAdapter = new ArrayAdapter<String>(this, R.layout.bdaylist, list);
Toast.makeText(getApplicationContext(), list.toString(), Toast.LENGTH_LONG).show();
/*final StableArrayAdapter adapter = new StableArrayAdapter(TodayList.this,
android.R.layout.simple_list_item_1, list);*/
listAdapter = new ArrayAdapter<String>(this, R.layout.simplrrow, list);
lv.setAdapter(listAdapter);
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
Custom Adaptor class(ListAdaptor.java)
package com.example.sampleparse;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> Name;
private ArrayList<String> Assid;
private ArrayList<String> Dob;
private ArrayList<String> Mobno;
private ArrayList<String> Email;
private ArrayList<String> dept;
private ArrayList<String> location;
public ListAdapter(Context c, ArrayList<String> name) {
this.mContext = c;
//this.id = id;
this.Name = name;
/* this.Assid = assid;
this.Dob = user_dob;
this.Mobno = user_mobno;
this.Email = user_email;
this.dept = dept;*/
//this.location = loc;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Name.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return Integer.valueOf(arg0);
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.Name.addAll(paramArrayList);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int pos, View child, ViewGroup parent) {
// TODO Auto-generated method stub
Holder mHolder;
LayoutInflater layoutInflater;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (child == null) {
mHolder = new Holder();
child = layoutInflater.inflate(R.layout.bdaylist, parent, false);
mHolder = new Holder();
/* localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);*/
// mHolder.
mHolder.txt_id = (TextView) child.findViewById(R.id.test_id);
mHolder.txt_Name = (TextView) child.findViewById(R.id.test_name);
mHolder.txt_Loc = (TextView) child.findViewById(R.id.test_Loc);
mHolder.txt_Bday = (TextView) child.findViewById(R.id.test_BDay);
mHolder.txt_Day= (TextView) child.findViewById(R.id.test_Day);
mHolder.txt_Today= (TextView) child.findViewById(R.id.test_toDay);
mHolder.txt_Date = (TextView) child.findViewById(R.id.test_Date);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText("id");
mHolder.txt_Name.setText(Name.get(pos).indexOf(0));
mHolder.txt_Loc.setText(":lov");
mHolder.txt_Bday.setText("Birth Day");
mHolder.txt_Day.setText("WEdness day");
mHolder.txt_Today.setText("Today");
mHolder.txt_Date.setText("May 7");
mHolder.txt_Loc.setText("loc");
return child;
}
public class Holder {
TextView txt_id;
TextView txt_Name;
TextView txt_Bday;
TextView txt_Day;
TextView txt_Today;
TextView txt_Date;
TextView txt_Loc;
}
}
Please give me a solution, I spent stuck in this concept more than one day.
for(String s : stockArr)
System.out.println(s);
// System.out.println(stockArr.toString());
/* user_loc=dbh.BLocation();
String[] loc = new String[user_loc.size()];
for(String l : loc)
System.out.println(l);*/
//ta = new TestAdaptor(TodayList.this, stockArr,loc );
ListAdapter la = new ListAdapter(getApplicationContext(), list);
lv.setAdapter(la);
There is a problem if i am not wrong you are setting your adapter recursively through the for loop just initailize only one time after the loop; And second thing is that the null pointer exception it may be raising cause you are trying to access the value which is not existing yet. May be my this comment help you

How do I get a list of checked items from a custom ListView in Android?

I am experimenting with custom ListView's in Android. I have subclassed ArrayAdpater to hold an ArrayList of objects. The objects that get put in the ArrayAdapter come from a SQLite database.
In my ArrayAdapter class, I have overwritten the getView() method and inflate a custom view that puts an ImageView, 3 TextViews, and a Checkbox view on each row of the ListView.
I want to be able to get all the checked rows in my list do something with them, ie. remove them from the list and underlying database or edit the underlying data object represented by that row.
My problem is that I cannot seem to find a way to get my OnItemClickListener to work. The ListView displays fine but nothing happens when I click the row or if I check the checkbox and try to remove the checked items with my removeUnit() method. I've ran out of ideas.
What am I doing wrong here? Thanks for any help!
Here is my Activity
package com.mack.mylogger;
import android.os.Environment;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.*;
import android.database.Cursor;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.util.SparseBooleanArray;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.util.StringTokenizer;
import java.io.*;
import java.util.*;
public class ReportActivity extends Activity {
private Context context = null;
DBAdapter db = new DBAdapter(this); //my database adapter
ListView reportLV;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
String TAG = "ReportActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
// set up the list of finished units
reportLV = (ListView) findViewById(R.id.listview);
reportLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayList<RUnit> units = new ArrayList<RUnit>(); //init adapter with empty list
reportLV.setAdapter(new ReportLVAdapter(this, units));
reportLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "Item is clicked at position: " + position);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
cb.toggle();
if (cb.isChecked()) {
checkedPositions.add(position);
Log.d(TAG, "Item is checked at position: " + position);
} else if (!cb.isChecked()) {
checkedPositions.remove(position);
Log.d(TAG, "Item is unchecked at position: " + position);
}
}
});
// context
context = this.getBaseContext();
}
#Override
public void onResume() {
super.onResume();
updateListView();
}
private void updateListView() {
// get list of units
db.read();
RUnit[] allUnits = db.getAllUnits();
ArrayList<RUnit> finishedUnits = new ArrayList<RUnit>();
System.out.println("Units in database: " + allUnits.length);
RUnit unit;
for (int i=0; i<allUnits.length; i++) {
unit = allUnits[i];
// check status
if (unit.getStatus() == "Finished") {
finishedUnits.add(unit);
}
}
// update adapter with updated list of finished units
reportLV.setAdapter(new ReportLVAdapter(this, finishedUnits));
}
public void addUnit(View view) {
// method to run when "Add" button is clicked
Intent intent = new Intent(this, AddActivity.class);
startActivity(intent);
}
public void removeUnit(View view) {
// method to run when remove button is clicked
// loop thru the items in the ListView and remove checked items from the db
for (int i=0; i<checkedPositions.size(); i++) {
String unitStr = reportLV.getItemAtPosition(i).toString();
Log.d(TAG, "Removing unit: " + unitStr);
// remove unit from the database
db.deleteUnit(unitStr);
}
//update the LV
updateListView();
}
public void submit(View view) {
// do something here
}
}
Here is my ArrayAdapter
package com.mack.mylogger;
import android.app.Activity;
import android.util.*;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CheckBox;
import android.view.View.OnClickListener;
import java.util.*;
public class ReportLVAdapter extends ArrayAdapter<RUnit> {
private final Activity context;
private final ArrayList<RUnit> units;
String TAG = new String("ReportLVAdapter");
static class ViewHolder {
public TextView serial;
public TextView status;
public TextView date;
public ImageView model;
public ImageView flag;
public CheckBox checkbox;
}
public ReportLVAdapter(Activity context, ArrayList<RUnit> units) {
super(context, R.layout.adapterlv_report, units);
this.context = context;
this.units = units;
Log.d(TAG, "Size of adapter array: " + units.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder = new ViewHolder();
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.adapterlv_report, null);
viewHolder.serial = (TextView) rowView.findViewById(R.id.serial);
viewHolder.model = (ImageView) rowView.findViewById(R.id.model);
viewHolder.status = (TextView) rowView.findViewById(R.id.status);
viewHolder.date = (TextView) rowView.findViewById(R.id.date);
viewHolder.flag = (ImageView) rowView.findViewById(R.id.flag);
viewHolder.checkbox = (CheckBox) rowView.findViewById(R.id.checkbox);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
// Need to handle empty database situation
// get info from RUnit obj
RUnit unit = units.get(position);
String sn = unit.getSerialNumAsString();
String mdl = unit.getModel();
String stat = unit.getStatus();
// date
String d;
if (stat == "Finished") { d = unit.getFinishDate(); }
else if (stat == "Submitted") { d = unit.getSubmitDate(); }
else if (stat == "Shipped") { d = unit.getShipDate(); }
else { d = "NA"; }
// flags
String[] flags = unit.getFlags();
///// Set view values
// text values
viewHolder.serial.setText(sn);
viewHolder.status.setText(stat);
viewHolder.date.setText(d);
// set model image
if (mdl == "TK") {
viewHolder.model.setImageResource(R.drawable.tk_icon);
} else {
// must be carrier
viewHolder.model.setImageResource(R.drawable.carrier_icon);
}
// set flag image - only look for hold
for (int i=0; i<flags.length; i++) {
if (flags[i] == "hold") {
// set hold image
viewHolder.flag.setImageResource(R.drawable.hold_flag);
} else {
// no image
}
}
return rowView;
}
My activity XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:text="#string/main_title"
android:textAlignment="gravity"
android:textAllCaps="true"
android:textSize="36sp"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:text="#string/report_subtitle"
android:textAlignment="gravity"
android:textAllCaps="true"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="#+id/button_submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
android:text="#string/button_submit"
android:onClick="submit"
android:textSize="26sp" />
<LinearLayout
android:id="#+id/button_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_submit"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1.0"
android:onClick="addUnit"
android:text="#string/button_add_fg" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1.0"
android:text="#string/button_modify_fg" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1.0"
android:onClick="removeUnit"
android:text="#string/button_remove_fg" />
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/button_group"
android:layout_below="#id/subtitle"
android:footerDividersEnabled="true"
android:headerDividersEnabled="true" />
</RelativeLayout>
My custom View for the rows XML
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:tools="http://schemas.android.com/tools"
android:columnCount="5"
android:rowCount="2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/model"
android:layout_row="0"
android:layout_column="0"
android:layout_margin="5dip"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/serial"
android:layout_row="0"
android:layout_column="1"
android:layout_columnSpan="2"
android:textSize="35dp"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/status"
android:layout_row="1"
android:layout_column="0"
android:layout_columnSpan="2"
android:textSize="20dp"
android:textStyle="italic"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/date"
android:layout_row="1"
android:layout_column="2"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/flag"
android:layout_row="0"
android:layout_column="3"
android:layout_rowSpan="2"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/checkbox"
android:layout_row="0"
android:layout_column="4"
android:layout_rowSpan="2"
android:layout_gravity="right"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</GridLayout>
You can call getCheckedItemPositions() on the list view. This will return a SparseBooleanArray containing ALL items in the list and whether or not they are checked. Once you have that, you can loop through the array and use valueAt(i) to determine if an item is selected or not.
Here's a good article on this topic.
You can try this
SparseBooleanArray checkedPositions = lv.getCheckedItemPositions ();int size = checkedPositions.size ();for (int i=0 ; i<size ; i++) {
// We get the key stored at the index 'i'
int key = checkedPositions.keyAt (i);
// We get the boolean value with the key
Log.i (Tag, "checkedPositions(" + key + ")=" + checkedPositions.get (key));}

Displaying the button at the end of the ListView with Linear Layout

I am a newbie in android application development. I faced a problem regarding the displaying a button at the end of the List View. I am using Linear Layout. The application can show all the list but cannot show the Button. I have also pasted my XML code here. Any help in this regard, will be highly appreciated.
Mohan
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_New"
android:width="170dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="Click"
/>
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/btn_New"
android:text="#string/hello"
/>
<ListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView"
/>
</RelativeLayout>
contactlistitem.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" android:orientation="horizontal" android:weightSum="1">
<TextView
android:id="#+id/txtDisplayName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium" >
</TextView>
<ImageView android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"></TextView>
</LinearLayout>
ContactListActivity.java
package com.contactlist;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Data;
public class ContactListActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContactList contactList=this.getContacts();
ArrayAdapter<Contact> adapter=new ContactAdapter(this,contactList.getContacts());
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object o=this.getListAdapter().getItem(position);
Contact c=(Contact)o;
Toast.makeText(this, c.getDisplayName(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, c.getId(), Toast.LENGTH_SHORT).show();
}
private ContactList getContacts()
{
ContactList contactList=new ContactList();
Uri uri=ContactsContract.Contacts.CONTENT_URI;
ContentResolver cr=getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur=cr.query(uri, null, null, null, sortOrder);
if(cur.getCount() >0)
{
String id;
String img;
String name;
while(cur.moveToNext())
{
Contact c =new Contact();
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
img= cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
final Bitmap photo;
if(img != null) {
photo = queryContactBitmap(img);
} else {
photo = null;
}
c.setId(id);
c.setImage(photo);
c.setDisplayName(name);
contactList.addContact(c);
}
}
// cur.close();
return contactList;
}
private Bitmap queryContactBitmap(String photoId) {
final Cursor photo = managedQuery(
Data.CONTENT_URI,
new String[] {Photo.PHOTO}, // column where the blob is stored
Data._ID + "=?", // select row by id
new String[]{photoId}, // filter by the given photoId
null);
final Bitmap photoBitmap;
if(photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(
photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(
photoBlob, 0, photoBlob.length);
} else {
photoBitmap = null;
}
photo.close();
return photoBitmap;
}
}
ContactList.java
package com.contactlist;
import java.util.ArrayList;
import java.util.List;
public class ContactList {
private List<Contact> _contacts=new ArrayList<Contact>();
public List<Contact> getContacts(){return _contacts;}
public void addContact(Contact contact){ this._contacts.add(contact);}
}
ContactAdapter.java
package com.contactlist;
import java.util.List;
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 ContactAdapter extends ArrayAdapter<Contact> {
private final List<Contact> _contacts;
private final Activity _context;
public ContactAdapter(Activity context, List<Contact> contacts)
{
super(context,R.layout.main,contacts);
this._contacts=contacts;
this._context=context;
}
static class ViewHolder {
protected TextView text;
private Contact _contact;
public ImageView imageview;
protected void setContact(Contact contact)
{
text.setText(contact.getDisplayName());
imageview.setImageBitmap(contact.getImage());
_contact=contact;
}
protected Contact getContact() {return _contact;}
}
#Override
public Contact getItem(int position)
{
return _contacts.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view=null;
if(convertView==null)
{
LayoutInflater inflater=_context.getLayoutInflater();
view=inflater.inflate(R.layout.contactlistitem, null);
final ViewHolder viewHolder=new ViewHolder();
viewHolder.text=(TextView)view.findViewById(R.id.txtDisplayName);
viewHolder.imageview =(ImageView)view.findViewById(R.id.contact_image);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
else
{
view = convertView;
}
return view;
}
}
Contact.java
package com.contactlist;
import java.util.ArrayList;
import android.R.string;
import android.graphics.Bitmap;
public class Contact {
private String _id;
private String _displayName;
private Bitmap _img;
public String getId(){return _id;}
public String getDisplayName(){return _displayName;}
public Bitmap getImage(){return _img;}
public void setId(String id){_id=id;}
public void setDisplayName(String displayName){_displayName=displayName;}
public void setImage(Bitmap img){_img=img;}
}
Try this and see if it works:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/contact_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_New"
android:width="170dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="Click"
/>
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/btn_New"
android:text="#string/hello"
/>
<ListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/textView"
/>
</RelativeLayout>
MainActivity class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.contactList);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
Now when you put things inside the listView it should not "push" the button or the textView down.
Firstly you have to set a linear layout in a main relative layout and set its gravity bottom
<RelativeLayout
android:width = "fill..."
android....>
<LinearLayout
android:gravity="bottom"
android:id="#+id/linear1"
android:layout_alignParentBottom="true">
<Button/>
</LinearLayout>
<ListView
android:layout_above="#id/linear"/>
android:layout_weight="1"
delete it.
if you are not express 'android:layout_weightSum' on over level that cotains some components are express 'android:layout_weight' but also component that contain 'android:layout_weight="1"' code is exactly change size to fullscreen.
(i'm sorry, i can't speak english very well....)
android:layout_weight="1" is wrong
android:layout_weight="1" delete it
Or use android:layout_weightSum first.

Custom Listview contains a button I want to set onclicklistener on the button

I made a custom listview with a button and textviews in it.
What i want to do is -
On the click of a button,
I want to get the index of listview.
I used HashMap to store the key value pair.
Here is my Activity code:
package com.hisham.listviewexhisham;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv= (ListView)findViewById(R.id.listview);
final TextView tvTesting = (TextView)findViewById(R.id.tvTesting);
// create the grid item mapping
String[] from = new String[] {"quantity", "item", "cost", "remove"};
int[] to = new int[] { R.id.quantity, R.id.item, R.id.cost, R.id.remove};
ArrayList<String> productNames = new ArrayList<String>();
productNames.add("Trumbull 125");
productNames.add("Trumbull 135");
productNames.add("Trumbull 17'' Monitor");
productNames.add("Trumbull Keyboard");
productNames.add("Trumbull 2TB HD");
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < productNames.size(); i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("quantity", "" + i);
map.put("item", productNames.get(i));
map.put("cost", "$ 600.99");
map.put("remove", "X");
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid, from, to);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
tvTesting.setText("Id is - " +arg2);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
here is grid.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"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:width="20dip" />
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.01"
android:text="Trumbull"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/cost"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:gravity="right"
android:text="$ 500.99" />
<Button
android:id="#+id/remove"
style="?android:attr/buttonStyleSmall"
android:layout_width="30dp"
android:layout_height="30dp"
android:text="X" />
</LinearLayout>
</LinearLayout>
and this is my main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTesting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
You can use SimpleAdapter.setViewBinder and then set the onClickListener() of your Button in the ViewBinder by comparing the Id of the View being bound to the Button Id (R.id.remove) and set its onClickListener().
Update:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation){
if (view.getId() == R.id.remove) {
Button b=(Button) view;
b.setOnClickListener(/*your desired implementation*/);
return true;
}
return false;
}

Categories

Resources