Android autocompletetextview won't populate contacts with custom adapter - android

I've created a custom adapter and custom list item. I was originally using a simple list item and just populated either the name or the number. However, now I'd like to show both the name and phone number in each list item. When I type something now into the autocomplete text it won't populate any anything. I did some error testing and it seems that it isn't even calling the overridden getView() method. I can't seem to figure out why this isn't working.
Also, yes I've added the READ_CONTACTS permission in the manifest.
MainActivity.java
package com.sncrmck.autocompletetest;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.widget.AutoCompleteTextView;
import com.sncrmck.adapter.ContactAdapter;
import com.sncrmck.obj.SimpleContact.SimpleContact;
public class MainActivity extends Activity {
AutoCompleteTextView acTextField;
private ContactAdapter adapter;
public ArrayList<SimpleContact> contactList = new ArrayList<SimpleContact>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver resolver = getContentResolver();
acTextField = (AutoCompleteTextView) findViewById(R.id.autoComplete);
Uri contacts = Uri.parse("content://icc/adn");
Cursor cursor = resolver.query(contacts, null, null, null, null);
if (cursor.moveToFirst()) {
String contactName;
String phoneNumber;
int nameColumn = cursor.getColumnIndex("name");
int phoneColumn = cursor.getColumnIndex("number");
do {
contactName = cursor.getString(nameColumn);
phoneNumber = cursor.getString(phoneColumn);
if((contactName != " " || contactName != null) && (phoneNumber!= " " ||phoneNumber!= null))
{
SimpleContact sc = new SimpleContact(contactName, phoneNumber);
contactList.add(sc);
}
} while (cursor.moveToNext());
}
adapter = new ContactAdapter(this, R.layout.grid_item, contactList);
acTextField.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
CustomAdapter.java
package com.sncrmck.adapter;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.sncrmck.autocompletetest.R;
import com.sncrmck.obj.SimpleContact.SimpleContact;
public class ContactAdapter extends ArrayAdapter<SimpleContact> {
private ArrayList<SimpleContact> entries;
private Activity activity;
public ContactAdapter(Activity a, int textViewResourceId, ArrayList<SimpleContact> entries){
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
Toast.makeText(getContext(), "Constructor", Toast.LENGTH_SHORT).show();
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Toast.makeText(getContext(), "Get View", Toast.LENGTH_SHORT).show();
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.big);
holder.item2 = (TextView) v.findViewById(R.id.small);;
}
else
holder=(ViewHolder)v.getTag();
final SimpleContact contactInfo = entries.get(position);
if (contactInfo != null) {
holder.item1.setText(contactInfo.getContactName());
holder.item2.setText(contactInfo.getContactNumber());
}
return v;
}
}
This is the SimpleContact object I'm passing to the ContactAdapter
package com.sncrmck.obj.SimpleContact;
public class SimpleContact {
private String contactName;
private String contactNumber;
public SimpleContact(String string, String string2) {
this.contactName = string;
this.contactNumber = string2;
}
public String getContactName() { return contactName; }
public void set(String contactName) { this.contactName= contactName; }
public String getContactNumber() { return contactNumber; }
public void setcustomSmall(String contactNumber) { this.contactNumber = contactNumber; }
}
Lastly, this is my custom list item - grid_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="fill_parent"
android:layout_height="fill_parent">
<TextView
android:textSize="24dp"
android:id="#+id/big"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:textSize="24dip"
android:id="#+id/small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

You need to override the getFilter() Method of your custom adapter
Also implement a custom filter and override the methods in that.
See this similar question.
I don't have my code available at work so but if I get a chance tonight I'll edit the answer.

Related

Putting images (emoticons) on ListView

I want to add new functionality to my chat. I have a code that allows me to insert chat bubbles and it's working pretty fine (1,2). I tried to make message and adapter (for images) classes analogically to previous adapter and message (for text) classes. I want it to work less like Messenger. When the message box is empty, sending button is emoticon button and it should put an emoticon on ListView (I skip increasing emoticon size within the length of pressing). When message box has text, emoticon button will change to sending button and this button should put the content of the box on the ListView. I tried but everything I tried, failed (when I put setAdapter to TextChangedListener the button do nothing and when I set setAdapter strictly to emojiAdapter Android Studio will throw me Null Pointer Exception). Below is my code:
Error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bk.cryptit, PID: 2720
java.lang.NullPointerException
at com.bk.cryptit.Chats.sendEmojiMessage(Chats.java:115)
at com.bk.cryptit.Chats$2.onClick(Chats.java:77)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.
ChatMessage.java
package com.bk.cryptit;
import java.util.Random;
public class ChatMessage {
public String body, sender, receiver, senderName;
public String Date, Time;
public String msgid;
public boolean isMine;
public ChatMessage(String Sender, String Receiver, String messageString,
String ID, boolean isMINE) {
body = messageString;
isMine = isMINE;
sender = Sender;
msgid = ID;
receiver = Receiver;
senderName = sender;
}
public void setMsgID() {
msgid += "-" + String.format("%02d", new Random().nextInt(100));
;
}
}
ChatAdapter.java
package com.bk.cryptit;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import static android.R.id.list;
public class ChatAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
ArrayList<ChatMessage> chatMessageList;
public ChatAdapter(Activity activity, ArrayList<ChatMessage> list) {
chatMessageList = list;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return chatMessageList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage message = (ChatMessage) chatMessageList.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chatbubble, null);
TextView msg = (TextView) vi.findViewById(R.id.message_text);
msg.setText(message.body);
msg.setTextSize(16);
msg.setSingleLine(false);
LinearLayout layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout);
LinearLayout parent_layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout_parent);
layout.setPadding(15,11,15,15);
// if message is mine then align to right
if (message.isMine) {
layout.setBackgroundResource(R.drawable.chat_bubble_right);
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
layout.setBackgroundResource(R.drawable.chat_bubble_left);
parent_layout.setGravity(Gravity.LEFT);
}
if (message.isMine) {
msg.setTextColor(Color.WHITE);
}
else {
msg.setTextColor(Color.BLACK);
}
return vi;
}
public void add(ChatMessage object) {
chatMessageList.add(object);
}
}
EmojiMessage.java
package com.bk.cryptit;
import android.widget.ImageView;
import java.util.Random;
public class EmojiMessage {
public String sender, receiver, senderName;
public ImageView body;
public String Date, Time;
public String msgid;
public boolean isMine;// Did I send the message.
public EmojiMessage(String Sender, String Receiver, ImageView emoji,
String ID, boolean isMINE) {
body = emoji;
isMine = isMINE;
sender = Sender;
msgid = ID;
receiver = Receiver;
senderName = sender;
}
public void setMsgID() {
msgid += "-" + String.format("%02d", new Random().nextInt(100));
;
}
}
EmojiAdapter.java
package com.bk.cryptit;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EmojiAdapter extends BaseAdapter{
private static LayoutInflater inflater = null;
ArrayList<EmojiMessage> chatMessageListEmoji;
public EmojiAdapter(Activity activity, ArrayList<EmojiMessage> list) {
chatMessageListEmoji = list;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return chatMessageListEmoji.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EmojiMessage message = (EmojiMessage) chatMessageListEmoji.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.imagechatbubble, null);
ImageView msgEmoji = (ImageView) vi.findViewById(R.id.message_image);
LinearLayout layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout);
LinearLayout parent_layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout_parent);
// if message is mine then align to right
if (message.isMine) {
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
parent_layout.setGravity(Gravity.LEFT);
}
return vi;
}
public void add(EmojiMessage object) {
chatMessageListEmoji.add(object);
}
}
Chats.java
package com.bk.cryptit;
import java.util.ArrayList;
import java.util.Random;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import com.bk.cryptit.ChatAdapter;
import com.bk.cryptit.ChatMessage;
import com.bk.cryptit.CommonMethods;
import com.bk.cryptit.EmojiMessage;
import com.bk.cryptit.EmojiAdapter;
import com.bk.cryptit.R;
public class Chats extends Fragment {
private EditText msg_edittext;
private String user1 = "khushi", user2 = "khushi1";
private Random random;
public static ArrayList<ChatMessage> chatlist;
public static ArrayList<EmojiMessage> emojilist;
public static EmojiAdapter emojiAdapter;
public static ChatAdapter chatAdapter;
ListView msgListView;
String editText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_welcome, container, false);
random = new Random();
msg_edittext = (EditText) view.findViewById(R.id.editText);
msgListView = (ListView) view.findViewById(R.id.messegesListView);
editText = msg_edittext.getText().toString();
final ImageButton sendButton = (ImageButton) view
.findViewById(R.id.button10);
sendButton.setImageResource(R.drawable.like);
// ----Set autoscroll of listview when a new message arrives----//
msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
msgListView.setStackFromBottom(true);
chatlist = new ArrayList<ChatMessage>();
chatAdapter = new ChatAdapter(getActivity(), chatlist);
emojilist = new ArrayList<EmojiMessage>();
emojiAdapter = new EmojiAdapter(getActivity(), emojilist);
msg_edittext.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (msg_edittext.getText().length()>0) {
sendButton.setImageResource(R.drawable.sending_black);
msgListView.setAdapter(chatAdapter);
} else sendButton.setImageResource(R.drawable.like); msgListView.setAdapter(emojiAdapter);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (msg_edittext.getText().length()>0) {
sendButton.setImageResource(R.drawable.sending_black);
msgListView.setAdapter(chatAdapter);
} else sendButton.setImageResource(R.drawable.like); msgListView.setAdapter(emojiAdapter);
}
#Override
public void afterTextChanged(Editable s) {
if (msg_edittext.getText().length()>0) {
sendButton.setImageResource(R.drawable.sending_black);
msgListView.setAdapter(chatAdapter);
} else sendButton.setImageResource(R.drawable.like); msgListView.setAdapter(emojiAdapter);
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendTextMessage(v);
}
});
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
public void sendTextMessage(View v) {
String message = msg_edittext.getEditableText().toString();
if (!message.equalsIgnoreCase("")) {
final ChatMessage chatMessage = new ChatMessage(user1, user2,
message, "" + random.nextInt(1000), true);
chatMessage.setMsgID();
chatMessage.body = message;
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
chatAdapter.add(chatMessage);
chatAdapter.notifyDataSetChanged();
}
}
public void sendEmojiMessage(View v) {
String message = msg_edittext.getEditableText().toString();
android.support.v7.widget.AppCompatImageView emoji = (android.support.v7.widget.AppCompatImageView) getView().findViewById(R.id.message_image);
emoji.setImageResource(R.drawable.like);
if (message.equalsIgnoreCase("")) {
final EmojiMessage emojiMessage = new EmojiMessage(user1, user2, emoji, "" + random.nextInt(1000), true);
emojiMessage.body = emoji;
emojiMessage.Date = CommonMethods.getCurrentDate();
emojiMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
emojiAdapter.add(emojiMessage);
emojiAdapter.notifyDataSetChanged();
}
}
}
chatbubble.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imagebubble_layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/imagebubble_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:layout_marginLeft="56dp"
android:background="#android:color/transparent">
<android.support.v7.widget.AppCompatImageButton
android:id="#+id/message_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/transparent"
app:srcCompat="#drawable/like"/>
</LinearLayout>
imagechatbubble.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imagebubble_layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/imagebubble_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:layout_marginLeft="56dp"
android:background="#android:color/transparent">
<android.support.v7.widget.AppCompatImageButton
android:id="#+id/message_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/transparent"
app:srcCompat="#drawable/like"/>
</LinearLayout>
First, we need to test emoji is easily send to listView which has text above it.
You may add interface in activity which calls from the adapter.
The interface will call the TextChangedListener which eventually display send button or emoji.

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

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

get onclick for button in listview, in fragment

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;
}

Contact list with checkBox, to select for the group mesage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to make the contact list with checkboxs. So I have to select the contacts to send a group message ; I tried this code but it doesn't work...
What can you suggest to me what to do further to get the contact list.
MainActivity.java
package com.example.cont1;
import java.util.ArrayList;
import com.example.cont.MainActivity;
import com.example.listo1.Demo;
import com.example.listo1.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
StringBuilder sb= new StringBuilder();
String str;
ListView tx;
private Contact selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
class ast extends AsyncTask<String, Void, String> {
String name, phone;
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "", "loading");
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, str);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//textDetail.setText(sb);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String phone = null;
if (cur.getCount() > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append("\n " + name + "\n" + phone);
sb.append("\n............................\n");
str=sb.toString();
}
phones.close();
}
return null;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, String.valueOf(getListView().getCheckedItemCount()), Toast.LENGTH_LONG).show();
return true;
}
}
Contact.java
package com.example.cont1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Contact extends ArrayAdapter {
private MainActivity list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Contact(Context context, String[] values) {
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.activity_main, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.textView1);
ImageView btn=(ImageView)v.findViewById(R.id.icon);
if (convertView == null) {
v = vi.inflate(R.layout.activity_main, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.textView1);
text1.setText(values[position]);
LinearLayout layout_item = (LinearLayout) v.findViewById(R.id.linear);
//Set the background and text color
if (position % 2 == 0) {
layout_item.setBackgroundColor(context.getResources().getColor(R.color.black));
text1.setTextColor(context.getResources().getColor(R.color.white));
} else {
layout_item.setBackgroundColor(context.getResources().getColor(R.color.white));
text1.setTextColor(context.getResources().getColor(R.color.black));
}
return v;
}
}
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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=".MainActivity">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"/>
<ImageView
android:id="#+id/icon"
android:layout_width="22px"
android:layout_height="22px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px">
</ImageView>
</LinearLayout>
</ScrollView>
</LinearLayout>
rowLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
It appears that it's quite complicated to do it with an Async Task but here is a Snippet coming from https://stackoverflow.com/a/17878191/2545832 but a bit more complete (but still quite simple) which is working (I tested it):
Main Activity:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lvCallList;
ProgressDialog pd;
ArrayList<String> aa = new ArrayList<String>();
ArrayList<String> num= new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvCallList = (ListView) findViewById(R.id.list);
new AsyncTask<Void, Void, Void>()
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(MainActivity.this,
"Loading..", "Please Wait", true, false);
}// End of onPreExecute method
#Override
protected Void doInBackground(Void... params)
{
getContacts();
return null;
}// End of doInBackground method
#Override
protected void onPostExecute(Void result)
{
pd.dismiss();
CustomAdapter cus = new CustomAdapter(MainActivity.this);
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
lvCallList.setAdapter(cus);
}//End of onPostExecute method
}.execute((Void[]) null);
}
private void getContacts()
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
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));
aa.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id},
null);
while (pCur.moveToNext())
{
String phoneNumber = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
num.add(phoneNumber);
}
pCur.close();
}
}
}
}
public class CustomAdapter extends BaseAdapter
{
/*
* Variables Declaration section
*/
private Context mContext;
public CustomAdapter(Context context)
{
mContext = context;
}//End of CustomAdapter constructor
public int getCount()
{
return aa.size();
}//End of getCount method
public Object getItem(int position)
{
return position;
}//End of getItem method
public long getItemId(int position)
{
return position;
}//End of getItemId method
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
final int pos = position;
if (convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.display_contact, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.textView1);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.textView2);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}//End of if condition
else
{
holder = (ViewHolder) convertView.getTag();
}//End of else
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
holder.textviewName.setText(aa.get(position));
holder.textviewNumber.setText("No. "+num.get(position));
holder.id = position;
return convertView;
}//End of getView method
}//End of CustomAdapter instance inner class
static class ViewHolder
{
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
int id;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"/>
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox1"/>
</LinearLayout>
I saw in your code that you were able to select many items so it mustn't be a problem for you to select many contacts from this list. You've two options : listener on each checkboxes or a long click listener on the list.
Good luck :)

how to display contact numbers in MultiAutoCompleteTextView insted of displaying names

I am selecting multiple contacts using MultiAutoCompleteTextView it is displaying contact names like ramu,raju like that instead of displaying contact name how can i display contact number like 9999999999,8888888888 in MultiAutoCompleteTextView
my activity_main.xml
<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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<MultiAutoCompleteTextView
android:id="#+id/contacts"
android:textSize="18sp"
android:layout_margin="8px"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
and MainActivity.java
package com.example.multiplecontactselect;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor peopleCursor = getContentResolver().query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION, null, null, Contacts.People.DEFAULT_SORT_ORDER);
ContactListAdapter contactadapter = new ContactListAdapter(this,peopleCursor);
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.contacts);
textView.setAdapter(contactadapter);
textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
public static class ContactListAdapter extends CursorAdapter implements Filterable {
public ContactListAdapter(Context context, Cursor c) {
super(context, c);
mContent = context.getContentResolver();
// System.out.println(mContent);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
final TextView view = (TextView) inflater.inflate(
android.R.layout.simple_dropdown_item_1line, parent, false);
view.setText(cursor.getString(5));
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView) view).setText(cursor.getString(5));
}
#Override
public String convertToString(Cursor cursor) {
return cursor.getString(5);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) {
return getFilterQueryProvider().runQuery(constraint);
}
StringBuilder buffer = null;
String[] args = null;
if (constraint != null) {
buffer = new StringBuilder();
buffer.append("UPPER(");
buffer.append(Contacts.ContactMethods.NAME);
buffer.append(") GLOB ?");
args = new String[] { constraint.toString().toUpperCase() + "*" };
}
//System.out.println(constraint);
Log.d("hai", (String) constraint);
return mContent.query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION,
buffer == null ? null : buffer.toString(), args,
Contacts.People.DEFAULT_SORT_ORDER);
}
private ContentResolver mContent;
}
private static final String[] PEOPLE_PROJECTION = new String[] {
Contacts.People._ID,
Contacts.People.PRIMARY_PHONE_ID,
Contacts.People.TYPE,
Contacts.People.NUMBER,
Contacts.People.LABEL,
Contacts.People.NAME,
};
}
change in manifast.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />

Categories

Resources