I'm building my first AndroidApp and can't get the ListView to populate with data from my database. The data is definitely there because I can loop through it and Toast() it and the data shows up - I just can't get it into the ListView for some reason. Below is the code:
ListSmsRecipients.java
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ListSmsRecipients extends Base_Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.smslist);
Button addSmsRecipient = (Button) findViewById(R.id.btn_listSms_addSms);
DbHelper dbhelper = new DbHelper(getApplicationContext());
SQLiteDatabase db = dbhelper.getWritableDatabase();
String[] from = new String[] { DbHelper.SMS_NAME, DbHelper.SMS_PHONE, DbHelper.SMS_MESSAGE };
String[] column = new String[] {DbHelper.SMS_ID, DbHelper.SMS_NAME, DbHelper.SMS_PHONE, DbHelper.SMS_MESSAGE };
int[] toViewIDs = new int[] { R.id.temp_smslist_item_name, R.id.temp_smslist_item_phone, R.id.temp_smslist_item_message };
Cursor cursor = db.query(DbHelper.SMS_TABLE_NAME, column, null, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.smslist_item, cursor, from, toViewIDs);
ListView list = (ListView)findViewById(R.id.listview_smsList);
list.setAdapter(adapter);
// This works
cursor.moveToFirst();
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DbHelper.SMS_NAME));
String phone = cursor.getString(cursor.getColumnIndex(DbHelper.SMS_PHONE));
String message = cursor.getString(cursor.getColumnIndex(DbHelper.SMS_MESSAGE));
Toast.makeText(getApplicationContext(), "Name = " + name + "\nPhone = " + phone + "\nMessage = " + message, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
}
BaseActivity.java
import android.support.v4.app.FragmentActivity;
public class Base_Activity extends FragmentActivity
{
}
smslist.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listview_smsList"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
smslist_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/temp_smslist_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text" />
<TextView
android:id="#+id/temp_smslist_item_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text" />
<TextView
android:id="#+id/temp_smslist_item_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
The problem is at adapter declaration. Change the getApplicationContext() to getActivity() as following
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.smslist_item, cursor, from, toViewIDs);
Hope this will help you.
After the help from Anu and Ramesh_D, I simply changed my code to Extend Activity cursor.close(), and then changed the adapter call to the following: SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.smslist_item, cursor, from, toViewIDs);
Related
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!
I am developing one Loaders & list view simple app. It is exactly like whatsapp's CONTACTS tab list. This app get the contacts from mobile and displays the name and image in list item. You can find the fragment code here.
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import java.io.InputStream;
public class TabThreeFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
MyCursorAdapter mAdapter;
SimpleCursorAdapter s;
public static final String TAG = "TabThreeFragment";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No phone numbers");
mAdapter = new MyCursorAdapter(getActivity(), R.layout.contact_list_item, null, 0 );
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.CONTACT_STATUS,
ContactsContract.Contacts.CONTACT_PRESENCE,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.LOOKUP_KEY,
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
Uri baseUri = ContactsContract.Contacts.CONTENT_URI;
String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(TAG, "onLoadFinished");
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
class MyCursorAdapter extends ResourceCursorAdapter{
public MyCursorAdapter(Context context, int layout, Cursor c, int flags) {
super(context, layout, c, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView contactName = (TextView) view.findViewById(R.id.textView1);
contactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
ImageView imageView = (ImageView) view.findViewById(R.id.profileImage);
Bitmap profileImage = getPhoto(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
//TextView ID = (TextView) view.findViewById(R.id.textView2);
if(profileImage !=null)
{
imageView.setImageBitmap(profileImage);
}
}
private Bitmap getPhoto(String id){
Log.d(TAG, id + "-----");
Bitmap photo = null;
try{
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI , new Long(id).longValue()));
if(inputStream != null)
photo= BitmapFactory.decodeStream(inputStream);
}catch (Exception e){
}
return photo;
}
}
}
List Item Layout file:- contact_list_item.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="wrap_content" android:gravity="center_vertical" android:layout_marginLeft="8dp"
android:layout_marginRight="8dp" android:layout_marginTop="6dp" android:layout_marginBottom="6dp">
<ImageView android:id="#+id/profileImage"
android:src="#drawable/ic_launcher"
android:layout_weight="0" android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout android:orientation="vertical"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView1" />
<TextView
android:id="#+id/textView2"
android:paddingLeft="6dp"
android:textSize="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy Content fro subtile"
/>
</LinearLayout>>
</LinearLayout>
My problem, app is displayed the contact details and photos but photos are changing every time when I scroll up and down. It means one contact information displaying with other contact's photo.
Did I miss anything?
use
if(profileImage !=null){
imageView.setImageBitmap(profileImage);
}else{
imageView.setImageDrawable(null);
}
inside your getview()
I have my ListView setup but it only shows 3 rows with numbers 1-3 and it's not showing the entries from my database.I've tried to find the answer for this but this ListView subject is very vague and I can't find a clear answer on how to show the text from my DB entries.
Here is the codes from my xml layout,ListView class and Cursor entry in database.
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:background="#drawable/nfbackground"
android:orientation="vertical" >
<ImageView
android:id="#id/titlebar"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:src="#drawable/nftitlebar" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/searchimageview"
android:textColor="#color/black"
android:textSize="25dp"
android:textStyle="bold"
android:text=""
android:orientation="vertical" >
</ListView>
</LinearLayout>
Code:
package com.fullfrontalgames.numberfighter;
import com.fullfrontalgames.numberfighter.DBAdapter;
import com.fullfrontalgames.numberfighter.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class PlayAFriend extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playafriend);
ListView FriendLV = (ListView) findViewById(android.R.id.list);
DBAdapter db = new DBAdapter(this);
db = db.open();
Cursor friendslist = db.GetAllFriends();
String[] from = new String[] {"ID","USERNAME","FRIENDS"}; // your column/columns here
int[] to = new int[] {android.R.id.text1};
#SuppressWarnings("deprecation")
ListAdapter cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, friendslist, from, to);
FriendLV.setAdapter(cursorAdapter);
db.close();
}
}
Code:
public Cursor GetAllFriends()
{
Cursor cursor = db.rawQuery("select rowid _id,* from NFDB", null);
int iRow = cursor.getColumnIndex("ID");
int iName = cursor.getColumnIndex("USERNAME");
int iFriends = cursor.getColumnIndex("FRIENDS");
if (cursor.moveToFirst()) {
do {
TextView friendslist = new TextView(context);
friendslist.setId(Integer.parseInt(cursor.getString(iRow)));
friendslist.setText(cursor.getString(iName));
friendslist.setText(cursor.getString(iFriends));
} while (cursor.moveToNext());
}
return cursor;
}
You need to create a layout with 2 TextView for your listview columns
list_items.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="wrap_content"
android:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textview_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
change
String[] from = new String[] {"USERNAME","FRIENDS"}; // your column/columns here
int[] to = new int[] {textview_name, textview_friends};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_items, friendslist, from, to, 0);
FriendLV.setAdapter(cursorAdapter);
//db.close(); Close the db in onDestroy
change
public Cursor GetAllFriends()
{
return db.rawQuery("select * from NFDB", null);
}
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.
(noob question)
Hello,
I am using this code to make a list of all contacts and display the phone number.
Currently I just want to display the name, but I am facing difficulties and I get a force close error.
ActivityManager: Starting: Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
cmp=com.beta.cphonebook/.CPhonebook }
The code I am using is this:
PhoneList.java:
package com.beta.cphonebook;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.content.ContentUris;
import android.net.Uri;
import android.database.Cursor;
public class PhoneList extends ListActivity {
private SimpleCursorAdapter myAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
ArrayList<String> nlist = new ArrayList<String>();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
nlist.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
}
}
}
String[] nlistString = new String[nlist.size()];
nlist.toArray(nlistString);
Arrays.sort(nlistString);
int[] mapto = new int[] {R.id.contact_name};
//------------------------------------------------------------------
//This is where I get the error. While trying to use the list adapter
ListAdapter mAdapter = new SimpleCursorAdapter(this,R.layout.phonelist,cur,test,mapto);
this.setListAdapter(mAdapter);
//------------------------------------------------------------------
}
}
phonelist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="#drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
/>
<TextView android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number: "
/>
<TextView android:id="#+id/contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
I know it should be something very simple, but for the past 3 hours, I just can't find it!!
instead of using the SimpleCursorAdapter class you can use ArrayAdapter....because u need to sort the name...and it is after iterating cursor....
so your code can be like the following
private ArrayAdapter<String> myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
ArrayList<String> nlist = new ArrayList<String>();
if (cur.getCount() > 0) {
if(cur.moveToFirst()) {
do {
Log.i("Test", "---------------------count-------------------" + cur.getCount());
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
nlist.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
//String num = cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.NUMBER));
}
}while (cur.moveToNext()) ;
}
}
String[] nlistString = new String[nlist.size()];
nlist.toArray(nlistString);
Arrays.sort(nlistString);
myAdapter = new ArrayAdapter<String>(this, R.layout.phonelist, R.id.contact_name, nlistString);
this.setListAdapter(myAdapter);
}
}