I am trying to get URL from string using JAVA. but my variable not working in "Uri.parse" section (no value in variable). please consider i am beginner in coding
Error is : " Cannot assign a value to final variable 'result' "
My code:
showResultDialogue(result.getContents());
..
public void showResultDialogue(final String result) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
Pattern p = Pattern.compile("[\\w\\.]+\\.(?:com|cc|net|ru|in)[^,\\s]*");
Matcher m = p.matcher(result);
builder.setTitle("Example Title")
.setMessage("Text is " + result);
if(m.matches()) {
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(result) // here is problem
);
startActivity(browserIntent);
}
});
}
Since you have provided no information of why it does not work, I am just gonna assume the URL is missing http since you're regex does not match that, in that case I would just do this
Edit: do you really need your regex? Android has a built in way of matching URLS.
You can find the docs here https://developer.android.com/reference/android/util/Patterns
Patterns.WEB_URL.matcher(result).matches();
so your code is gonna look like this
if (Patterns.WEB_URL.matcher(result).matches()) {
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(!result.startsWith("http://") && !result.startsWith("https://") ? "http://" + result : result)
);
startActivity(browserIntent);
}
});
}
Related
Here is my code which request user for their username:
private void request_user_name() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setCancelable(false);
builder.setView(input_field);
final String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
input_field.setSelection(input_field.getText().length());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(TextUtils.isEmpty(savedName)) {
input_field.setError("Your message");
builder.setCancelable(false);
}
else
{
dialogInterface.cancel();
request_user_name();
}
}
});
builder.show();
}
And this is how I pass he username to next Activity:
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
intent.putExtra("default_name","anyonymous");
startActivity(intent);
And this is how I receive the Intent Extra in next Activity:
if (getIntent().getExtras() != null
&& getIntent().getExtras().get("user_name")!=null) {
user_name = getIntent().getExtras().get("user_name").toString();
}else{
user_name = getIntent().getExtras().get("default_name").toString();
}
My problem is when users don't enter his name and it returns null then it returns anyonymous but when users enter his name then it pass user name to next activity. But when I restart the app then again it passes anyonymous to next activity instead of usernae the user already entered
So I need suggestion on how to save the entered username in shared prefrences and use the same in future launch of app unless new name is not entered instead of anyonymous
Thanks in advance.
If you are already using SharedPreferences to store the user_name, then you don't need to pass the user_name via Intent. SharedPreferences are global and could be accessed throughout the application. Just do:
sharedpreferences.getString("username","anonymous")
in your target activity.
Google Developer Console indicates me that my app got java.lang.ClassCastException error on 2 different devices (P10 (HWVTR)-Android 7.0 and LG G3 (g3) - Android 6.0) at the same lane. I don't know what's the problem, I have tested it on Samsung Galaxy A3 2014 & 2017 and Huawei P9 Lite and works great.
Here is the code:
SharedPreferences prefs = this.getSharedPreferences(
"toast", Context.MODE_PRIVATE);
final int hasVisited = prefs.getInt("HAS_VISISTED_BEFORE", 0);
if(hasVisited == 0) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("My Text")
.setMessage("My Text, dsajh jghjsahjhsda dsa dsa")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.show();
prefs.edit().putInt("HAS_VISISTED_BEFORE", 1).apply();
}
The error is here final int hasVisited = prefs.getInt("HAS_VISISTED_BEFORE", 0);
I want to display this AlertDialog only once when the app if run for the first time.
Error log:
Caused by: java.lang.ClassCastException:
at android.app.SharedPreferencesImpl.getInt (SharedPreferencesImpl.java:242)
at com.doggedness_dev.pubgcratessimulator.MenuActivity.onCreate (MenuActivity.java:40)
at android.app.Activity.performCreate (Activity.java:6272)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2387)
It is possible that my SharedPreferences with the key HAS_VISISTED_BEFORE to interfere with another app that has the same key?
Every application has their own shared preferences location, so there is no way to interfere with another app that has the same key.
If your application's older versions have the same key with HAS_VISISTED_BEFORE and its value is not integer, you will have this problem. Because you have already have the value for this key and types are just different.
You can use try-catch like below, for this exception.
try {
}catch (ClassCastException ex){
ex.printStackTrace();
}
Remove this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
and write below line;
builder = new AlertDialog.Builder(MainActivity.this);
i have read several already answered article on this site and used this
Sending message through WhatsApp
i am able to share from chrome but not from app.
my code is
public void onClickWhatsApp(View view) {
PackageManager pm=getPackageManager();
try {
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
String text = "YOUR TEXT HERE";
PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
//Check if package exists or not. If not then code
//in catch block will be called
waIntent.setPackage("com.whatsapp");
waIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(waIntent, "Share with"));
} catch (NameNotFoundException e) {
Toast.makeText(MainActivity.this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}
}
when i click on share button in my android app whatsapp icon it gives error page not found but when same thing is shared from chrome it just works fine.
my url is http://way2enjoy.com/app/jokes.php
if anyone can guide where the mistake is i will be thankful
you can use my code which works for me
void openWhatsappContact(String number) {
Uri uri = Uri.parse("smsto:" + number);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));}
enjoy your code time:)
you can use this code also
//method used to show IMs
private void show_custom_chooser(String value) {
List<ResolveInfo> list = null;
final Intent email = new Intent(Intent.ACTION_SEND);
email.setData(Uri.parse("sms:"));
email.putExtra(Intent.EXTRA_TEXT, "" + value);
email.setType("text/plain"); // vnd.android-dir/mms-sms
WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
.getAttributes();
WMLP.gravity = Gravity.CENTER;
dialogCustomChooser.getWindow().setAttributes(WMLP);
dialogCustomChooser.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialogCustomChooser.setCanceledOnTouchOutside(true);
dialogCustomChooser.setContentView(R.layout.about_dialog);
dialogCustomChooser.setCancelable(true);
ListView lvOfIms = (ListView) dialogCustomChooser
.findViewById(R.id.listView1);
PackageManager pm = getPackageManager();
List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
// ////////////new
list = new ArrayList<ResolveInfo>();
for (int i = 0; i < launchables.size(); i++) {
String string = launchables.get(i).toString();
Log.d("heh", string);
//check only messangers
if (string.contains("whatsapp")) {
list.add(launchables.get(i));
}
}
Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
int size = launchables.size();
adapter = new AppAdapter(pm, list, MainActivity.this);
lvOfIms.setAdapter(adapter);
lvOfIms.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
ResolveInfo launchable = adapter.getItem(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(
activity.applicationInfo.packageName, activity.name);
email.addCategory(Intent.CATEGORY_LAUNCHER);
email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
email.setComponent(name);
startActivity(email);
dialogCustomChooser.dismiss();
}
});
dialogCustomChooser.show();
}
I have the following code for cropping images. It's working perfectly in android version 4 or OS Kitkat, but its not working on Android version 5 or OS Lollipop.
I've already searched the whole world but couldn't find the answer...
Here's my code:
In OS Kitkat: this list variable return a value. but,
In OS Lollipop: this list variable return a empty arraylist.
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
PackageManager test = getPackageManager();
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mCapturedImageURI);
intent.putExtra("outputX", 110);
intent.putExtra("outputY", 110);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mCapturedImageURI != null ) {
getContentResolver().delete(mCapturedImageURI, null, null );
mCapturedImageURI = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
I had already given android.permission.MANAGE_DOCUMENTS permission. But facing the same issue. After searching a lot, i found the solution.
Here's a workaround, for the time being:
Intent mIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(mIntent, CHOOSE_IMAGE);
This forces the older image gallery to open instead of the new Kitkat documents view.
Now, you can get the Uri by calling the following in your onActivityResult:
Uri selectedImageURI = data.getData();
Hope this help to solve your problem.
My code is:
View.OnClickListener menuHandle = new View.OnClickListener() {
public void onClick(View v) {
//inflate menu
final String [] items = new String[] {"Rate This App", "Quit"};
final Integer[] icons = new Integer[] {R.drawable.star, R.drawable.quit};
ListAdapter adapter = new ArrayAdapterWithIcon(MainActivity.this, items, icons);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item ) {
//Toast.makeText(MainActivity.this, "Item Selected: " + item, Toast.LENGTH_SHORT).show();
switch (item) {
case 0:
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent.setData(Uri.parse("market://details?id=com.test.testing"));
if (MyStartActivity(intent) == false) {
//Market (Google play) app seems not installed, let's try to open a web browser
intent.setData(Uri.parse("https://play.google.com/store/apps/details?com.test.testing"));
if (MyStartActivity(intent) == false) {
//Well if this also fails, we have run out of options, inform the user.
//let the user know nothing was successful
}
}
break;
case 1:
finish();
break;
default:
//do nothing
}
}
});
AlertDialog alert = builder.create();
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alert.getWindow().setGravity(Gravity.BOTTOM);
alert.show();
}
};
I get the following error:
The constructor AlertDialog.Builder(MainActivity, int) is undefined
What do I have to modify to get rid of the error?
Note: My MainActivity class extends Activity and DialogSlideAnim as been initialized in the res/values/styles.xml file
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim) will work only on API level 11 and above.
If you are targeting all the platforms then use following.
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim))
try
new AlertDialog.Builder(v.getContext(), R.style.DialogSlideAnim)
instead of
new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
I think its because the AlertDialog.Builder is inside a inner class(menuHandle.setOnClickListener), try changing to: new AlertDialog.Builder(TheNameOfYourClass.this,R.style.DialogSlideAnim);
Like this way :
public void onClick(View v) {
new AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim);
^^^
....
}
Try to set the Style in your AlertDialog as below:
new AlertDialog.Builder(
new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim)