Google maps intent parameters - java

I want passing parameters taking from a edittext in the google maps.. the method:
public void nav() {
String address = edit.getText().toString();
address = address.replace(" ","+");
String city = address.substring(address.lastIndexOf(" ") + 1);
Intent i = new Intent(Intent.ACTION_VIEW, uri.parse("geo:0,0?q="+city));
startActivity(i);
}
why String city = address.substring(address.lastIndexOf(" ") + 1);? Because the intent have to start only if in the edittext there is the word bring. So maps starts only if anyone write: bring me New york for example.. The "problem" is that actually the maps application takes the whole string and not only the city. I tried with the substring but not works.. Any way?

The problem is that there are no spaces because you just replaced them all with "+" so if you want the user to write "bring me" (place name) than try this:
try {
String address = edit.getText().toString();
address = address.replace(" ","+");
address = address.substring(9);
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:0,0?q="+address));
startActivity(i);
}
catch (Exception e){
}

Related

How to return a JSONObject with a method using volley? (android studio)

I am making a weather app where I use a weather API and Volley to get the JsonObject with a request, then parse the values and display the values in textViews in another activity(screen).
I am now calling this method below in my MainActivity and using Intent to send the values to my displayInfo activity.
public void getInfoMethod(){
String finalUrl ="";
String cityName = searchBar.getText().toString().trim();
RequestQueue rQ = Volley.newRequestQueue(getApplicationContext());
//create a requestQueue to add our request into
finalUrl = leftApiUrl+cityName+rightApiUrl;
StringRequest sR = new StringRequest(Request.Method.POST, finalUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = "";
try {
JSONObject allJsonRes = new JSONObject(response);
String name = allJsonRes.getString("name");
double visibility = allJsonRes.getDouble("visibility");
int timeZone =allJsonRes.getInt("timezone");
//Creates a new JSONArray with values from the JSON string.
//try/catch are mandatory when creating JSONObject
//now we extract values from this JsonObject
JSONArray weatherJsonArr = allJsonRes.getJSONArray("weather");
//store []weather
//1.to get mainDescription and subDescription
//store the []weather part into weatherJsonArr
//inside this JsonArray,we store the only JsonObject as weatherBlock
//{}0
//then get different values from this subJsonObject
JSONObject weatherBlock = weatherJsonArr.getJSONObject(0);
//this includes id,main,description,icon
String mainDescription = weatherBlock.getString("main");
//get the string under key "main" e.g. "rain"
String subDescription = weatherBlock.getString("description");
//e.g."moderate rain"
JSONObject mainBlock = allJsonRes.getJSONObject("main");
//access {}main
double temp_in_C = mainBlock.getDouble("temp");
//get temperature from {}main
double temp_feel = mainBlock.getDouble("feels_like");
double temp_min = mainBlock.getDouble("temp_min");
double temp_max = mainBlock.getDouble("temp_max");
double pressure = mainBlock.getDouble("pressure");
double humidity = mainBlock.getDouble("humidity");
JSONObject windBlock = allJsonRes.getJSONObject("wind");
//get wind{}
double windSpeed = windBlock.getDouble("speed");
double degree = windBlock.getDouble("deg");
///
JSONObject sysBlock = allJsonRes.getJSONObject("sys");
String country = sysBlock.getString("country");
///
result += "Current weather in "+ name+", "+country+": "
+"\ntime zone: "+ timeZone
+"\nvisibility: "+ visibility
+"\nTemperature: "+Math.round(temp_in_C)+"°C"
+"\n"+mainDescription
+"\n("+subDescription+")"
+"\nWind speed : "+ windSpeed+" meters per minute"
+"\ndegree: "+degree
+"\ntemp feel:"+Math.round(temp_feel)+"°C"
+"\nmin: "+Math.round(temp_min)+"°C/"+"max"+Math.round(temp_max)+"°C"
+"\npressure: "+pressure
+"\nhumidity: "+humidity;
//then send these values to the displayInfo activity
//using Intent and putExtra
Intent i =new Intent(MainActivity.this,displayInfo.class);
i.putExtra("city",name);
i.putExtra("mainD",mainDescription);
i.putExtra("subD",subDescription);
i.putExtra("temp",temp_in_C);
i.putExtra("tempMax",temp_max);
i.putExtra("tempMin",temp_min);
i.putExtra("tempFeel",temp_feel);
i.putExtra("pressure",pressure);
i.putExtra("humidity",humidity);
i.putExtra("visibility",visibility);
i.putExtra("speed",windSpeed);
i.putExtra("deg",degree);
i.putExtra("timezone",timeZone);
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error,check network or spelling",Toast.LENGTH_SHORT).show();
}//note that .show() is necessary for the message to show
});
rQ.add(sR);
//add the request into the queue,Volley will handle it and send it
//and then onResponse() or onErrorResponse() will run
//https://developer.android.com/training/volley/simple
}
It works fine by now, but the problem is, now I want to implement the observer pattern, get the JsonObject in my MainActivity(subject) and make the observers(displayInfo.class for now) to get the latest JsonObject from subject, so I need a method that could return the JSONObject in the MainAvtivity, what should I do to implement this method for observer pattern?
(not using inbuilt Observer interface)
Firstly I suggest putting your getInfoMethod() in a helper class. This will allow for easier re-usability.
Next, I wouldn't gather your result in your first activity. Instead, I would build the URL like you are. Then create an Intent to your second activity and pass the URL as a string with i.putExtra(finalUrl.toString).
In your second activity, have a loading spinner visible, that gets set to 'gone' at the end of processing your result. If an error occurs you can always call finish() to send you back to your first activity.
Optionally you could create a POJO for the results and use Jackson to map the results to an object. It'll be easier to pass the one object around instead of working with every little bit of a JSONObject. JSONObjects are fine, but once you have the data the way you want it, you should map it to a class if you are expecting to work with the object for any length of time.

Validating two strings

I'm trying to validate two strings via TextUtils.isEmpty but i'm failing everytime.
Following is my code:
private void addArtist() {
//getting the values to save
String email = editTextName.getText().toString().trim();
String mobileno = editTextName1.getText().toString().trim();
//checking if the value is provided
if (TextUtils.isEmpty(email)){
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter email.", Toast.LENGTH_LONG).show();
}
else{
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseArtists.push().getKey();
//creating an Artist Object
Artist artist = new Artist(id, email, mobileno);
//Saving the Artist
databaseArtists.child(id).setValue(artist);
Toast.makeText(this, "Successful...", Toast.LENGTH_LONG).show();
}
}
Currently this code is working on string email, i want it to work with string mobileno also.Any help is appreciated.
Why don't you just try to use try catch block and inside it try to convert this string after you read from TextField control object into number if "Mobileno" variable should be int type? If it fails then you can in catch block make some other instructions to prevent from inserting it to field of specific object. Have you tried that?

Multiply contacts' name On update (ContentProviderOperation)

A very strange porblem. I'm tring to update contacts name by this rule:
- if a contact's name start with "bit" + space ("bit ") so -> update the contact's name to name.substring(4, name.length()), and that means that the contact name will update without the "bit ".
when I use name.substring from number that lower them 4 (I think until the space in contact's name) its working perfectly. When I use from the 4 character onwards the contact's name multiply. For exmaple, when i use name = name.substring(4, name.length()) while name equal to "bit Lili" its update to:
Lili Lili.
private void updateContact(String name) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[] {name};
Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI,null,where,params,null);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if ((null == phoneCur)) {//createContact(name, phone);
Toast.makeText(this, "no contact with this name", Toast.LENGTH_SHORT).show();
return;} else {ops.add(ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name.substring(4,name.length()))
.build());
}
phoneCur.close();
try {cr.applyBatch(ContactsContract.AUTHORITY, ops);}
catch (RemoteException e) {e.printStackTrace();}
catch (OperationApplicationException e) {e.printStackTrace();}}
Thanks!
Not a certain answer but it suppose to work the issue you have is with the
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME //This specific part has a problem with the new update function
,name.substring(4,name.length()))
So my fix proposal is to change it to family name and given name change these as you need based on your question you want to remove the given name so it's a fix for that
public static boolean updateContactName(#NonNull Context context, #NonNull String name) {
if (name.length() < 4) return true;
String givenNameKey = ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME;
String familyNameKey = ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME;
String changedName = name.substring(4, name.length());
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[]{name};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(givenNameKey, changedName)
.withValue(familyNameKey, "")
.build());
try {
context.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

How to compare input text with string array in android studio? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am new to app development and I have a problem with coding in android studio. I want to compare an input text with a string in the string array. For some reason it won't work. When i try the java code in eclipse it works.
I already run the debugger and the inputmessage is "Banana". The debugger also shows that message = "Banana" when it is in CheckAnswer(message). But for some reason the function isn't returning "Right". It returns "wrong"
I hope somebody can help me.
Here is my code:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
String message2 = CheckAnswer(message);
intent.putExtra(CORRECT_MESSAGE, message2);
startActivity(intent);
}
public static String CheckAnswer(String string) {
String rightanswer[] = {"Apple", "Banana", "Coconut"};
String answer = null;
for (int i = 0; i <= rightanswer.length-1; i++) {
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
else answer = "Wrong.";
}
return answer;
}
The correct way of comparing two strings is with equals() function not ==
So Change :
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
to:
if (string.equals(rightanswer[i])) {
answer = "Right!!";
break;
}
When you are comparing Strings in Java, it is best to use the String's equals()method which looks like this:
if(someValue.equals(somethingElse){}
I hope this helps!

Convert from Double to String in Android

I am trying to convert a value from Double to String in an Android Activity.I can get this to work with my first example here below (working in the sense of no squigly error from Eclipse). However I am curious as to why the second example is not working.
First example
balance = (TextView) findViewById(R.id.textViewCardBalance);
Intent intent = getIntent();
if (intent.getExtras() != null) {
balance.setText(String.valueOf((long)intent.getDoubleExtra("balance", 0.00)));
}
Second example below not working (Error: "Cannot cast from Double to Long"
balance = (TextView) findViewById(R.id.textViewCardBalance);
Double cardBalance;
Intent intent = getIntent();
if (intent.getExtras() != null) {
cardBalance = intent.getDoubleExtra("balance", 0.00);
balance.setText(String.valueOf((long)cardBalance);
}
Would anyone know how I can get the second example to work as I need to log the value retrieved from the intent before passing it to the TextView.
Thanks
Why can't you do this?
balance.setText(cardBalance + "");
String yourDoubleString = String.valueOf(yourDouble);
in your case:
String yourDoubleString = String.valueOf(intent.getDoubleExtra("balance", 0.00));
using String v = ""+String.valueOf((long)cardBalance) not work?

Categories

Resources