How to make a reusable java function for android webview - java

Please am very new to java, am trying to put my website in webview, i have few lines of code that send user to email form and is working very fine. But now i have to use the same code in more than 3 place when url match something and i know that there will be a way to put this code one place as a function then call it and time i want to use it. please can someone help me.
function RequestMailForm(newbody, newsubject, newemailto, newmailbbc){
/* That email code*/
}
mva.setWebViewClient(new WebViewClient() {
if (url.startsWith("mailto:")) {
url = url.substring(7);
String body = "Body of message.";
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("application/octet-stream");
mail.putExtra(Intent.EXTRA_EMAIL, new String[] { url });
mail.putExtra(Intent.EXTRA_SUBJECT, "Subject");
mail.putExtra(Intent.EXTRA_TEXT, body);
startActivity(mail);
return true;
}
if (url.startsWith("http://example.com/help") || url.startsWith("https://example.com/contact")){
RequestMailForm(newbody, newsubject, newemailto, newmailbbc);
}
});

Create a class and put sendEmail method with message and email paramater.
See the code below.
class SendEmail {
Context context;
public SendEmail(Context context){
this.context = contex;
}
//send an email
public void send(String email) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", email, null));
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Body of message");
context.startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
}
Then create an object of the SendEmail class and call that function every time you want to send an email like this:
if (url.startsWith("mailto:")) {
url = url.substring(7);
sendEmail.send(url);
return true;
}

Related

Get value from deeplink parameter rather than dynamic link in android java

I made an application in which users can send links to their friends. With the link, I added some parameters, So when the user clicks on the link the page with the given parameter will open.
The deep link user sends to his friends is:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "https://shareemotion.page.link/mood?mood=Sad&bottomneg=2";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
context.startActivity(Intent.createChooser(sharingIntent, "Share via"));
While the dynamic link in firebase is:
https://www.myapp.com/?mood=Happy&bottomneg=2
And the code for getting data from link is :
FirebaseDynamicLinks.getInstance()
.getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
// Get deep link from result (may be null if no link is found)
Uri deepLink = null;
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.getLink();
}
if(deepLink!=null)
{
String mood = deepLink.getQueryParameter("mood");
String bottomId = deepLink.getQueryParameter("bottomneg");
NewActivity(mood, bottomId);
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e( "getDynamicLink", " "+e);
}
});
So Now when I share the link with mood=Sad the app run but at the fetching point it fetches "Happy"(which is present in the dynamic link) but I want to fetch mood=Sad from the link that sends to another user.
Note
mood=Sad will replace by variable, for now, it uses for testing purposes.

Unable to find working solution with Intent.ACTION_SEND_MULTIPLE for multiple images to be attached to an email

So here's the situation - I'm developing an Unreal plugin with native android features.
Intention for single image works perfectly, but now, when I'm trying to add multiple image attachments using ACTION_SEND_MULTIPLE it's not starting activity.
No errors, execution stops on .startActivity(), wrapping with try-catch doesn't return any exceptions, Unreal passes images array without any issue.
I feel like it's not building intent properly, but after 2 days of searching and countless hours of trials and errors I feel like it's time to give up and seek for advise here :)
Here's the java part of the code I'm suspecting isn't working:
public static void sendEMail(Activity activity, String subject, String[] extraImagePaths,
String[] recipients, String[] cc, String[] bcc,
boolean withChooser, String chooserTitle) {
Intent intent = createEMailIntent(subject, recipients, cc, bcc);
ArrayList<Uri> paths = new ArrayList<Uri>();
if (extraImagePaths.length > 0) {
for (String extraImagePath : extraImagePaths) {
File fileIn = new File(extraImagePath);
Uri arrayPath = Uri.fromFile(fileIn);
paths.add(arrayPath);
}
}
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, paths);
try {
launchShareIntent(activity, withChooser, chooserTitle, intent);
} catch (Exception e) {
Log.d("AndroidLOG:", e.getMessage());
}
}
private static Intent createEMailIntent(String subject, String[] recipients, String[] cc, String[] bcc) {
return new Intent(Intent.ACTION_SEND_MULTIPLE)
.setData(Uri.parse("mailto:"))
.setType("image/*")
.putExtra(Intent.EXTRA_SUBJECT, subject)
.putExtra(Intent.EXTRA_EMAIL, recipients)
.putExtra(Intent.EXTRA_CC, cc)
.putExtra(Intent.EXTRA_BCC, bcc);
}
private static void launchShareIntent(Activity activity, boolean withChooser, String chooserTitle, Intent intent) {
if (withChooser) {
Intent chooserIntent = Intent.createChooser(intent, chooserTitle);
activity.startActivity(chooserIntent);
} else {
activity.startActivity(intent);
}
}
tried removing all of the extras, except images, but that didn't solve the problem.
Help would be much appreciated!
After more digging through SO found similar post, changed .fromFile() to FileProvider and it worked like a charm.
Snippet:
for (String extraImagePath : extraImagePaths) {
Uri arrayPath = FileProvider.getUriForFile(activity, getAuthority(activity), new File(extraImagePath));
paths.add(arrayPath);
}
P.S. Credit goes to CommonsWare!

android share clickable string url with indication google maps

I have a listview of elements. Each element is a different place and when I click into one of this I open a google map intent with the way to go.
Sometimes I need to share the address (for example "Colosseo, Piazza del Colosseo 1, 00184 Roma RM".
How do I share this string with a clickable url? I want to share it and permit other people to click inside it and open google map
This is how I create the intent:
public void OpenMaps(Context context) {
Toast.makeText(context, "Ti porto a: "Colosseo, Piazza del Colosseo 1, 00184 Roma RM", Toast.LENGTH_SHORT).show();
Uri address = Uri.parse("google.navigation:q=Colosseo,+Piazza+del+Colosseo+1,+00184+Roma+RM");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, address);
context.startActivity(mapIntent);
}
Maybe you'll like this:
private String UrlMap(String s) {
try {
String url = "https://www.google.com/maps/search/?api=1&query=" + URLEncoder.encode(s, "UTF-8");
return url;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
I don't know how to set a custom caption, to avoid seeing the entire url

Understand SharedPreferences Android

In android I want to make a basic login and registration application. I am following this tutorial. The application works properly and runs. I am just trying to understand the code now and after many google searches I can not understand some of the code and was wondering if somebody could help me understand it.
Below I have posted the method I do not understand and in comments highlighted what I do not understand - any clarification is much appreciated, I have also commented the code to what I believe the code does, if any of it is incorrect please tell me, you can also view all of the code on the tutorial website.
I am mainly confused about how the sharedpreferences works I have followed his tutorial on sharedpreferences too I understand that but do not understand this. Thank you and sorry if the problem is very basic
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
// Dialog stating trying to login
pDialog.setMessage("Logging in ...");
showDialog();
// Send the request over to the database to check details
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
// Do this once you get a response
#Override
public void onResponse(String response) {
Log.d(loginName, "Login Response: " + response.toString());
hideDialog();
// Break the response up into individual things and store in variables
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// I DO NOT UNDERSTAND THIS!!! how does this bit work?
// it sets the shared preferences login to true correct?
// but how does it set it true to only this particular user?
// Because it doesnt store the email and password along with it
// and sets its tag "isLoggedIn" and then saves it to the shared
// preferences
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
//I DO NOT UNDERSTAND THIS!!! Why do you need to do this & does this
//affect the MySQL DB at all?
db.addUser(name, email, uid, created_at);
// I DO NOT UNDERSTAND THIS!!! Why do you need to write LoginActivity.this
// do you not just write MainActivity?
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(loginName, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
/***************************************************************/
//I DO NOT UNDERSTAND THIS WHOLE METHOD WHY DO YOU DO THIS?!!!
/***************************************************************/
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// FINALLY I ALSO DO NOT UNDERSTAND WHY YOU DO THIS! AND WHAT DOES IT DO
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This adds a user to an SQL database:
db.addUser(name, email, uid, created_at);
There should be a class somewhere that defines the actual function, which then creates the query that actually interacts with the database.
The intent changes the activity (what is rendered on the screen and what logic is handled):
LoginActivity.this: the context in the current class - this can be simplified to just this, but it's a bit of syntactic sugar in Java that attempts to clarify which this is being referred to.
MainActivity.class: the target activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
The difference between two activities can be explained with the content of a game. The menu is "LoginActivity.this" and "MainActivity.class" is the actual game content
As for shared preferences, the usage is pretty straight-forward:
To obtain shared preferences, use the following method In your
activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
(Source, posted by naikus)
The internal mechanics aren't something you need to worry about - the thing you really need to know is that it's able to save your data in a way you can use that doesn't involve directly accessing files (which has become a maze since Android 10).
EDIT:
Based on what I saw at the tutorial, the entire thing is to check if the login information entered exists in the database. The getParams() method defines what goes into the form data

Passing parameters from Javascript to Android (Java)

I'm trying to send an email through the Android's email client. However, when I attempt to send the E-mail to the client, it says the email is null. I find that strange since I'm passing the correct parameters in JavaScript, but the app wont read it?
I have been researching this issue for awhile now and have searched Stack Overflow for awhile.
Anyways, my goal with this is to understand why my parameters are not being passed through.
JavaScript:
function sendEmailToAndroid (emailAddresses, CC, subject) {
alert(emailAddresses); //This displays the correct address
if (IsAndroidDevice()) {
window.ccs.sendEmail(emailAddresses, CC, subject);
}
}
Java:
#JavascriptInterface
public void sendEmail(String[] emailAddress, String[] CC, String subject){
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, emailAddress);
email.putExtra(Intent.EXTRA_CC, CC);
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.setType("message/rfc822");
if(emailAddress == null || emailAddress.length == 0){
Toast ctoast = Toast.makeText(getApplicationContext(), "There is no email for this customer", Toast.LENGTH_LONG);
ctoast.setGravity(Gravity.CENTER, 0, 0);
ctoast.show();
Log.d(LOG, "Email: "+emailAddress);
}
else{
try{
startActivity(Intent.createChooser(email, "Send mail..."));
} catch(ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Failed to initalize email client!", Toast.LENGTH_LONG).show();
}
}
}
Now when I debug the JavaScript, all parameters are being passed correctly. However, when it is read in the android app, all the values come back as null, or undefined. Which is not correct.

Categories

Resources