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);
Related
after select multi images from gallery on order selection the images goes to the recycle view on random order not as I select on specific order or sort. for example if I select B then A then C but the code always bring them with random sort or order like A C B and sometimes C A B. . the order seems undefined at first I thought android sort them based on date and time added to the gallery or what their name i mean alphabet letter but then I realize the order seems undefined. i'm not sure if I need to add listener with array track the user selections. any suggestion
ArrayList imagesUriArrayList;
public static final int slect_photo = 100;
Bitmap bitmap1 = null;
RecyclerView rec;
LinearLayoutManager lnm;
Adopter_Browse list;
ArrayList<MyCard> mylist;
public void Onclick_View(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, slect_photo);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data.getData() != null) {//data.getData() != null) {
imagesUriArrayList = null;
imagesUriArrayList = new ArrayList();
try{
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
imagesUriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
try {
for (int i = 0; i < imagesUriArrayList.size(); i++) {
bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), (Uri) imagesUriArrayList.get(i));
mylist.add(new MyCard(count_s, bitmap1));
}
} catch (IOException e) {
e.printStackTrace();
}
lnm = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
list = new Adopter_Browse(mylist);
rec.setLayoutManager(lnm);
list.notifyDataSetChanged();
rec.setAdapter(list);
}
I found out that using onActivityResult that provided by google will always return the order of your selection on miss , so maybe a bug or need improve .
I got two option :
1- using ItemTouchHelper library ... helped me to solve my problem !
2- gradle source form githup !
I share this maybe some one can get relief !
So, I have android application using Sqlite Database. I has a cardview to showing the data. In the table, I have field like, name(text), cost(int) and an image(BLOB). I want to update the data. So, when I change and update the name or the cost, the image not updated and return blank or null. But when I change and update the image, it successfully updated.
First, this is my select query to showing the name, cost and image in update class
public ModelProduk getnama(int selection){
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_ID_PRODUK + "=?";
String[] whereargs = new String[]{String.valueOf(selection)};
Cursor cursor = db.query(
TABLE_PRODUK,
null,
whereclause,
whereargs,
null,
null,
null
);
ModelProduk modelProduk = new ModelProduk();
if (cursor.moveToFirst()) {
modelProduk.set_id(Integer.parseInt(cursor.getString(0)));
modelProduk.set_nama(cursor.getString(1));
modelProduk.set_harga(Integer.parseInt(cursor.getString(2)));
modelProduk.set_gambar(cursor.getBlob(3));
}
cursor.close();
db.close();
return modelProduk;
}
Here's my database to update
public void update(ModelProduk modelProduk) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
// update baris
db.update(TABLE_PRODUK, values, where, whereArgs);
db.close();
}
my java class for update
private void init(){
pilih = getIntent().getIntExtra("id_produk", 0);
db = new Database(this);
modelProduk = db.getnama(pilih);
gambar_produku = (ImageView) findViewById(R.id.pilihgambaru);
tambahgambaru = (Button) findViewById(R.id.btaddu);
simpandatau = (Button) findViewById(R.id.btsimpanu);
deskripsiu = (EditText) findViewById(R.id.etdesku);
harga_produku = (EditText) findViewById(R.id.ethargau);
kembaliu = (Button) findViewById(R.id.btkembaliu);
deskripsiu.setText(modelProduk.get_nama());
harga_produku.setText(String.valueOf(modelProduk.get_harga()));
if (modelProduk.get_gambar() != null) {
gambar_produku.setImageBitmap(bitmap(modelProduk.get_gambar()));
}
}
public void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Pilih Gambar"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
gambar_produku.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getImageByte(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[]=null;
if(bitmap!=null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
imageInByte=stream.toByteArray();
}
return imageInByte;
}
public Bitmap bitmap (byte[] byteImage){
byte[] outImage = byteImage;
Bitmap image ;
if (outImage != null){
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
image = BitmapFactory.decodeStream(imageStream);
}else {
image= null;
}
return image;
}
my onclick to save the update
simpandatau.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
modelProduk.set_nama(deskripsiu.getText().toString());
modelProduk.set_harga(Integer.parseInt(harga_produku.getText().toString()));
modelProduk.set_gambar(getImageByte(bitmap));
db.update(modelProduk);
Toast.makeText(getApplicationContext(), "Data Berhasil Diubah!", Toast.LENGTH_SHORT).show();
}
});
Please Help! I have read many solutions but it's not same to my problems.
Thank you!
You could try the following. This will attempt to get the row that is to be updated before updating. However, rather than return blank or null or update successful it returns an integer which can be -1, 0 or 1 which indicates three possible outcomes.
If the row doesn't exist then it will return -1 (NOTUPDATED).
Otherwise it will then compare the stored image against the image passed.
If the images are different then it will add the new image to values and set the value to be returned to 1 (IMAGEUPDATED).
Otherwise the new image is not added to the values and the value to be returned will remain as 0 (IMAGENOTUPDATED). By not adding the image to values the gambar column will not be included in the SET clause of the SQL generated by the update method.
:-
public int update(ModelProduk modelProduk) {
final int NOTUPDATED = -1;
final int IMAGENOTUPDATED = 0;
final int IMAGEUPDATED = 1;
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// get the current row from the database (return -1 if it doesn't exist)
Cursor before_update = db.query(TABLE_PRODUK,null,where,whereArgs,null,null,null);
if (!before_update.moveToFirst) {
before_update.close();
return NOTUPDATED;
}
// Default value to return
rv = IMAGENOTUPDATED;
// Compare the store image against the new image, if not the same
// then include the image in the update
if (!Arrays.equals(before_update.getBlob(3),modelProduk.get_gambar)) {
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
rv = IMAGEUPDATED;
}
before_update.close();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
// Update baris checking to see if an update occurred, if not
// then set return value to -1 (could be a different status code)
if (db.update(TABLE_PRODUK, values, where, whereArgs) = 0) {
rv = NOTUPDATED;
}
db.close();
before_update.close();
return rv;
}
Note the above is in-principle code, it has not been tested and therefore may contain errors.
You may wish to define NOTUPDATED, IMAGENOTUPDATED and IMAGEUPDATED elsewhere with greater scope.
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..
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.
I've a problem using the ContactPicker in Android. My code is the next
public void showContacts(View v){
phoneNumber.setText("");
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, 1001);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1001:
Cursor cursor = null;
String[] numeros = null;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null,
Phone.CONTACT_ID + "=?", new String[] {id}, null);
int phoneIdx = cursor.getColumnIndex(Phone.NUMBER);
if(cursor.getCount() > 0){
numeros = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int cont = 0;
do{
numeros[cont] = cursor.getString(phoneIdx);
cont++;
}while(cursor.moveToNext());
}
}
} catch (Exception e) {
Log.e("Exception", "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
if(numeros != null){
if(numeros.length > 1){
showNumbers(numeros);
}else{
phoneNumber.setText(numeros[0]);
}
}
}
break;
}
}
}
private void showNumbers(final String[] numeros){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(numeros, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo, int item) {
phoneNumber.setText(numeros[item]);
dialogo.cancel();
}
});
builder.create().show();
}
Basically in the first method I call the ContactPicker, in the second I receive the answer of this, I process that and validate if the user have more than one phone.
The problem is, the algorithm return me six times the numbers. I don't know why occur that.