I am doing an contact list android application but i have a small problem with my screens.
Here is my search.xml code:
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText android:id="#+id/searchText"
android:hint="#string/searchDefault"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button android:id="#+id/searchButton"
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
enter code here
Here is my detalii.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
My problem is that my screen appears like image from below but i want detalii to appear on entire screen.I dont know what am i doing wrong.Could anybody give me a solution?
This is my search.java:
package org.example.dbcontactconsole;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import static android.provider.BaseColumns._ID;
public class Search extends ListActivity {
private static int[] TO = {R.id.rowid,R.id.name, R.id.mobilephone, R.id.email };
private static String[] FROM = {_ID,DbConstants.NAME, DbConstants.PHONE, DbConstants.EMAIL, };
private Button sButton;
private ListView lv1;
private static SQLiteDatabase db;
private DbCreate contacts;
private Cursor cursor;
private EditText searchText;
protected SimpleCursorAdapter adapter;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchText=(EditText)findViewById(R.id.searchText);
sButton=(Button)findViewById(R.id.searchButton);
sButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
}
});
}
private Cursor getContacts() {
db = contacts.getReadableDatabase();
cursor = db.rawQuery("SELECT _id,name, phone, email FROM contactTest1 WHERE name LIKE ?",
new String[]{searchText.getText().toString()+"%"});
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent(){
contacts = new DbCreate(this);
try {
cursor = getContacts();
showContacts(cursor);
} finally {
contacts.close();
db.close();
}
}
private void showContacts(Cursor cursor) {
//set up data binding
adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Intent abaintent = new Intent(this,Detalii.class);
Cursor cursor = (Cursor) adapter.getItem(position);
abaintent.putExtra("Contact_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(abaintent);
}
}
Here is my Detalii.java:
package org.example.dbcontactconsole;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Detalii extends ListActivity
{
protected TextView contactName;
protected TextView contactPhone;
protected TextView email;
protected int contactId;
protected List<Actiune> actiune;
protected ActiuneAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalii);
contactId = getIntent().getIntExtra("Contact_ID",0);
SQLiteDatabase db = (new DbCreate(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT name,phone,email FROM contactTest1 WHERE _id=?",new String[]{""+contactId});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
contactName = (TextView) findViewById(R.id.name);
contactName.setText(cursor.getString(cursor.getColumnIndex("name")));
actiune= new ArrayList<Actiune>();
String phoneString=cursor.getString(cursor.getColumnIndex("phone"));
if (phoneString!=null)
{
actiune.add(new Actiune("Suna la numar",phoneString,Actiune.ACTION_CALL));
}
String stringemail = cursor.getString(cursor.getColumnIndex("email"));
if (stringemail != null) {
actiune.add(new Actiune("Email", stringemail,Actiune.ACTION_EMAIL));
}
adapter = new ActiuneAdapter();
setListAdapter(adapter);
}
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Actiune action = actiune.get(position);
Intent intent;
switch (action.getType()) {
case Actiune.ACTION_CALL:
Uri callUri = Uri.parse("tel:" + action.getData());
intent = new Intent(Intent.ACTION_CALL, callUri);
startActivity(intent);
break;
case Actiune.ACTION_EMAIL:
intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{action.getData()});
startActivity(intent);
break;
}
}
class ActiuneAdapter extends ArrayAdapter<Actiune> {
ActiuneAdapter() {
super(Detalii.this, R.layout.actiune_detalii, actiune);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Actiune action = actiune.get(position);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.actiune_detalii, parent, false);
TextView label = (TextView) view.findViewById(R.id.label);
label.setText(action.getLabel());
TextView data = (TextView) view.findViewById(R.id.data);
data.setText(action.getData());
return view;
}
}
}
Here is my DBconsole.java:
package org.example.dbcontactconsole;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.view.View;
import android.app.ListActivity;
import static android.provider.BaseColumns._ID;
public class DbContactConsole extends ListActivity {
private static String[] FROM = {_ID,DbConstants.NAME };
private DbCreate contacts;
private static SQLiteDatabase db;
private static int[] TO = {R.id.rowid,R.id.name,};
private ListView lv1;
private static String itemId;
private Cursor cursor;
static final int CONTACT_CANCELED = 0;
static final int CONTACT_ADDED = 1;
static final int CONTACT_MODIFIED = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
cursor = (Cursor) a.getItemAtPosition(position);
itemId = cursor.getString(0);
openOptionsMenu();
}
});
lv1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
//selected item index from ListView
public void showDialogItemId(long itemId){
Toast.makeText(this, "Menu item selected index is" + Long.toString(itemId), Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.modifyitem:
if(null != itemId){
Bundle contactToModify = new Bundle();
contactToModify.putString("cFirstName", cursor.getString(1));
contactToModify.putString("cMobilePhone", cursor.getString(2));
contactToModify.putString("cEmail", cursor.getString(3));
contactToModify.putString("mod_type", "modifyPerson");
Intent intent = new Intent(this, ContactDetails.class);
intent.setClass(this, ContactDetails.class);
intent.putExtras(contactToModify);
startActivityForResult(intent, CONTACT_MODIFIED);
}else{
Toast.makeText(this, "Select Contact to modify", Toast.LENGTH_LONG).show();
}
break;
case R.id.additem:
Intent i = new Intent(this, ContactDetails.class);
Bundle bun = new Bundle();
bun.putString("mod_type", "addPerson");
i.setClass(this, ContactDetails.class);
i.putExtras(bun);
startActivityForResult(i, CONTACT_ADDED);
break;
case R.id.removeitem:
if(null != itemId){
removeContact(itemId);
showDatabaseContent();
}
else{
Toast.makeText(this, "Select Contact to delete", Toast.LENGTH_LONG).show();
}
break;
case R.id.search:
Intent j =new Intent(this,Search.class);
j.setClass(this, Search.class);
startActivity(j);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
// See which child activity is calling us back.
switch (resultCode) {
case CONTACT_ADDED:
// This is the standard resultCode that is sent back if the
// activity crashed or didn't doesn't supply an explicit result.
if (resultCode == RESULT_FIRST_USER){
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("contactData");
addContact(bundle);
showDatabaseContent();
}
else{
Toast.makeText(this, "CANCEL CONTACT BUTTON PRESSED", Toast.LENGTH_LONG).show();
}
break;
case CONTACT_MODIFIED:
if (resultCode == 2){
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("contactData");
modifyContact(bundle);
showDatabaseContent();
}
else{
Toast.makeText(this, "MODIFY CONTACT FAILED", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
//method removes item from database
private void removeContact(String itemId){
db = contacts.getWritableDatabase();
db.delete(DbConstants.TABLE_NAME, "_ID=" + itemId, null);
}
private void addContact(Bundle bundle) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
db = contacts.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.NAME, bundle.getString("contactFirstName"));
vals.put(DbConstants.PHONE, bundle.getString("contactMobilePhone"));
vals.put(DbConstants.EMAIL, bundle.getString("contactEmail"));
db.insertOrThrow(DbConstants.TABLE_NAME, null, vals);
}
//method should modify existing Contact
private void modifyContact(Bundle bundle){
db = contacts.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.NAME, bundle.getString("contactFirstName"));
vals.put(DbConstants.PHONE, bundle.getString("contactMobilePhone"));
vals.put(DbConstants.EMAIL, bundle.getString("contactEmail"));
db.update(DbConstants.TABLE_NAME, vals, _ID+"="+itemId, null);
}
private Cursor getContacts() {
db = contacts.getReadableDatabase();
cursor = db.query(DbConstants.TABLE_NAME, FROM, null, null, null,
null,DbConstants.NAME);
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent(){
contacts = new DbCreate(this);
try {
cursor = getContacts();
showContacts(cursor);
} finally {
contacts.close();
db.close();
}
}
private void showContacts(Cursor cursor) {
//set up data binding
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
}
Do you have to have the orientation as vertical? Could you change that for detalii.xml to be horizontal so it fills the parent horizontally instead of vertically?
android:orientation="vertical"
Related
I'm currently trying to pull from one table but display different results from different sql queries into different listviews on the same activity.
currently it's not populating the listview.
it was populating when I only had the one listview however it's not what I wanted as it only displayed one sql query
adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:screenOrientation="portrait"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/tvName"
android:layout_width="92dp"
android:layout_height="30dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:text="Name"
android:textColor="#FEE851"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.016"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.14" />
<TextView
android:id="#+id/tvlearningstyle"
android:layout_width="92dp"
android:layout_height="30dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:text="Name"
android:textSize="20sp"
android:textColor="#FEE851"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.055"
app:layout_constraintStart_toEndOf="#+id/tvName"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.14" />
</android.support.constraint.ConstraintLayout>
Adapterlist
package com.example.jcw3;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class AdapterList extends BaseAdapter {
ArrayList<String> n,p;
GroupList l;
LayoutInflater inflater;
public AdapterList(GroupList data,ArrayList<String> name,ArrayList<String> learningstyle){
this.l=data;
this.n=name;
this.p=learningstyle;
this.inflater=LayoutInflater.from(data);
}
#Override public int getCount() {
return n.size();
}
#Override public Object getItem(int i) {
return null;
}
#Override public long getItemId(int i) {
return 0;
}
#Override public View getView(int i, View view, ViewGroup viewGroup) {
view=inflater.inflate(R.layout.adapter,null);
TextView tvname=(TextView)view.findViewById(R.id.tvName);
TextView tvlearningstyle=(TextView)view.findViewById(R.id.tvlearningstyle);
tvname.setText(n.get(i));
tvlearningstyle.setText(p.get(i));
return view;
}
}
Grouplist
package com.example.jcw3;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import android.widget.ListView;
import android.view.View;
public class GroupList extends AppCompatActivity {
ListView listView, listView2, listView3, listView4, listView5;
SQLiteDatabase db;
Button clear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_list);
clear = (Button) findViewById(R.id.clear);
db = openOrCreateDatabase("Mydata", Context.MODE_PRIVATE, null);
onViewData();
onViewData2();
onViewData3();
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAll();
openStudents();
}
});
}
public void onViewData() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =Visual and LEARNINGSTYLE=VK order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView = findViewById(R.id.lv1);
listView.setAdapter(new AdapterList(GroupList.this, listname, listLearningstyle) {
});
} //shows the 1st list view
public void onViewData2() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =Kinesthetic and LEARNINGSTYLE=VA order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView2 = findViewById(R.id.lv2);
listView2.setAdapter(new AdapterList(GroupList.this, listname, listLearningstyle) {
});
} //shows the 2nd list view
public void onViewData3() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =Aural and LEARNINGSTYLE=VAK order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView3 = findViewById(R.id.lv3);
listView3.setAdapter(new AdapterList(GroupList.this, listname, listLearningstyle) {
});
} //shows the 3rd list view
public void deleteAll() {
db.delete("id", null, null); //delete all rows in a table
}
public void openStudents() {
Intent intent = new Intent(this, Students.class);
startActivity(intent);
}
}
2nd Adapterlist
package com.example.jcw3;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class AdapterList2 extends BaseAdapter {
ArrayList<String> n,p;
GroupList2 l;
LayoutInflater inflater;
public AdapterList2(GroupList2 data,ArrayList<String> name,ArrayList<String> learningstyle){
this.l=data;
this.n=name;
this.p=learningstyle;
this.inflater=LayoutInflater.from(data);
}
#Override public int getCount() {
return n.size();
}
#Override public Object getItem(int i) {
return null;
}
#Override public long getItemId(int i) {
return 0;
}
#Override public View getView(int i, View view, ViewGroup viewGroup) {
view=inflater.inflate(R.layout.adapter,null);
TextView tvname=(TextView)view.findViewById(R.id.tvName);
TextView tvlearningstyle=(TextView)view.findViewById(R.id.tvlearningstyle);
tvname.setText(n.get(i));
tvlearningstyle.setText(p.get(i));
return view;
}
}
2nd Grouplist
package com.example.jcw3;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import android.widget.ListView;
import android.view.View;
public class GroupList2 extends AppCompatActivity {
ListView listView, listView2, listView3, listView4, listView5;
SQLiteDatabase db;
Button clear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_list);
clear = (Button) findViewById(R.id.clear);
db = openOrCreateDatabase("Mydata", Context.MODE_PRIVATE, null);
onViewData();
onViewData2();
onViewData3();
onViewData4();
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAll();
openStudents();
}
});
}
public void onViewData() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =Visual and LEARNINGSTYLE=VA order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView = findViewById(R.id.lv1);
listView.setAdapter(new AdapterList2(GroupList2.this, listname, listLearningstyle) {
});
} //shows the 1st list view
public void onViewData2() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =Kinesthetic and LEARNINGSTYLE=VK order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView2 = findViewById(R.id.lv2);
listView2.setAdapter(new AdapterList2(GroupList2.this, listname, listLearningstyle) {
});
} //shows the 2nd list view
public void onViewData3() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =Aural and LEARNINGSTYLE=VA order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView3 = findViewById(R.id.lv3);
listView3.setAdapter(new AdapterList2(GroupList2.this, listname, listLearningstyle) {
});
} //shows the 3rd list view
public void onViewData4() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
int groupsize = bundle.getInt("groupsize");
}
ArrayList<String> listname = new ArrayList<String>();
ArrayList<String> listLearningstyle = new ArrayList<String>();
listname.clear();
listLearningstyle.clear();
Cursor c = db.rawQuery("select distinct NAME from id where LEARNINGSTYLE =VA and LEARNINGSTYLE=VK order by NAME desc, LEARNINGSTYLE desc ", null);
while (c.moveToNext()) {
listname.add(c.getString(1));
listLearningstyle.add(c.getString(2));
}
ListView listView4 = findViewById(R.id.lv4);
listView4.setAdapter(new AdapterList2(GroupList2.this, listname, listLearningstyle) {
});
} //shows the 4th list view
public void deleteAll() {
db.delete("id", null, null); //delete all rows in a table
}
public void openStudents() {
Intent intent = new Intent(this, Students.class);
startActivity(intent);
}
}
I expect it to run the query and then populate into the correct listview,
what happens however is the activity that should display the results is just blank.
Do the following change in your adapter class:
#Override public Object getItem(int i) {
return n.get(i);
}
#Override public long getItemId(int i) {
return i;
}
#Override public View getView(int i, View view, ViewGroup viewGroup) {
view=inflater.inflate(R.layout.adapter,viewGroup,false);
TextView tvname=(TextView)view.findViewById(R.id.tvName);
TextView tvlearningstyle=(TextView)view.findViewById(R.id.tvlearningstyle);
tvname.setText(n.get(i));
tvlearningstyle.setText(p.get(i));
return view;
}
Hope it will help.
I managed to get Dialog to show up on the long click by implementing this code:
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
Unfortunately, when the dialog opens and prompts for new text input, when clicked ok, no changes are made to the list.
Here is the Dialog file:
package com.example.classorganizer;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
Here is the file containing list:
package com.example.classorganizer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.cookbook.data.Constants;
import com.cookbook.data.MyDB;
public class Monday extends ListActivity {
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
private class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Here is an xml file for dialog:
<?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" >
<RelativeLayout
android:id="#+id/relativeLayout4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</RelativeLayout>
</LinearLayout>
I don't understand why the rows are not being updated with data entered through Dialog file...
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
You are getting the value from TextView of the dialog ,have u added the data to the list.
Update the data to the list
fragment_monday.add(((TextView) editText).getText().toString());
I'm trying to get the data to load into mArrayAdapter. Is this at all possible?
I want the list to look just like the other lists in other activities.
-------------------------------
Startpage.java,
-------------------------------
package com.example.sqltest;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Startpage extends ListActivity {
final Context context = this;
String[] startpage;
private SQLiteAdapter mySQLiteAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startpage = new String[]{SQLiteAdapter.KEY_CONTENT}; // <--- This returns the word"content"
//startpage = getResources().getStringArray(R.array.startpage); <---- How do I load SQL DATA to here?
setListAdapter(new mArrayAdapter(this, startpage));
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
mySQLiteAdapter.insert("this");
mySQLiteAdapter.insert("that");
mySQLiteAdapter.insert("where");
mySQLiteAdapter.close();
getListView().setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent int1 = new Intent(view.getContext(),
AndroidSQLite.class);
startActivity(int1);
break;
case 1:
Intent int2 = new Intent(view.getContext(),
AndroidSQLite.class);
startActivity(int2);
break;
case 2:
Intent int3 = new Intent(view.getContext(),
AndroidSQLite.class);
startActivity(int3 );
break;
case 3:
Intent int4 = new Intent(view.getContext(),
AndroidSQLite.class);
startActivity(int4 );
break;
}
}
});
}
public class mArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public mArrayAdapter(Context context, String[] values) {
super(context, R.layout.startpage, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.startpage, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.startpage);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
ListView list = getListView();
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent,
View view, int position, long id) {
String s = values[position];
System.out.println(s);
if (s.equals("this")) {
Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();
} else if (s.equals("that")) {
Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();;
} else if (s.equals("where")) {
Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();
} else {
Toast.makeText( Startpage.this, getItem(position), Toast.LENGTH_LONG).show();
}
return true;
}
});
textView.setText(values[position]);
Context context1 = context;
AssetManager assetManager = context1.getResources().getAssets();
Typeface typeface = Typeface.createFromAsset(assetManager, (getString(R.string.font1)));
textView.setTextColor(Color.YELLOW);
textView.setTypeface(typeface);
String s = values[position];
System.out.println(s);
if (s.equals("this")) {
imageView.setImageResource(R.drawable.ic_launcher);
} else if (s.equals("that")) {
imageView.setImageResource(R.drawable.ic_launcher);
} else if (s.equals("where")) {
imageView.setImageResource(R.drawable.ic_launcher);
} else {
imageView.setImageResource(R.drawable.ic_launcher);
}
return rowView;
}
}
}
-------------------------------
SQLiteAdapter.java
-------------------------------
package com.example.sqltest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT = "Content";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_CONTENT + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String content){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
----------------------------------
startpage.xml layout
----------------------------------
<?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:layout_gravity="bottom|left"
android:padding="5dp" >
<ImageView
android:id="#+id/logo"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginLeft="5sp"
android:layout_marginRight="20sp"
android:layout_marginTop="5sp" />
<TextView
android:id="#+id/startpage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom|left"
android:text="#+id/label"
android:textSize="27sp" />
</LinearLayout>
----------------------------------
main.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="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
----------------------------------
row.xml layout
----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"/>
The code is based on a tutorial.
You haven't updated the data source for the adapter after calling setListAdapter(new mArrayAdapter(this, startpage));. All the mySQLiteAdapter.<foo> code just modifies the data in your database, you never actually retrieve it again and swap it into your adapter. All you have is a String array with one item, whose values is "content".
Add a method in your mArrayAdapter class:
public void setData(String[] newData) {
values = newData;
notifyDataSetChanged(); // tells the adapter the data has been updated
}
Although, you could use a CursorAdapter and use the Cursor you get from querying the database to populate the list. You can look at the ApiDemos sample project in the sdk to see how to use CursorAdapter.
I have added the checkBoxView to my ListView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<TextView
android:id="#+id/textViewWord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/fstRow"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textViewWord"
android:layout_below="#+id/textViewWord"
android:textColor="#ff1009"
android:text="#string/scndRow"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/starCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:button="#android:drawable/btn_star"
android:focusable="false"
/>
</RelativeLayout>
here is my code
package com.wts.ui;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static int REQUEST_CODE = 1;
private WordsDBAdapter dbAdapter;
private SimpleCursorAdapter dataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
//context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
//options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter = new WordsDBAdapter(this);
dbAdapter.open();
button = (Button)findViewById(R.id.buttonAddWord);
listView = (ListView)findViewById(R.id.listWords);
displayListView();
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Add some words, please",
Toast.LENGTH_LONG).show();
}
});
//================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor)listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(0);
return false;
}
});
//================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editWord = (EditText)findViewById(R.id.editWord);
editTranslate = (EditText)findViewById(R.id.editTranslate);
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if(word.length() > 0 && translate.length() > 0){
dbAdapter.insertWord(word,translate , "noDscrpt");
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE, menuItems[0]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE, menuItems[1]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT:
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(1));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(2));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(3));
startActivityForResult(intent, REQUEST_CODE);
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
}
return true;
}
#SuppressWarnings("deprecation")
private void displayListView() {
Cursor cursor = dbAdapter.fetchAllWords();
String[] columns = new String[] {
WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION,
};
int[] to = new int[] {
R.id.textViewWord,
R.id.textViewTranslate,
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.word_info, cursor,
columns, to);
listView.setAdapter(dataAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
String[] menuItems = getResources().getStringArray(R.array.options_menu_items);
menu.add(Menu.NONE,IDM_ABOUT,Menu.NONE,menuItems[1]);
menu.add(Menu.NONE,IDM_EXIT,Menu.NONE,menuItems[2]);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item)
{
switch(item.getItemId())
{
case IDM_ABOUT:
{
Intent intent = new Intent(MainActivity.this,AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE)
{
if(intent.hasExtra(getResources().getString(R.string.fstRow)))
{
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(getResources().getString(R.string.fstRow)),
intent.getExtras().getString(getResources().getString(R.string.scndRow)),
intent.getExtras().getString(getResources().getString(R.string.thrdRow))
);
displayListView();
}
}
}
}
How to get listViewItem that holds CheckBox that I have been clicked ?
Do i Need to set OnClickListener on CheckBox? but what next ?
Please help
thnx!
You should create your custom adapter , and you can catch your checkbox its getView method
public class CustomListAdapter extends ArrayAdapter<String> {
private Activity context;
private ListItemRow itemRow;
private String[] list;
private LayoutInflater layoutInflater;
public CustomListAdapter(Activity context, String[] list) {
super(context, R.layout.main, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
itemRow = new ListItemRow();
layoutInflater = context.getLayoutInflater();
rowView = layoutInflater.inflate(R.layout.word_info, null, true);
itemRow.starCheck= (ChechBox) rowView.findViewById(R.id.starCheck);
itemRow.textViewTranslate= (TextView) rowView.findViewById(R.id.textViewTranslate);
} else {
itemRow = (ListItemRow) rowView.getTag();
}
itemRow.starCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
itemRow.textViewTranslate.setText("starCheck clicked");
}
});
return rowView;
}
private class ListItemRow {
private ChechBox starCheck;
private TextView textViewTranslate;
}
}
im easily able to use for textviews but textview with imageview like contacts name,number and image display sort of listing i m suffering with i have searched many blogs but without success please help....
public class Listmain extends ListActivity
{
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
Data_baseActivity db=new Data_baseActivity(this);
db.open();
InputStream is;
Cursor cursor =db.getAllContacts1();
int len=cursor.getCount();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, cursor, new String[] { "image", "name"}, new int[] { R.id.icon, R.id.label});
adapter.setViewBinder(new ProductViewBinder());
setListAdapter(adapter);
db.close();
}
catch(Exception e)
{
Toast.makeText(this, e.toString()+" error", Toast.LENGTH_LONG).show();
}
}
}
public class ProductViewBinder implements ViewBinder
{
public boolean setViewValue(View view, Cursor cursor, int columnIndex)
{
try
{
if (view instanceof ImageView)
{
byte[] result = cursor.getBlob(3);//my image is stored as blob in db at 3
Bitmap bmp = BitmapFactory.decodeByteArray(result, 0, result.length);
ImageView im=(ImageView)findViewById(R.id.icon);
im.setImageBitmap(bmp);
return true;
}
}
catch(Exception e)
{
Toast.makeText(Listmain.this, e.toString()+" err", Toast.LENGTH_LONG).show();
}
return false;
}
}
Try like this:
cr.getBlob(cr.getColumnIndex("Image")) //where "Image" is column name.
I used this and it worked.
If it doesn't worked. Please post the toast message that u r getting in the exception
package com.service;
import java.io.InputStream;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Listmain extends ListActivity{
Bitmap bmaps;
private FriendAdapter friendAdapter;
String forDeletion[][]=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.viewer);
EditText etxData=(EditText)findViewById(R.id.search);
etxData.setText(null);
listContacts();
}
#Override
protected void onResume() {
super.onResume();
EditText etxData=(EditText)findViewById(R.id.search);
etxData.setText(null);
listContacts();
}
public void listContacts()
{
Data_baseActivity db=new Data_baseActivity(this);
try
{
Resources res=getResources();
Drawable d = res.getDrawable(R.drawable.no_photo);
bmaps = ((BitmapDrawable)d).getBitmap();
final ListView lv = getListView();
final EditText etx=(EditText)findViewById(R.id.search);
final ImageButton imgbtn=(ImageButton)findViewById(R.id.refresh);
db.open();
Cursor cursor =getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.getCount()<1)
{
etx.setVisibility(View.GONE);
}
startManagingCursor(cursor);
int len=cursor.getCount();
forDeletion=new String[len][4];
String[] from = new String[] {};
int[] to = new int[] {};
this.friendAdapter = new FriendAdapter(this, R.layout.rowlayout, cursor, from, to);
lv.setAdapter(friendAdapter);
etx.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void onTextChanged(CharSequence c, int s,
int e, int h) {
try
{
Data_baseActivity db1=new Data_baseActivity(Listmain.this);
db1.open();
Cursor searchCursor =getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,
ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?" , new String[]{c+"%"}, null);
startManagingCursor(searchCursor);
String[] from = new String[] {};
int[] to = new int[] {};
friendAdapter = new FriendAdapter(Listmain.this, R.layout.rowlayout, searchCursor, from, to);
lv.setAdapter(friendAdapter);
db1.close();
}
catch(Exception es)
{
Toast.makeText(Listmain.this, es.toString()+" g", Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception e)
{
Toast.makeText(this, e.toString()+" error", Toast.LENGTH_LONG).show();
}
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent=new Intent(Listmain.this,Editing.class);
String send[]=new String[4];
send[0]=forDeletion[position][0];
send[1]=forDeletion[position][1];
send[2]=forDeletion[position][2];
send[3]=forDeletion[position][3];
intent.putExtra("com.service.id", send);
startActivity(intent);
}
public class FriendAdapter extends SimpleCursorAdapter
{
private final Context mContext;
private final int mLayout;
private final Cursor mCursor;
private final int mNameIndex;
private final int mIdIndex;
private final LayoutInflater mLayoutInflater;
private int lookUp;
private final class ViewHolder {
public TextView name;
public ImageView image;
public TextView number;
public ImageView endis;
}
public FriendAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mNameIndex = mCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
this.mIdIndex = mCursor.getColumnIndex(ContactsContract.Contacts._ID);
this.lookUp=mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
public View getView(int position, View convertView, ViewGroup parent) {
try
{
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder = null;
String name = mCursor.getString(mNameIndex);
if (convertView == null)
{
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.label);
viewHolder.number = (TextView) convertView.findViewById(R.id.number);
viewHolder.image = (ImageView) convertView.findViewById(R.id.icon);
viewHolder.endis = (ImageView) convertView.findViewById(R.id.endis);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
String number = null;
String image = mCursor.getString(mIdIndex);
String lookup=mCursor.getString(lookUp);
long lid=Long.parseLong(image);
Bitmap bmp = loadContactPhoto(mContext.getContentResolver(),lid,mContext);
if(bmp==null)
{
bmp=bmaps;
}
viewHolder.image.setImageBitmap(bmp);
viewHolder.name.setText(name);
Cursor cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? " , new String[] {image}, null);
String num=null;
while(cur.moveToNext())
{
num = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
num=num+"\n";
}
number=num;
viewHolder.endis.setVisibility(View.GONE);
viewHolder.number.setText(number);
forDeletion[position][0]=name;
forDeletion[position][1]=number;
forDeletion[position][2]=image;
forDeletion[position][3]=lookup;
}
}
catch(Exception e)
{
Toast.makeText(Listmain.this, e.toString()+" 2", Toast.LENGTH_LONG).show();
}
return convertView;
}
}
public Bitmap loadContactPhoto(ContentResolver cr, long id,Context ctx) {
InputStream input=null;
try
{
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
input= ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
}
catch(Exception e)
{
Toast.makeText(ctx, "Image formation error", Toast.LENGTH_LONG).show();
}
Bitmap bmp=BitmapFactory.decodeStream(input);
return bmp;
}
}
## Heading ##
Write a class and extend simpleCusorAdapter in it.
Create a constructor in the class and take parameters: context, layout, cursor, from, to
In the constructor, intialize the views of your customized layout like this.imageContainer=container.