i need some help with a contacts picker class that ive got.
The class retrieves the contacts list and allows me to choose one, but when I go and choose another one, it just replaces the first one.
I want to make a list of contacts in my app and not only one.
Thank you,
Noam
The Code:
public static final int PICK_CONTACT = 1;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
TextView tv = (TextView) findViewById(R.id.txtSelContact);
tv.setText(name + "-" + phoneNumber);
}
break;
}
}
}
}
And here is the on create function:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
}
This is the layout.xml (for some reason it didn't let me post the code so i linked to an image) :
https://imagizer.imageshack.us/v2/516x255q90/4/igi5.png
Lines 29 - 35:
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
as far as I see you are writing results into the same textview:
//Set
TextView tv = (TextView) findViewById(R.id.txtSelContact);
tv.setText(name + "-" + phoneNumber);
You could specify a Listview in your Layout
<ListView
android:id="#+id/ContactListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
and use an arrayadapter to add your result to this Listview:
public class MainActivity extends Activity {
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
final ListView lv = (ListView) findViewById(R.id.contactListView);
lv.setAdapter(arrayAdapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + "-" + phoneNumber);
arrayAdapter.notifyDataSetChanged();
}
break;
}
}
}
}
Related
I have a java code that displays the numeric soft keyboard in Android:
public class MainActivity extends Activity {
EditText ed1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = (EditText) findViewById(R.id.editText1);
ed1.setInputType(InputType.TYPE_CLASS_NUMBER);
}
}
My activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="numberkeypad.inputmethod.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10" >
</EditText>
The output is: numeric soft keyboard
I want to display the same keyboard using NDK JNI call and no EditText. I have implemented the default keyboard in this way using the following link:
How to show the soft keyboard on native activity
But I am facing a lot of trouble using the same methodology for the numeric keyboard. Any help would be great..Thanks!
Could not find a way to do this directly, had to override the onCreateInputConnection method of View class, and then make a JNI call to a function using the overridden method.
public class NumbersView extends View {
public NumbersView(Context context) {
super(context);
}
#Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection inputConnection = super.onCreateInputConnection(outAttrs);
switch(SystemKeyboardType){
case InputType.TYPE_CLASS_PHONE:
outAttrs.inputType |= InputType.TYPE_CLASS_PHONE;
break;
case InputType.TYPE_CLASS_TEXT:
outAttrs.inputType |= InputType.TYPE_CLASS_TEXT;
break;
case InputType.TYPE_CLASS_NUMBER:
outAttrs.inputType |= InputType.TYPE_CLASS_NUMBER;
break;
case InputType.TYPE_CLASS_DATETIME:
outAttrs.inputType |= InputType.TYPE_CLASS_DATETIME;
break;
default:
outAttrs.inputType |= InputType.TYPE_CLASS_TEXT;
break;
}
return inputConnection;
}
}
**/
#Override
protected void onCreate(Bundle savedInstanceState) {
calculateDeviceDPI();
super.onCreate(savedInstanceState);
myView = new NumbersView(getApplicationContext());
addContentView(myView,new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
myView.setFocusable(true);
myView.setFocusableInTouchMode(true);
//myView.requestFocus();
mContext = this;
}
public void displaySystemKeyboard(String keyboardType){
if(keyboardType.equals("text")) {
SystemKeyboardType = InputType.TYPE_CLASS_TEXT;
}
else if(keyboardType.equals("phone")) {
SystemKeyboardType = InputType.TYPE_CLASS_PHONE;
}
else if(keyboardType.equals("number")) {
SystemKeyboardType = InputType.TYPE_CLASS_NUMBER;
}
else if(keyboardType.equals("datetime")) {
SystemKeyboardType = InputType.TYPE_CLASS_DATETIME;
}
else {
SystemKeyboardType = InputType.TYPE_CLASS_DATETIME;
}
Context ctx = getApplicationContext();
InputMethodManager mgr = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
myView.requestFocus();
// only will trigger it if no physical keyboard is open
mgr.restartInput(myView);
mgr.showSoftInput(myView, 0);
}
public void hideSystemKeyboard(){
Context ctx = getApplicationContext();
View myView = this.getWindow().getDecorView();
InputMethodManager mgr = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(myView.getWindowToken(), 0);
}
And finally made a JNI call to the function:
if(pShow){
jmethodID showSysKeys = lJNIEnv->GetMethodID(lClassDeviceAPI,"displaySystemKeyboard","(Ljava/lang/String;)V");
if(showSysKeys == NULL){
LOGI("displaySystemKeyboard::Couldn't get void displaySystemKeyboard Method");
return;
}
jstring keyboardType = lJNIEnv->NewStringUTF(KeyboardType.c_str());
if(!keyboardType)
{
LOGI( "failed to alloc param string in java." );
return;
};
lJNIEnv->CallVoidMethod(lObjDeviceAPI,showSysKeys, keyboardType);
}
else{
jmethodID hideSysKeys = lJNIEnv->GetMethodID(lClassDeviceAPI,"hideSystemKeyboard","()V");
if(hideSysKeys == NULL){
LOGI("hideSystemKeyboard::Couldn't get void hideSystemKeyboard Method");
return;
}
lJNIEnv->CallVoidMethod(lObjDeviceAPI,hideSysKeys);
}
lJavaVM->DetachCurrentThread();
I have two activities namely mainactivity and main2activity. Mainactivity has three buttons and main2activity has list view.
When I click button string is passed to main2activity and is displayed in main2activity.
So now I want also image in listview. corresponding image for button selected. Below are my codes.
MainActivity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button addButton;
String text1 ="Item 1";
String text2 ="Item 2";
String text3 ="Item 3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("text",text1);
startActivity(intent);
}
});
Button button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("text",text2);
startActivity(intent);
}
});
Button button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("text",text3);
startActivity(intent);
}
});
}
Main2activity
public class Main2Activity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
#Override
protected void onRestart() {
super.onRestart();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Global.list1);
listView.setAdapter(adapter);
if (Global.list1.size() < 1) {
Global.list1 = new ArrayList<>();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent1 = getIntent();
listView = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Global.list1);
listView.setAdapter(adapter);
String havestring = intent1.getStringExtra("text");
if (havestring != null) {
Global.list1.add(havestring);
adapter.notifyDataSetChanged();
}
Button backbtn = (Button) findViewById(R.id.backbtn);
backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageview"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<TextView
android:id="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp" />
</LinearLayout>
So how to set custom adapter that will add corresponding image with string added.
Can it be done using if else statement in custom adapter???
Please do help me
for same.
Can anyone help me out???
I'm trying to save to a database using the code below.
Logcat shows values as empty (client, email, address, balance).
It seems the TextViews are not being passed into the OnOptionsItemSelected method. Any idea of how I can pass the TextViews from OnCreate method to OnOptionsItemSelected?
public class NewClient extends Activity {
private ActionBar actionBar;
//private DatabaseHandler dbHelper;
static SimpleCursorAdapter dataAdapter;
private TextView client_name;
TextView client_code;
TextView email;
TextView addressline1;
TextView addressline2;
TextView balance;
ClientsFragment client = new ClientsFragment();
//String carried_code;
//String carried_name;
DatabaseHandler db;
static Cursor cursor;
private TextView ObtainAdd;
private String ObtainAdd1;
private String ObtainAdd2;
public static TextView textViewC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_client);
db = new DatabaseHandler(this.getApplicationContext());
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
// dbHelper.open();
// Get the layout inflater
client_code = (TextView)findViewById(R.id.code_field);
//set
//get the Text-view for
client_name = (TextView)findViewById(R.id.client_name_field);
email = (TextView)findViewById(R.id.invoice_email_add_field);
addressline1 = (TextView)findViewById(R.id.contact_info_field);
balance = (TextView)findViewById(R.id.balance_field);
//Generate ListView from SQLite Database
// displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.client_activity_actions, menu);
final View menuItemView = findViewById(R.id.action_save);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_save:
openSave();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSave() {
String Updated_Name = client_name.getText().toString();
// TextView prod_price = (TextView) newProd.findViewById(R.id.price_text);
String Updated_code = client_code.getText().toString();
String Updated_email = email.getText().toString();
String Updated_add1 = addressline1.getText().toString();
String Updated_add2 = "add2";// addressline2.getText().toString();
String Updated_balance = balance.getText().toString();
//get double value of code
//updating products
// product.setID(position);
client.setClientName(Updated_Name);
client.setCode(Updated_code);
client.setEmail(Updated_email);
client.setAddressl1(Updated_add1);
client.setAddressl2(Updated_add2);
client.setBalance(Updated_balance);
//update database
// db.updateProduct(product);
db.addClient(client);
// db.close();
// cursor.close();
//cursor = db.getAllProducts();
displayListView();
//dataAdapter = new SimpleCursorAdapter(this, R.layout.list_entry, cursor, columns, to, 0);
//dataAdapter.swapCursor(NewClient.cursor);
//startActivity(new_client_intent);
}
private void displayListView() {
cursor = db.getAllClients();
}
}
I fixed it by removing the Inflater for the textView out of the onCreate method. Now it works perfectly :-)
[Activity]
public class MainActivity : Activity
{
public string[] items = new string[100]; // string to store data from editText
int i =0;
ArrayAdapter<string > adapter;
protected override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
SetContentView(R.Layouts.MainLayout);
var btn1= FindViewById <Button> (R.Ids.btn1);
btn1.Click += AddItem; // calls a function on button click to add data to listview
}
public void AddItem(object sender,EventArgs eventargs)
{
try
{
var et1 = FindViewById <EditText>(R.Ids.et1);
items[i] = et1.Text.ToString();
i++;
view(); //to add data to listview
}
catch(Exception ex)
{
error(ex.ToString());
}
}
public void view ()
{
adapter = new ArrayAdapter<string>(GetApplicationContext(),Android.R.Layout.Simple_list_item_1,items);
ListView listview = FindViewById<ListView>(R.Ids.listview1);
listview.SetAdapter(adapter);
listview.SetTextFilterEnabled(true);
}
}
You should not call view() from AddItem because all code in view is initialization code. Rename it initList or so and call it from OnCreate.
You also don't need items (or i). Just add the string to adapter.
-- EDIT
[Activity]
public class MainActivity : Activity
{
private ArrayAdapter<string> adapter;
protected override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
SetContentView(R.Layouts.MainLayout);
ListView list = FindViewById<ListView>(R.Ids.list);
adapter = new ArrayAdapter<string>(this, Android.R.Layout.Simple_list_item_1);
list.SetAdapter(adapter);
Button button = FindViewById<Button>(R.Ids.button);
button.Click += button_Click;
}
void button_Click(object sender, EventArgs e)
{
EditText text = FindViewById<EditText>(R.Ids.text);
adapter.Add(text.Text.ToString());
}
}
I have a simple app, in one activity I take name and date of birth. I store it in the database. and in the main activity I have linearlayout which will show all the names.
When I click on any of the name in the main activity, it should delete that name from the database and also refresh the view.
I am able to delete the entry from database, but my linear layout view is not being updated. Can some one pls help.
public class child extends Activity {
private Intent intent;
private LinearLayout layout;
private LayoutInflater linflater;
private int i =0;
private Cursor cr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child);
layout = (LinearLayout)findViewById(R.id.layout);
Button addBtn = (Button)findViewById(R.id.AddButton);
Button remBtn = (Button)findViewById(R.id.RemoveButton);
intent = new Intent(this,login.class);
layout = (LinearLayout) findViewById(R.id.mylayout1);
linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Check the database if there are any entries available. If available, then
//list them on the main screen
final myDBAdapter mydb = new myDBAdapter(getApplicationContext());
mydb.open();
cr = mydb.GetMyData();
if(cr.getCount()>0)
{
cr.moveToFirst();
for (int i=0;i<cr.getCount();i++)
{
cr.moveToPosition(i);
buildList(cr.getString(1),cr.getString(2));
}
}
//Start the login activity which will return the newly added baby name
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(intent, 1001);
}
});
//Remove all the entries from Database
remBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(cr.getCount()>0)
{
cr.moveToFirst();
for (int i=0;i<cr.getCount();i++)
{
Toast.makeText(getApplicationContext(), cr.getString(1),
Toast.LENGTH_LONG).show();
mydb.RemoveEntry(cr.getString(1));
cr.moveToPosition(i);
}
}
}
});
mydb.close();
}
private void buildList(final String bname,String bsex)
{
final View customView = linflater.inflate(R.layout.child_view,
null);
TextView tv = (TextView) customView.findViewById(R.id.TextView01);
//tv.setId(i);
tv.setText(bname);
tv.setTextColor(getResources().getColor(R.color.black));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDBAdapter mydb = new myDBAdapter(getApplicationContext());
mydb.open();
if (mydb.RemoveEntry(bname)>0)
{
Toast.makeText(getApplicationContext(), "Row deleted",
Toast.LENGTH_LONG).show();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
WHAT IS REQUIRED HERE TO UPDATE THE VIEW???
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
Toast.makeText(getApplicationContext(), "Row not deleted",
Toast.LENGTH_LONG).show();
}
}
});
layout.addView(customView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 1001)
{
if(resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
buildList(extras.getString("bname"),extras.getString("bsex"));
}
}
}
}
Hmm I'm also trying to get this to work, Have you tried looking at maybe refreshing the LinearLayout every say 5 seconds using a game loop? This may prove to be useful as it helped me with my problem http://aubykhan.wordpress.com/2010/04/25/android-game-programming-the-game-loop/
You may also be able to call onCreate(Bundle) function again while this is a terrible terrible way to do this it will work.