I have an issue in getting parameters from a URL mentioned below,
String url = http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999
My code to extract the parameters is as follows:
Uri uri = Uri.parseurl(url);
Set<String> paramNames = uri.getQueryParameterNames();
However, as you can see a "#" in the URL instead of "?" so that's why I am not able to get the parameters Set.
First thing that came to my mind is to replace "#" with "?" using String.replace method then I thought their might be better solution for this. So if you guys have better solution please help me.
Easiest method:
String string = url.replace("#","?");
String access_token = Uri.parse(string).getQueryParameter("access_token");
Log.d("TAG", "AccessToken: " + access_token);
Now you can get any parameter from the url just by passing their name.
Good Luck
'#' is called refrence parameter, Here you can do one of two things either replace the '#' with '?' and process your uri i.e
String url = "http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999";
url = url.Replace("#","?"); //now your URI object to proceed further
or other alternative
String url = "http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999";
URL myurl = new URL(url);
String refrence = myurl.getRef(); //returns whatever after '#'
String[][] params = GetParameters(refrence);
and the defination for function GetParameters() is following
private String[][] GetParameters(String r)
{
try
{
String[] p = r.split("&"); //separate parameters mixed with values
String[][] data = new String[p.length][2];
for(int i = 0 ; i<p.length; i++) //iterate whole array
{
data[i][0] = p[i].split("=")[0]; //parameter name
data[i][1] = p[i].split("=")[1]; //parameter value
data[i][1] = data[i][1].replace("%"," "); //replace % with space character
}
return data; //return result
}
catch(Exception e)
{
return null;
}
}
i have not executed and tested the code i am lazy one too so i hope you will accomodate lolz :D
You can use the Uri class in Android to do this; https://developer.android.com/reference/android/net/Uri.html
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394");
//Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("chapter"); //will return "V-Maths-Addition "
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths- Addition%20&%20Subtraction&post=394");
String server = uri.getAuthority();
String path = uri.getPath();
String protocol = uri.getScheme();
Set<String> args = uri.getQueryParameterNames();
Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("key");
Related
When I'm printing String, in logcat I'm getting like this:
{"urldetails":"aHR0cDydmljZXMvfmh0dHA6Ly80Ny45MS4xMTUuMjEyL1NDTVMvd2ViL2FwcF9zYm94LnBocA==","customer":"NH4fjIyOTF+RHIuQWZhcmdoZXNl"}
In this 3 things I want store in separately, one is urldetails, one iscustomer before + and 3rd one is after + String.
How can I do that?
When I tried, I'm getting indexoutofbounf exception
You can extract the values with JSONObject.
JSONObject json = new JSONObject(your-string);
String urldetails = json.getString("urldetails");
String[] customers = json.getString("customer").split("\\+");
String customer1 = customers[0]; //customer before +
String customer2 = customers[1]; //customer after +
try use kotlin
yourModel = Gson().fromJson(this, T::class.java)
yourModel.customer.substringAfter("+")
yourModel.customer.substringBefore("+")
I have a minor problem that I'm stuck. The problem is that I had passed a id with the code below.
Intent i = new Intent(First.this,Second.class);
i.putExtra("classification_id","3");
However, when I try to get the parameter of 3 with the code below I get the result of -1 when I check it in the debug mode.
if(intent.getExtras().getString("classification_id")!=null){
classId = intent.getExtras().getString("classification_id");
}else{
classId = "1";
}
Actually I want to use this parameter to set it into a url to get the json data to get the json data . But Is this a right way? Or is it a bad practice to set the String int into a url? Ex. "www.test.test/myid?="+classId
Where is the intent coming from ? There are getIntent() or Intent coming from methods like onNewIntent()
Also I think this is shorter
if(getIntent().hasExtra("classification_id")) {
String classId = getIntent().getStringExtra("classification_id");
}
As for inserting String into url, you will be overwhelmed if there are many parameters (btw, I think this is a wrong format: www.example.test/myid?=classId maybe this is what you want www.example.com/test?myid=classId ). So we can do
private static final String URL="https://www.example.com";
private static final String PATH = "test";
private static final String PARAM_MYID = "myid";
public static String buildMyUrl(String id){
Uri.Builder b = Uri.parse(URL).buildUpon();
b.path(PATH);
b.appendQueryParameter(PARAM_MYID, id);
b.build();
return b.toString();
}
Consider the url: www.xyz.com/buy/thankyou/handlers/display.html?ie=UTF8&asins=B00F0G8K&orderId=404-35644-70307&purchaseId=404-2849-9658 as 1st url. The 2nd url is : sndbx.abc.com/mob#?path=confirmOrder&oid= &pid= &asins= . Here the values of the orderid(multiple), purchaseId and asins from the first url should be filled here in the 2nd url ie, 2nd url should be
sndbx.abc.com/mob#?path=confirmOrder&asins=B00F8K&oid=40444-7037&pid=4089-958.
replaceAll("[&][a-zA-Z0-9._%+-]{1,}[=]","") will replace all the keys from 2nd url which dont have values..
URL_1.split("?")[1] will give u all the key- values pair and hence..
URL_2= URL_2.replaceAll("[&][a-zA-Z0-9._%+-]{1,}[=]","").concat(URL_1.split("?")[1] );
will do the needful.
hope this helps
cheers :)
you may use simple splitter of URL, might be creates as some static helper or whatever. for example:
String url1 =..., url2=...;
String[] url1splitted = url1.split("&");
for(String pair:url1splitted){
if(pair.contains("=") && pair.length()>=3 && getCount(pair, '=')=1){
String param = pair.split("=")[0];
String value = pair.split("=")[1];
// add to HashMap, format another url or whatever...
}
}
//getCount method
private int getCount(String pair, Char lookingFor){
int counter = 0;
for(int i=0; i<pair.length(); i++)
if( pair.charAt(i) == lookingFor )
counter++;
return counter;
}
I want to split a string and get a word finally. My data in database is as follows.
Mohandas Karamchand Gandhi (1869-1948), also known as Mahatma Gandhi, was born in Porbandar in the present day state of Gujarat in India on October 2, 1869.
He was raised in a very conservative family that had affiliations with the ruling family of Kathiawad. He was educated in law at University College, London.
src="/Leaders/gandhi.png"
From the above paragraph I want get the image name "gandhi". I am getting the index of "src=". But now how can I get the image name i.e "gandhi" finally.
My Code:
int index1;
public static String htmldata = "src=";
if(paragraph.contains("src="))
{
index1 = paragraph.indexOf(htmldata);
System.out.println("index1 val"+index1);
}
else
System.out.println("not found");
You can use the StringTokenizer class (from java.util package ):
StringTokenizer tokens = new StringTokenizer(CurrentString, ":");
String first = tokens.nextToken();// this will contain one word
String second = tokens.nextToken();// this will contain rhe other words
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
Try this code. Check if it working for you..
public String getString(String input)
{
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
if(mt.find())
{
return mt.group(1);
}
return null;
}
Update:
Change for multiple item -
public ArrayList<String> getString(String input)
{
ArrayList<String> ret = new ArrayList<String>();
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
while(mt.find())
{
ret.add(mt.group(1));
}
return ret;
}
Now you'll get an arraylist with all the name. If there is no name then you'll get an empty arraylist (size 0). Always make a check for size.
I want to display multiple values in the text message body, however the following code below display no body message even when the textArray has values. Is there any way of adding values to a body of an email through a loop?
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Example");
int sizeOfArray = list.size();
String textArray [] = new String[sizeOfArray];
for(int i = 0;sizeOfArray > i;i++)
{
HashMap<String, String> arrayString = list.get(i);
String user = arrayString.get("user");
String book = arrayString.get("book");
textArray[i] = user + " - " + book;
}
sharingIntent.putExtra(Intent.EXTRA_TEXT, textArray);
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
});
It's difficult to get proper documentation on what Intent Receivers are expecting as extra values, but I'm pretty sure you need to pass a String and not a String[] to putExtra, since the Receiver will anyway end up converting the value to a String, so better to control that.
Thats being said, your implementation of the loop is weird. Do you really have a list of HashMap<String, String>as input ?
I would do :
StringBuffer sb = new StringBuffer();
for(HashMap<String, String> item: list){
String user = item.get("user");
String book = item.get("book");
sb.append(user + " - " + book+", ");
}
String value = sb.substring(0, Math.max(0,sb.length()-2));
Intent.EXTRA_TEXT expects CharSequence according to the documentation:
http://developer.android.com/reference/android/content/Intent.html#EXTRA_TEXT
I would guess as you are passing in an array, the receiving activity doesn't know what to do with it and just skips over it.
Trying joining your array values and passing them in as a String.
String arg = org.apache.commons.lang.StringUtils.join (textArray, '\n');
sharingIntent.putExtra(Intent.EXTRA_TEXT, arg);