I am trying to create a List in which I take the Contacts I have in my android phone, with CheckBoxes and Images. For now I am just trying to get the contacts on the list with the checkbox.
Code is as Follows :
Problems I am facing :
1) Unable to create ViewHolder Properly
2) Unable to populate contacts into a adapter
3) Unable to retrive images from contacts
main.java
package com.example.curs;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.provider.ContactsContract;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState );
setContentView(R.layout.activity_main);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
my_custom_adapter adapter = new my_custom_adapter(this, // Context.
android.R.layout.simple_list_item_multiple_choice, // Specify the row template
// to use (here, two
// columns bound to the
// two retrieved cursor
// rows).
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String []{ ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME },
// Parallel array of which template objects to bind to those
// columns.
new int[] { android.R.id.text1,android.R.id.text2});
setListAdapter(adapter);
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
}
my_custom_adapter.java
package com.example.curs;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class my_custom_adapter extends SimpleCursorAdapter{
private Context context ;
//ArrayList<String> elements ;
private ArrayList<Boolean> itemChecked ;
Cursor c;
String contact_id;
String contact_name[];
String []from;
int to1;
int to2;
String elements;
public my_custom_adapter(Context context, int layout, Cursor c, String []from, int[] to) {
super(context, layout, c, from, to);
// set_checked(false);
}
/*
// AS EVERY TIME LISTVIEW INFLATE YOUR VIEWS WHEN YOU MOVE THEM SO YOU NEED TO SAVE ALL OF YOUR CHECKBOX STATES IN SOME ARRAYLIST OTHERWISE IT WILL SET ANY DEFAULT VALUE.
private void set_checked(boolean is_checked)
{
for (int i=0; i < c.getCount(); i++) {
itemChecked.add(i, is_checked);
}
}
*/
//THIS IS SIMPLY A CLASS VIEW WILL HOLD DIFFERENT VIEWS OF YOUR ROW.
static class ViewHolder
{
public TextView tv;
public CheckBox cb;
public ImageView iv;
}
public View getView (final int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
View view = null;
if (rowView == null) {
LayoutInflater inflator = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
rowView = inflator.inflate(R.layout.inflated_layout, null);
final ViewHolder holder = new ViewHolder();
holder.cb = (CheckBox) rowView.findViewById(R.id.checkBox1);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.iv = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setTag(holder);
holder.cb
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
/* Model element = (Model) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
*/
}
});
view.setTag(holder);
holder.cb.setTag(c.getPosition());
} else {
view = convertView;
((ViewHolder) view.getTag()).cb.setTag(c.getPosition());
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.tv.setText(c.getString(c.getPosition()));
holder.iv.setImageBitmap(BitmapFactory.decodeResource(Resources.getSystem(),c.getPosition()));
//holder.cb.setChecked(c.getPosition().isSelected());
return view;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
inflated_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="17dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/checkBox1"
android:layout_toRightOf="#+id/imageView1"
android:singleLine="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:padding="15dp"/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Related
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);
I have a listview with several buttons in which the button.text property populated with several child names from a an sqlite database.
I need to retrieve tasks specificaly assigned to each child when the child's button is clicked (possibly using the text property of the button(which is populated with the child name) ).
I have 3 java files that i am working (ChildDatabase, ChildListAdapter, ChildList) with and 2 xml files(fragment_child_list_layout, fragment_child_list).
Where can I set an onClick event for the buttons in my list view. And how can i differentiate from each button if only ONE BUTTON is delcared?
This is my ChildDatabase file
package com.example.victor.kidsrewards;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildDataBase {
private SQLiteDatabase db;
private ChildSQLiteHelper childSQLiteHelper;
String _parentName = Globals._username;
public ChildDataBase(Context context) {
childSQLiteHelper = new ChildSQLiteHelper(context);
db = childSQLiteHelper.getWritableDatabase();
}
public void Close() {
db.close();
}
public void createChild(String childNameText, String nickNameText, String genderText, int ageText) {
String query = "select * from child";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
ContentValues contentValues = new ContentValues();
contentValues.put("id", count);
contentValues.put("childname", childNameText);
contentValues.put("nickname", nickNameText);
contentValues.put("age", ageText);
contentValues.put("gender", genderText);
contentValues.put("parent", _parentName);
//insert
db.insert("child", null, contentValues);
}
public List<ChildUser> getChildren() {
List<ChildUser> childList = new ArrayList<ChildUser>();
//select columns
String[] tableColumns = new String[]{"id", "childname", "nickname"};
Cursor cursor = db.query("child", tableColumns, "parent =? ", new String[]{_parentName}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChildUser child = new ChildUser();
//take values from database
child.setId(cursor.getInt(0));
child.setChildName(cursor.getString(1));
child.setNickName(cursor.getString(2));
//add to db
childList.add(child);
cursor.moveToNext();
}
return childList;
}
public String[] getChildNames() {
String[] tableColumns = new String[]{"childname"};
Cursor cursor = db.query("child", tableColumns, "parent =?", new String[]{_parentName}, null, null, null);
String[] array = new String[cursor.getCount()];//sets the length of the array
int i = 0;
while (cursor.moveToNext()) {
String uname = cursor.getString(cursor.getColumnIndex("childname"));
array[i] = uname;
i++;
}
return array;
}
}
This is my ChildListAdapter
Displays same button over again with different text property
package com.example.victor.kidsrewards;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildListAdapter extends ArrayAdapter<ChildUser> {
private final Context context;
private final List<ChildUser> childList;
public ChildListAdapter(Context context, List<ChildUser> childList){
super(context, R.layout.fragment_child_list_layout, childList);//fragment_child_list
this.context = context;
this.childList= childList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
return rowView;
}
ChildList class
package com.example.victor.kidsrewards;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ChildList extends ListFragment {
private ChildDataBase cdb;
public ChildList() {
// Required empty public constructor
}
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_child_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cdb = new ChildDataBase(getContext());
setListAdapter(new ChildListAdapter(getContext(), cdb.getChildren()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
}
fragment_child_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/childButton"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
fragment_child_list.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.victor.kidsrewards.ChildList">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:text="TODO TEXT GOES_HERE">
</ListView>
</FrameLayout>
You can set the OnClickListener for the Button inside the getView() method of the adapter. The position argument can be used to identify which button was clicked.
See the code,
#Override
public View getView(final int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String selectedChild = childList.get(position).getNickName();
// do something with selected item
}
});
return rowView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOncLickListener(new OnclickListener() {
public void onClick() {
// do something for click each row
}
return rowView;
}
I need help here, I got a SCA into the ListView but then when I applied OnClickListener to get the String Value on my ListView it shows text but not the actual text that is on my ListView android.database.sqlite.SQLiteCursor#2915f605.
here is my Java File in displaying the ListView.
package com.example.jello.letscook;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
public class showmenu extends AppCompatActivity {
DatabaseHelper myDb;
Spinner mainIng;
EditText sub1,sub2,sub3,sub4,sub5,sub6;
CheckBox Cb_Ar,Cb_Db,Cb_Hb;
String toPass="";
ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showmenu);
myDb = new DatabaseHelper(this);
sub1 = (EditText) findViewById(R.id.sub1);
sub2 = (EditText) findViewById(R.id.sub2);
sub3 = (EditText) findViewById(R.id.sub3);
sub4 = (EditText) findViewById(R.id.sub4);
sub5 = (EditText) findViewById(R.id.sub5);
sub6 = (EditText) findViewById(R.id.sub6);
Cb_Ar = (CheckBox) findViewById(R.id.check1);
Cb_Db = (CheckBox) findViewById(R.id.check2);
Cb_Hb = (CheckBox) findViewById(R.id.check3);
myList = (ListView) findViewById(R.id.selectView);
myDb.insertHB(true);
myDb.inert_Arth(true);
myDb.inert_Dia(true);
myDb.checkData(StartingScreen.gettingCheckBox());
showList();
}
public void showList() {
String toPass;
toPass = StartingScreen.gettingCheckBox();
Cursor cursor = myDb.getData(toPass);
String[] fromField = new String[] {DatabaseHelper.RECIPE_NAME};
int[] toView = new int[] {R.id.textViewMenuSuggest};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(this,R.layout.menushow,cursor,fromField,toView,0);
myList.setAdapter(myCursorAdapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPos = position;
Cursor listValue = (Cursor) myList.getItemAtPosition(itemPos);
Toast.makeText(showmenu.this, "" + listValue, Toast.LENGTH_LONG).show();
}
});
}
}
Here is my XML Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_height="wrap_content">
/>
<TextView
android:layout_marginTop="50dp"
android:text="Menu to Cook:"
android:id="#+id/lala"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content"/>
<ListView android:id="#+id/selectView"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:layout_height="0dp"
android:layout_width="wrap_content"/>
</LinearLayout>
I think your error comes from Crusor because you dont parse properly values from DataBase.. can you try some like this after line that you declare Cursor
put this line
String someData=listValue .getString(listValue .getColumnIndex(DbHelper.KEY_COL));
DbHelper is your DataBase variable, also KEY_COL is your column from which you fetch desire data.Hope to help!
Like the title says, my setOnItemClickListener isn't working. I looked through everything I've seen so far on SO and couldn't find my error.
This is the code:
This is the problematic class. It isn't the main class, but is called from an intent:
package...;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
public class GroupActivity extends Activity {
String group_id = "";
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
context = this;
Intent intent = getIntent();
group_id = intent.getStringExtra("group_id");
Log.i("bla", "Launched GroupActivity for group_id " + group_id);
final SubAdapter adapter = new SubAdapter(this, group_id);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setClickable(true);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int idx, long lidx) {
Log.i("print here", "blaa " + idx);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is the SubAdapter class:
package...;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class SubAdapter extends BaseAdapter {
private static final int thumb_width = 128;
private static final int thumb_hight = 128;
private static Bitmap default_thumb = null;
private static LayoutInflater inflater = null;
private final String group_id_;
private final Activity activity;
private final SubAdapter t = this;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SubAdapter(Activity a, final String group_id) {
Drawable d = a.getResources().getDrawable(R.drawable.ic_contact_picture);
default_thumb = ((BitmapDrawable) d).getBitmap();
activity = a;
group_id_ = group_id;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int idx, View convertView, ViewGroup parent) {
Log.i("bla2", "getting view with index " + idx);
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.sub_list_item, null);
vi.setClickable(true);
}
TextView tv1 = (TextView)vi.findViewById(R.id.textView1);
TextView tv2 = (TextView)vi.findViewById(R.id.textView2);
ImageView img = (ImageView)vi.findViewById(R.id.imageView1);
tv1.setText("first name" + " " + "last name");
tv2.setText("some date");
// put thumbnail
Bitmap thumb = default_thumb;
img.setImageBitmap(thumb);
Log.i("bla3", "index is " + idx + "selected index is " + selectedPos);
if(selectedPos == idx){
Log.i("bla4", "inside if");
}
return vi;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
This is the activity_group xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".GroupActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusableInTouchMode="false"
android:focusable="false" >
</ListView>
</RelativeLayout>
This is the sub_list_item xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:layout_toLeftOf="#+id/toggleButton1"
android:layout_toRightOf="#+id/imageView1"
android:text="some text"
android:textAppearance="?android:attr/textAppearance" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_toLeftOf="#+id/toggleButton1"
android:text="more text"
android:textAppearance="?android:attr/textAppearance" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:text="present" />
</RelativeLayout>
Apart from the click listener, everything else seems to work. The SubAdapter opens properly and the list is populated.
Basically what I'm looking for is to get the message "Log.i("print here", "blaa " + idx);" to print - it is the log from the ListView's setOnItemClickListener (look above)
Please let me know if there is any other relevant code missing
Thanks!!!
In your GroupActivity class please add the following code before findViewById method:
now you get the view same and change your code
ListView lv = (ListView) findViewById(R.id.listView1);
to
final View v = inflater.inflate(R.layout.rescuer_no_dialog, null);
ListView lv = (ListView)v.findViewById(R.id.listView1);
You should probably remove the call to
vi.setClickable(true); in your SubAdapter class, because your convertView will consume the click before you onItemClick listener.
Change this
ListView lv = (ListView) findViewById(R.id.listView1);
to
lv = getListView()
Extend ListActivity and declare lv outside methods.
I am developing the program that used ListActivity. So, when i scroll the listview to down, it cause to restart application and start from first activity. My code is as follows :
package com.daarkoob.food;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Window;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
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.Toast;
public class FoodListActivity extends ListActivity {
private ArrayList<Food> M_foods = new ArrayList<FoodListActivity.Food>();
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.foodlist);
SQLiteDatabase sqliteDatabase = SQLiteDatabase.openOrCreateDatabase(
"/data/data/" + this.getPackageName() + "/data.db", null);
Cursor cursor = sqliteDatabase.rawQuery("SELECT * FROM FOOD", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
M_foods.add(new Food(cursor.getString(2), cursor.getString(1)));
cursor.moveToNext();
}
FoodAdapter adapter = new FoodAdapter(this);
setListAdapter(adapter);
cursor.close();
sqliteDatabase.close();
}
public class Food {
public Food(String foodName, String foodType) {
this.M_foodName = foodName;
this.M_foodType = foodType;
}
String M_foodName;
String M_foodType;
}
public class FoodAdapter extends ArrayAdapter<Food> {
private Context M_context = null;
public FoodAdapter(Context context) {
super(context, R.layout.foodlist_view_item, M_foods);
this.M_context = context;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) M_context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(
R.layout.foodlist_view_item, parent, false);
}
TextView textView = (TextView) convertView
.findViewById(R.id.foodlist_view_item_textview);
textView.setText(M_foods.get(position).M_foodName);
return convertView;
}
}
}
And the foodlist_view_item.xml is :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/border"
android:orientation="vertical" >
<TextView
android:id="#+id/foodlist_view_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="right|center_vertical"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:textStyle="bold" />
</RelativeLayout>
and the foodlist.xml is as follows :
<?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:background="#drawable/background"
android:orientation="vertical" >
<TextView
android:id="#+id/foodlist_title_bar"
android:layout_width="match_parent"
android:layout_height="40dip"
android:background="#drawable/textlines"
android:gravity="right|center_vertical"
android:text="#string/foodlist_titlebar_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:dividerHeight="1dip" >
</ListView>
</LinearLayout>
What thing is wrong ? Why restarting occurs ?
Thanks in advance :)