Call onActivityResult for contact in OnCreate() Android - android

I got this code from another question but I don't know how to call this onActivityResult() class in my onCreate() activity to display the first contact from my phone. Also, what does "if (requestCode == RQS_PICKCONTACT){" and "RQS_PICKCONTACT" stand for? Could someone please clarify?
public class MainActivity extends Activity {
Button buttonReadContact;
TextView textPhone;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
buttonReadContact.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//Start activity to get contact
/*final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
*/
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {
if(requestCode == RQS_PICKCONTACT) {
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if (cursor.moveToNext()) {
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
textPhone.setText("0"+stringNumber);
}
} else {
textPhone.setText("NO Phone Number");
}
} else {
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}

When you call startActivityForResult(intent,requestCode)
onActivityResult is called when user comes back to calling activity with
requestCode
//You can start multiple activities by calling startActivityForResult so this value is to differentiate between them
resultCode
//This value is set by the called activity to indicate whether the intended operation was a success or not.
data
//this is an object of type Intent which contains data returned by called activity.
in your code when this part is executed:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, RQS_PICKCONTACT);
New activity is started and when user comes back from that activity by selecting a contact onActivityResult is called

onActivityResult is called after u startIntent or u select an contact.
RQS_PICK_CONTACT u can change as u want. like 2 , 3,4 or another number.
it just identity for requestCode in onActivityResult so u can do as u need.

Related

Picking a number from a contact but removing the country code

I am able to get the contact phone number on button click then transfer it to an EditText, but I want only to get the result without the country code. Exemple : +33 xx xx xx xxx becomes xx xx xx xxx
Is there a way I can achieve this?
The following code I use to get the number and put it in an EditText:
Button click:
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == 1) && (resultCode == RESULT_OK)) {
Cursor cursor = null;
try {
Uri uri = data.getData();
cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
if (cursor != null && cursor.moveToNext()) {
String phone = cursor.getString(0);
editText.setText(phone);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use the libphonenumber library from Google. Don't try to create your own logic, as format varies from location to location.
Try to use replaceall. For example:
String phone = cursor.getString(0);
phone = phone.replaceAll("+33", "");
editText.setText(phone);

Call Image from Gallery/ImageButton to Canvas (DrawingView)

can anyone help me to solve this problem, how to call image from gallery/imagebutton to canvas for drawing?
this is my snippet code :
buah1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), BelajarMewarnai.class);
startActivity(intent);
}
});
If anyone need a project I will send my project to email.
Actually i wanted to post the link in the comment for u but u seemed to bit less fimiliar with android(i thinking so), So i am posting my code to do that. First choose on which button click u want the user to be guided to gallery(only default gallery and not anything else, u may get a null pointer if u choose pic from any other).
On that button click u do this:
private void onClickOfButton(View v){
Intent galleryIntent=new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(Intent.createChooser(galleryIntent, "pic-select"), 10);//(10 its just a request code, u can give ur own, but same should there at receiving end )
}
Since u have started an activity for result, so u should be awaiting for a result from that started activity, so that activity will bring u the image and in ur activity u just collect it and put it into ur image view like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==10 && resultCode==Activity.RESULT_OK){
try{
Uri selectImageUri=data.getData();
String selectedImagePath=getPath(selectImageUri);
Bitmap pic=BitmapFactory.decodeFile(selectedImagePath);
if(pic!=null){
yourImageView.setImageBitmap(pic);
}
}catch(NullPointerException ex){
Toast.makeText(getActivity().getBaseContext(), "Go to default gallery area and choose a pic", Toast.LENGTH_LONG).show();
}
}
else
super.onActivityResult(requestCode, resultCode, data);
}
The getPath method:
private String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
So this will do ur job...
try this:
buah1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), BelajarMewarnai.class);
Bundle bundle = new Bundle();
//Get the image name you clicked on
String imageName = getResources().getResourceName(imageId);;
//Send the image name as a string, which you want to load in the other activity
bundle.putString("image_to_load", imageName.split("/")[1].toString());
intent.putExtras(bundle);
startActivity(intent);
}
});
then you can get your image name in the next activity in onCreate like this:
//Here you can get the image name you already clicked in the previous activity to load in your canvas
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String image_name = bundle.getString("image_to_load")
}
then you can set the image name to your imageView like this:
//Here you can get all resources in res folder
Resources res = getResources();
//define a new string which takes the image name you get from extras in the above code
String mDrawableName = image_name;
//Now you have the image name you clicked in theprevious activity, and ResID is to get the resource id from its name
int resID = res.getIdentifier(mDrawableName, "drawable", getPackageName());
//Here you can get the drawable from the resourceID you obtained in the above line
Drawable drawable = res.getDrawable(resID );
YOUR_IMAGE is the ImageView of the canvas you want to load the image inside in order to draw or whatever you want to do
drawView.setBackgroundDrawable(drawable);
I hope this will help..

startChildActivity issue when working with TabGroupActivity

Fallowing is Home class. I am going to call Pick_contact intent. When ContactNumber view is clicked, device contact list is shown. And the result of picked contact is getting on TabGroupActivity.
public class Home extends Activity{
private static int PICK_CONTACT= 1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
}
public void ContactNumber(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
parentActivity = (TabGroupActivity)getParent();
parentActivity.startActivityForResult(intent, PICK_CONTACT);
}
}
My TabGroupActivity code is shown below.
public class TabGroupActivity extends ActivityGroup {
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_CONTACT)
{
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
String cNumber="";
if (c.moveToFirst()) {
String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex("data1"));
System.out.println("number is:"+cNumber);
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
QRCodeStaticData.qr_contents=name;
}
}
}
}
}
In this above code when user pick up contact from list, I want to open other child activity. But if user does not pick up contact and just cancel it, user will leave on the home activity. I am not getting how to call child activity inside TabGroupActivity after picking contact. I used below code to call child activity.
Intent intent = new Intent(getParent(), CreateQRCode.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("CreateQRCode", intent);
But it does not work inside onActivityResult of TabGroupActivity.
Try this...Sorry for the Late Answer
In your TabGroupActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost) findViewById(android.R.id.tabhost);
// Adding the Activities to the tab view
// Blah Blah
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
System.out.println("Success");
if (requestCode == PICK_CONTACT) {
//Here you can launch the Child Activity according to the index
//Here CreateQRCode Activity index is 1 in the TabView
tabHost.setCurrentTab(1);
}
} else {
System.out.println("Fail");
}
}
In your HomeActivity
public void ContactNumber(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}

Control back button functionality

From the given ListView in picture, I select the contact to send sms and move to another activity (second picture). And from this sms Activity picture. When I press back hardware button available on phone, I should move where I want. I don't want a default Activity to be displayed. How can I do this?
public class SendSms extends Activity{
ListView listView;
List<RowItems> rowItems;
CustomListViewAdapter adapter;
String toNumbers = "";
String separator;
int i=0,j,count=0,count1; String a[]=new String[5];
String number,val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new4);
listView = (ListView) findViewById(R.id.list);
rowItems = new ArrayList<RowItems>();
val2=getIntent().getStringExtra("name");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
// ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
}, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[] { rawContactId }, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
//int type = c.getInt(1);
String name = c.getString(1);
int photoId = c.getInt(2);
Bitmap bitmap = queryContactImage(photoId);
RowItems p=new RowItems(bitmap, number, name);
rowItems.add(p);
}
adapter = new CustomListViewAdapter(this,
R.layout.new5, rowItems);
listView.setAdapter(adapter);
c.close();
}
}
}
}
private Bitmap queryContactImage(int imageDataRow) {
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO
}, ContactsContract.Data._ID + "=?", new String[] {
Integer.toString(imageDataRow)
}, null);
byte[] imageBytes = null;
if (c != null) {
if (c.moveToFirst()) {
imageBytes = c.getBlob(0);
}
c.close();
}
if (imageBytes != null) {
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
} else {
return null;
}
}
public void showResult(View v) {
// String result = "";
String result1="";
for (RowItems p : adapter.getBox()) {
if (p.chck){
// result += "\n" + p.getTitle();
result1 +="\n" +p.getDesc();
a[i]=p.getTitle();
i++;
count++;
}
count1=count;
}
Toast.makeText(this, result1+"\n", Toast.LENGTH_LONG).show();
}
public void send(View v) throws IOException {
int value=a.length-count1;
for(j=0;j<a.length-value;j++){
if(android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")){
separator = ",";
} else
separator = ";";
number = a[j];
toNumbers= toNumbers +number +separator;
}
toNumbers = toNumbers.substring(0, toNumbers.length());
Uri sendSmsTo = Uri.parse("smsto:" + toNumbers);
String smsValue = "help iam in danger..i am presently at \n"+val2;
if(val2==null){
Toast.makeText(SendSms.this, "wait.....", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", smsValue);
intent.setData(sendSmsTo);
startActivity(intent);
}
Use startAtctivityForResult, and in onActivityResult check the resultCode. If it is Activity.RESULT_CANCELLED, the user 'backed out' of the SMS activity. Due to the implementation of the SMS activity being outside of your control, this might not be the only case when the result code says it has been cancelled.
I think you should, when the Activity picture is displayed, try to call the onBackPressed method.
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// new intent to call an activity that you choose
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// finish the activity picture
this.finish();
}
If you don't want to call an external Activity, you can hide the layout calling by the Intent as below:
// back button pressed method
#Override
public void onBackPressed() {
super.onBackPressed();
// your layout with the picture is displayed, hide it
if(MySecondView.getVisibility() == View.VISIBLE)
MySecondView.setVisibility(View.Gone);
// display the layout that you want
MyDefaultView.setVisibility(View.VISIBLE);
}
As I said below, try with a boolean that you initialize to false at the beginning of your Class. When you start the Intent.ACTION_VIEW, make this boolean to true:
public class Foo extends Activity {
private boolean isSms = false;
// some stuff
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
// ...
startActivity(intent);
// make your boolean to true
isSms = true;
// create the onBackPressed method
#Override
public void onBackPressed() {
// check if the user is on the sms layout
if(isSms)
// do something
else
// do something else like finish(); your activity
}
}
Or you can try to use the onKeyDown method (see here: onKeyDown (int keyCode, KeyEvent event)) as below:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0) {
// dome some stuff
return true;
}
return super.onKeyDown(keyCode, event);
}
You can see the diffence between these two methods here: onBackPressed() not working and on the website that I talk in the comments below.
Hope this will be useful.
UPDATE:
A better way should make an startActivityForResult to start the Intent.ACTION_VIEW:
startActivityForResult(intent, 1);
And then, you return the cancel code like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != 1 && resultCode == RESULT_CANCELED) {
// do something
}
}
This is #FunkTheMonk, just above, who tells the good choice!
Add this method to the class to handle device back button.
#Override
public void onBackPressed() {
// do something
}
Please note that it requires API Level 5 or higher.
You have to overide go back behaviour of hardware back button by calling a method name onbackpressed();
#Override
public void onBackPressed() {
super.onBackPressed();
// set intent to activity where you want to move on after back press
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
// also clean the current activity from stack.
youractivityname.this.finish();
}

Android - Passing database and id through activities

I have 2 android activity's
One where I have a room list, i.e. list of rooms.
The other the room contents. Where all the content of a selected room is displayed.
All I want is for the room id(r_id) to be passed through the room list class into the room overview class where I can retreive all its contents from the database.
I've been trying to figure out where i'm going wrong, I think its around line 94 - 101:
selectedRoom = (String) ((TextView) view).getText();
Cursor c2 = sampleDB.rawQuery("SELECT * FROM tbl_roomDesc WHERE roomName =?", new String[] {selectedRoom});
if (c2 != null ) {
if (c2.moveToFirst()) {
do {
r_id = c2.getString(c2.getColumnIndex("r_id"));
}while (c2.moveToNext());
}
}
c2.close();
Can anyone help me figure out what i'm doing wrong here?
Here is the source for the room list
Here is the source for the room overview
Thanks in advance!
To pass data between to Intents, use the putExtras() method.
Example:
Intent i = new Intent(...);
i.putExtras("roomid", "10");
startActivity(i);
final int roomId = r_id;
next = (ImageButton) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
CreateBuilding.val = "Retrieve";
sampleDB.close();
Intent intent2 = new Intent(RoomList.this, TabLayoutActivity.class);
intent2.putExtra("roomId", roomId);
setResult(RESULT_OK, intent2);
finish();
startActivityForResult(intent2, 0);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
int roomId = data. getIntExtra("roomId", 0);
}
}
}
If I have not misunderstood you put the roomId inside the Intent and retrieve it inside the onActivityResult

Categories

Resources