I know this is a stupid question, but problems happen randomly, so annoying! that is I found sometime Bundle putExtras() doesn't work very well(sometimes it works sometimes it doesn't). The bundle i received always only get one value:
for example,here i want to pass four string value to a fragment, here's the code:
Bundle license = new Bundle();
license.putString(LICENSE_1, license_1);
license.putString(LICENSE_2, license_2);
license.putString(LICENSE_3, license_3);
license.putString(LICENSE_ADD, license_add);
DialogFragment mFragment = new WatchOptionsDialog();
mFragment.setArguments(license);
mFragment.show(getActivity().getFragmentManager(),"tag");
at the top of this fragment I defined
public static final String LICENSE_1 = "";
public static final String LICENSE_2 = "";
public static final String LICENSE_3 = "";
public static final String LICENSE_ADD = "";
and the value of four string i wanna pass is "5", "6", "7", "8"
and in another fragment, i receive the bundle as this
Bundle license = getArguments();
String license_1 = license.getString(FragmentMovieInfo.LICENSE_1);
String license_2 = license.getString(FragmentMovieInfo.LICENSE_2);
String license_3 = license.getString(FragmentMovieInfo.LICENSE_3);
String license_add = license.getString(FragmentMovieInfo.LICENSE_ADD);
Log.v("license_1", license_1);
Log.v("license_2", license_2);
Log.v("license_3", license_3);
Log.v("license_add", license_add);
and the problems is all the value i got is four "8". as followed:
license_1 8
license_2 8
license_3 8
license_add 8
It happens many times when i use bundle, I only get the last value. why is that? is there any mistake with the code?
The problem is that you have defined all of your keys (LICENSE_1, LICENSE_2, etc) as an empty string. Thus all of your keys are the exact same.
Methods such as putString() take two arguments- a key and a value. A Bundle is really just a map of key-value pairs. If all of your keys are the same, they all will map to the same values.
Use should use other values, e.g.:
public static final String LICENSE_1 = "LICENSE_1";
public static final String LICENSE_2 = "LICENSE_2";
public static final String LICENSE_3 = "LICENSE_3";
public static final String LICENSE_ADD = "LICENSE_ADD";
Related
I have a function in my Android code where I get a bundle as input:
void f(Bundle data)
This data is actually in the form of a json. Suppose it is in the following format:
{"a":"x", "b":"y", "content":{"a1":"x1", "b1":"y1"}}
In such cases, if I want to get the value of a, or b, then I would need to do String a = data.getString("a"); which would fetch me the string "x". Similarly, String content = data.getString("content") would return me the string {"a1":"x1", "b1":"y1"}}. But I cannot figure out how to get the specific values inside content itself. Is there any way by which I can get content as another bundle just like data so that I can get the values inside it by doing content.getString("a1") or something like that. Is that possible?
JSONObject jOBj = new JSONobject(data.getString("content"));
String a1 = jOBj.getString("x1");
String b1 = jOBj.getString("y1");
try this
To get value from bundle and create JSon object/ Hashmap
private void createFlatJSon(Bundle appRestrictions,JSONObject jsonObject) throws JSONException{
for (String key : appRestrictions.keySet()) {
if (appRestrictions.get(key) instanceof Bundle) {
createFlatJSon((Bundle) appRestrictions.get(key),jsonObject);
}else if (appRestrictions.get(key) instanceof Parcelable[]){
for (int i=0;i< ((Parcelable[]) appRestrictions.get(key)).length; i++){
createFlatJSon((Bundle)((Parcelable[]) appRestrictions.get(key))[i],jsonObject);
}
//Log.e("KEY skipped",appRestrictions.get(key).toString());
}else{
Log.e("KEY: ",key+" Value:"+appRestrictions.get(key).toString());
jsonObject.put(key,appRestrictions.get(key).toString());
}
}
}
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();
}
In my Const.java I have
public static final String[] MONTHS = new String[]{<list of string values>}
public static final String[] YEARS = new String[]{<list of string values>}
public static int MONTH_NUM = <some int>;
public static int YEAR_NUM = <some int>;
in my other file i have
ArrayList<String> skList = new ArrayList<String>();
String month = Const.MONTHS[Const.MONTH_NUM];
String year = Const.YEARS[Const.YEAR_NUM];
skList.add(month);
skList.add(year);
then I got this error: The method add(String) in the type ArrayList is not applicable for the arguments (String[])
on lines:
skList.add(month);
skList.add(year);
Hope you can help. I already used all possible keywords I can come up w/ in Google.
Thanks.
Note: After I restarted eclipse and rebuild, several times, it ran.
thanks guys for all your comments.
I want to split this string
String info = "0.542008835 meters height from ground";
from this i want to get only two decimals like this 0.54.
by using this i am getting that
String[] _new = rhs.split("(?<=\\G....)");
But i am facing problem here, if string does't contain any decimals like this string
String info = "1 meters height from ground";
for this string i am getting those characters upto first 4 in the split string like 1 me.
i want only numbers to split if it has decimals, How to solve this problem.
if(info.contains("."))
{
String[] _new = rhs.split("(?<=\\G....)");
}
I think you can check by white space after first value. see this
If you get the space then get first character only.
For checking if a string contains whitespace use a Matcher and call it's find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
You could use a regex to do this as an alternative to Deepzz's method, this will handle the case where there is a '.' in the later part of the String, I've included an example below. It's not clear from your question is you actually want to remaining part of the String, but you could add a second group to the reg ex to capture this.
public static void main(String[] args) {
final String test1 = "1.23 foo";
final String test2 = "1 foo";
final String test3 = "1.234 foo";
final String test4 = "1.234 fo.o";
final String test5 = "1 fo.o";
getStartingDecimal(test1);
getStartingDecimal(test2);
getStartingDecimal(test3);
getStartingDecimal(test4);
getStartingDecimal(test5);
}
private static void getStartingDecimal(final String s) {
System.out.print(s + " : ");
Pattern pattern = Pattern.compile("^(\\d+\\.\\d\\d)");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("Doesn't start with decimal");
}
}
Assuming the number is always the first part of the string:
String numStr = rhs.split(" ")[0];
Double num = Double.parseDouble(numStr);
After that you can use the String Formatter to get the desired representation of the number.
This will work when you know the String near the numbers, with int and double numbers as well.
String a ="0.542008835 meters height from ground";
String b = a.replace(" meters height from ground", "");
int c = (int) ((Double.parseDouble(b))*100);
double d = ((double)c/100);
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.