Share multiple messages with same intent chooser in my app - java

I have this code
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
else
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
String activityTitle = cellsList.get(position).getTitle();
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, activityTitle);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setType("image/*");
sharingIntent.setPackage("com.whatsapp");
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sharingIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Intent chooser = Intent.createChooser(sharingIntent,getResources().getString(R.string.share_using));
getActivity().startActivity(chooser);
And I want to share another message that contain text and image to the same chooser app.
Do u have any idea on how to solve the problem?

You can use a ShareActionProvider. In the following sample, I'm using one tied to a MenuItem in the Toolbar, but it's also possible to use them with e.g. a Button.
main_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_item_share"
app:showAsAction="ifRoom"
android:title="Share"
app:actionProviderClass=
"android.support.v7.widget.ShareActionProvider" />
</menu>
activity_main.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sharing.datasender.MainActivity">
<TextView
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="Send data once more"
/>
</FrameLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
private ShareActionProvider shareActionProvider;
private Intent shareIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.view2);
view.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
sendDataOnceMore();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
shareActionProvider = (ShareActionProvider)MenuItemCompat.getActionProvider(item);
setShareIntent(getShareIntent());
shareActionProvider.setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener()
{
#Override
public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent)
{
ComponentName component = intent.getComponent();
shareIntent = intent;
String className = null;
if (component != null)
{
className = component.getClassName();
}
Log.d("TEST", "onShareTargetSelected: *" + className + "*");
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
switch (id)
{
case R.id.menu_item_share:
Intent intent = getShareIntent();
setShareIntent(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private Intent getShareIntent()
{
Intent sharingIntent = new Intent();
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "This is my text to send.");
Uri uri = Uri.parse(IMAGE_PATH);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setType("image/*");
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sharingIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return sharingIntent;
}
private void sendDataOnceMore()
{
if (shareIntent != null)
{
Intent sendIntent = new Intent();
try
{
sendIntent.fillIn(shareIntent, Intent.FILL_IN_COMPONENT + Intent.FILL_IN_ACTION + Intent.FILL_IN_CATEGORIES + Intent.FILL_IN_PACKAGE);
sendIntent.putExtra(Intent.EXTRA_TEXT, "And another thing...");
sendIntent.setType("text/plain");
sendIntent.setAction(Intent.ACTION_SEND);
startActivity(sendIntent);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Boooom!", Toast.LENGTH_LONG).show();
return;
}
}
else
{
Toast.makeText(this, "No Go :(", Toast.LENGTH_LONG).show();
return;
}
}
// Call in onCreateOptionsMenu() or the MenuItem will not be clickable!
// Call later to update the share Intent
private void setShareIntent(Intent shareIntent)
{
if (shareActionProvider != null)
{
shareActionProvider.setShareIntent(shareIntent);
}
}
}
Remember to make sure that sendIntent.resolveActivity() != null if you're using this much later - the other app may have been uninstalled in the meantime!

Related

Upload Image on Firebase Storage

Hi I want to add an image on firebase storage with android studio but firebase doesn't accept my upload. I changed the rule to allow the write and read and my match folder allows all path.Thus I am confused. Here is the part of my code who should put the image in my database.
If you know how to resolve this problem i would be glad to ear a solution
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
image_uri = data.getData();
uploadPicture();
ProfileImage.setImageURI(image_uri);
}
}
private void uploadPicture() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading Image...");
pd.show();
final String randomKey = UUID.randomUUID().toString();
StorageReference riversRef = storageReference.child(("images/" + randomKey + ".jpg"));
Toast.makeText(Create_Profile.this, "Upload success", Toast.LENGTH_SHORT).show();
riversRef.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
name = riversRef.getDownloadUrl().toString();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
pd.setMessage("Percentage: " + (int) progressPercent + "%");
}
});
}
if you don't getting error compare with this simple code
thank you
firebase storage dependency
implementation 'com.google.firebase:firebase-storage:19.1.0'
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<!--Linear Layout with horizontal orientation
and other properties-->
<LinearLayout
android:id="#+id/layout_button"
android:orientation="horizontal"
android:layout_alignParentTop="true"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--Button for choosing image from gallery-->
<Button
android:id="#+id/btnChoose"
android:text="Choose"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<!--Button for uploading image-->
<Button
android:id="#+id/btnUpload"
android:text="Upload"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<!--Image View for showing image choosen from gallery-->
<ImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
in your Activity
public class MainActivity extends AppCompatActivity {
private Button btnSelect, btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 22;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable
= new ColorDrawable(
Color.parseColor("#0F9D58"));
actionBar.setBackgroundDrawable(colorDrawable);
btnSelect = findViewById(R.id.btnChoose);
btnUpload = findViewById(R.id.btnUpload);
imageView = findViewById(R.id.imgView);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SelectImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
uploadImage();
}
});
}
private void SelectImage()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(
intent,
"Select Image from here..."),
PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data)
{
super.onActivityResult(requestCode,
resultCode,
data);
if (requestCode == PICK_IMAGE_REQUEST
&& resultCode == RESULT_OK
&& data != null
&& data.getData() != null) {
// Get the Uri of data
filePath = data.getData();
try {
Bitmap bitmap = MediaStore
.Images
.Media
.getBitmap(
getContentResolver(),
filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImage()
{
if (filePath != null) {
ProgressDialog progressDialog
= new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref
= storageReference
.child(
"images/"
+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Image Uploaded!!",
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Failed " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
})
.addOnProgressListener(
new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(
UploadTask.TaskSnapshot taskSnapshot)
{
double progress
= (100.0
* taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage(
"Uploaded "
+ (int)progress + "%");
}
});
}
}
}
I found a solution by modifying my firebase Rules to match with the bucket directly and not with the ref of my firebase storage

What is the better way to handle mutiple intents in android?

We come across the following code or something similar in Android or Java many times. This code seems like containing repetitions and this is not a good practice at all. There must be some better way to do this. is there any shorter code to achieve this?
Intent intent=null;
switch (v.getId()) {
case R.id.details:
intent = new Intent(this, DetailsActivity.class);
break;
case R.id.apply:
intent = new Intent(this, ApplyActivity.class);
break;
case R.id.edit:
intent = new Intent(this, EditActivity.class);
break;
case R.id.upload:
intent = new Intent(this, UploadActivity.class);
break;
case R.id.call:
intent = new Intent(this, CallActivity.class);
break;
}
startActivity(intent);
Make a table of ids to activity classes in a static initializer or constructor:
HashMap<Integer, Class<?>> map = new HashMap<>();
map.put(R.id.foo, Foo.class); // repeat for each id/class pair
Then use the map instead of a switch:
startActivity(new Intent(this), map.get(v.getId()));
As I commented use setClass method instead. Do like this.
Set your Activity classname to button tag and get this tag on button click.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="YourActivityName"
/>
Java Code
String classname = (String) textView.getTag();
intent.setClassName(getPackageName().toString(), classname)
startActivity(intent);
Yes Ofcourse. This is not a good practise at all. Try to achieve generalization.
Below is what I put into practice.
Just a think, Why I would write the code again, when it is already written..!!
Thinking that way,
Put all the common code in to a common class
Extend that class
Use its members
Create a class, say BaseAppCompatActivity.java as below:
public abstract class BaseAppCompatActivity extends AppCompatActivity {
private ProgressDialog mProgressDialog;
private Toolbar mToolbar;
private TabLayout mTabLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
initiateViews();
}
protected abstract int getLayoutResourceId();
protected abstract void initiateViews();
public void setHasToolBar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
public Toolbar getToolBar() {
return mToolbar;
}
public void setHasTabLayout() {
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
}
public TabLayout getTabLayout() {
return mTabLayout;
}
public void showProgressDialog() {
showProgressDialog("Please Wait ...");
}
public void showProgressDialog(String message) {
// progress bar not null and is visible, so set the title
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.setMessage(message);
}
// create new progress bar
else {
mProgressDialog = ProgressDialog.show(this, "Loading", message, true, false);
}
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
public void showAlertDialog(String message) {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.create();
alertDialog.setMessage(message);
alertDialog.show();
}
public void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void logInformation(Class tag, String description) {
Log.i(tag.getName(), description);
}
public void logError(Class tag, String description) {
Log.e(tag.getName(), description);
}
public void logDebug(Class tag, String description) {
Log.d(tag.getName(), description);
}
public void launchActivity(Class<? extends Activity> cls, Bundle bundle, int code) {
Intent intent = new Intent();
if (bundle != null)
intent.putExtras(bundle);
intent.setClass(activity, cls);
if (code == -1)
startActivity(intent);
else
startActivityForResult(intent, code);
}
public void loadFragment(Class fragmentClass, boolean addToBackStack) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
if (fragment != null) {
if (addToBackStack) {
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(fragmentClass.getSimpleName())
.replace(R.id.frameLayout, fragment, fragmentClass.getSimpleName())
.commit();
} else {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment, fragmentClass.getSimpleName())
.commit();
}
}
}
}
And after that, extend all your activities to this BaseAppCompatActivity class.
Then, in your code in activity is cut down to just
launchActivity(Activity2.class, null, -1);
You can set tag equal your activity :
<Button
android:id="#+id/btn1"
android:tag="DetailsActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn2"
android:tag="ApplyActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn3"
android:tag="EditActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn4"
android:tag="EditActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn5"
android:tag="DetailsActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn6"
android:tag="CallActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
Java code this : Your package name :com.example.pkg1
Intent intent = new Intent();
intent.setClassName("com.example.pkg1", "com.example.pkg1."+v.getTag() );
startActivity(intent);

Can't write in inflate layout

I'm using a broadcastreceiver in my DrawerActivity in which i can receive a notification from a service and then i would set the text of notification in a layout that is in a fragment (The first fragment of the navigation drawer). So my DrawerActivity is where i start the broadcastreceiver (i tried start it directly from the fragment but it doesn't work!) So this is the broadcastreceiver:
public BroadcastReceiver onNotice= new BroadcastReceiver() {
LinearLayout notificationLayout;
Drawable icon;
#Override
public void onReceive(Context context, Intent intent) {
final String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
View myView = getLayoutInflater().inflate(R.layout.activity_main, null);
notificationLayout = (LinearLayout)myView.findViewById(R.id.notificationLayout);
TextView notificationDescription = (TextView) myView.findViewById(R.id.notificationDesc);
TextView notificationTitle = (TextView) myView.findViewById(R.id.notificationTitle);
CircularImageView notificationImage = (CircularImageView) myView.findViewById(R.id.img_thumbnail);
Log.i("Notification ", title);
Toast.makeText(DrawerActivity.this, title, Toast.LENGTH_SHORT).show();
if(!pack.equals("") || !title.equals("") || !text.equals("")) {
notificationLayout.setVisibility(View.VISIBLE);
notificationTitle.setText("Ciao");
notificationDescription.setText(text);
try {
icon = DrawerActivity.this.getPackageManager().getApplicationIcon(pack);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
notificationImage.setImageDrawable(icon);
notificationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
PackageManager pmi = DrawerActivity.this.getPackageManager();
Intent intent;
intent = pmi.getLaunchIntentForPackage(pack);
if (intent != null) {
DrawerActivity.this.startActivity(intent);
}
//LocalBroadcastManager.getInstance(MainActivity.instance).sendBroadcast(new Intent("collapseAfterClick"));
} catch (Exception ignored) {
}
}
});
notificationLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
notificationLayout.setVisibility(View.INVISIBLE);
return true;
}
});
} else {
notificationLayout.setVisibility(View.INVISIBLE);
}
}
};
in this way it's very strange!!! When a notification arrives the toast inside the Broadcastrecevier is fired but the settext in the inflate layout not! So i can see the notification from the Toast but not in my layout! How is possible?
The issue is the code doesnt enter the if statement.
*if(!pack.equals("") || !title.equals("") || !text.equals(""))*

Why does my Alert Dialog not open?

I have the Problem that the Dialog Box with "Take Photo", "Choose from Gallery" and Cancel isn't showing.
Below I have added the code.
Wizard.Java:
public class Wizard extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.btnSelectPhoto);
viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from
Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Wizard.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new
File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new
Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
Wizard.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" >
<EditText
android:id="#+id/editText1"
android:layout_width="284dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:ems="10"
android:singleLine="true"
android:maxLength="10">
<requestFocus />
</EditText>
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Photo" />
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/camera"/>
</LinearLayout>
You can use custom alertdialog.
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);builder.show();
before you must create dialog_layout.xml
are you sure that it doesn't work? Your code is correct. It could be perfectly show on Nexus 5.

(EditText)Android Contact list getting phone number

I'm new to Android development. I have used ;
I type the number in the EditText, Now i want to get the contact number from my contact list. can someone pls help me to fix this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText pnumber= (EditText) findViewById(R.id.editTextPnumber);
final EditText gsms= (EditText) findViewById(R.id.editTextSMS);
Button sendsms= (Button) findViewById(R.id.buttonSend);
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String gPhone= pnumber.getText().toString();
String gSMS= gsms.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(gPhone, null, gSMS, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent ! ", Toast.LENGTH_LONG).show();
finish();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "PLS Enter Again ! ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
This is a simple trick. I hope you would be able to fix this to your code easily.
You can put a button (SMS) to its setOnClickListener you can use this.
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),
"PLS Enter Again ! ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
If you means that you want wrap input number with matched contact name from your contacts on the device?
For that you want
1) ContactProvider http://developer.android.com/guide/topics/providers/contacts-provider.html
2) AutoComplete http://developer.android.com/guide/topics/ui/controls/text.html#AutoComplete
3) If you want no one number, you could youse some chips. (EditText, Spanned) https://github.com/nichtemna/ChipsEditText#mychipsedittext, https://github.com/kpbird/chips-edittext-library
// try this way here i gave sample or demo code you modify as per your requirement.
1.activity_main.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:padding="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edtNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="phone number"
android:layout_weight="1"/>
<ImageView
android:id="#+id/imgPickUpContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_marginLeft="5dp"/>
</LinearLayout>
<EditText
android:id="#+id/edtMessage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="message"/>
<Button
android:id="#+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send"/>
</LinearLayout>
2.MyActivity
public class MyActivity extends Activity {
private EditText edtNumber;
private EditText edtMessage;
private Button btnSend;
private ImageView imgPickUpContact;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtNumber=(EditText)findViewById(R.id.edtNumber);
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnSend=(Button)findViewById(R.id.btnSend);
imgPickUpContact=(ImageView)findViewById(R.id.imgPickUpContact);
imgPickUpContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent localIntent = new Intent("android.intent.action.PICK", ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(localIntent, 1);
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendSMS(edtNumber.getText().toString(), edtMessage.getText().toString());
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent paramIntent) {
super.onActivityResult(requestCode, resultCode, paramIntent);
if (resultCode == RESULT_OK) {
String str = getPhoneNumber(paramIntent.getData());
if (str.trim().length() > 0) {
edtNumber.setText(str);
edtNumber.setSelection(edtNumber.getText().length());
}
} else {
Toast.makeText(this,"Phone Number Not Founded ...",Toast.LENGTH_SHORT).show();
}
}
private String getPhoneNumber(Uri paramUri) {
String id = "";
String no="";
Cursor cursor = getContentResolver().query(paramUri, null, null, null, null);
while(cursor.moveToNext()){
id = cursor.getString(cursor.getColumnIndex("_id"));
if("1".equalsIgnoreCase(cursor.getString(cursor.getColumnIndex("has_phone_number")))){
Cursor cursorNo = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = " + id, null, null);
while (cursorNo.moveToNext()) {
if (cursorNo.getInt(cursorNo.getColumnIndex("data2")) == 2){
no = no.concat(cursorNo.getString(cursorNo.getColumnIndex("data1")));
break;
}
}
cursorNo.close();
}
}
cursor.close();
return no;
}
private void sendSMS(String paramString1, String paramString2) {
Intent localIntent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:" + paramString1));
localIntent.putExtra("sms_body", paramString2);
startActivity(localIntent);
}
}
3.please define this permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Categories

Resources