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();
}
Related
How is possible to return a string value in a activity in Java Android Studio, to another? I am trying these 3 codes below, to get the path that I want, and to return it into a string value.
Some trys:
1)
public static String s = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
2)
public static String retornaString(){
String s=null;
s = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+ UUID.randomUUID().toString()+"audio_record.3gp";
return s;
}
3)
public static retornar(String retorno){
retorno = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
System.out.println(retorno);
return retorno;
}
ERRORS in 3):
Invalide method declaration; return type required
Modifier 'static' not allowed here
Cannot return a value from a method with void result type
How to fix it? Which type of method I have to use?
Thank you.
String yourStringVariable = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
When starting Activity2 from Activity1do the following:
Intent intent = new Intent(Activity1.this,Activity2.class);
intent.putExtra("key",yourStringVariable);
startActivity(intent);
To retrieve the string when you are in Activity2
String myStringFromActivity1 = getIntent().getStringExtra("key");
You can read this article here https://medium.com/#peterekeneeze/passing-data-between-activities-2d0ef122f19d
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");
I intend to share 6 text information, however it always shows the last information only, i.e.
share.putExtra(Intent.EXTRA_TEXT, Contact);
I also tried to use a string array to store all 6 information, i.e:
share.putExtra(Intent.EXTRA_TEXT, stringArray);
However, it still doesn't work. Can anyone help ? Thank you.
My code:
public class SingleJobActivity extends Activity {
// JSON node keys
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
String PostName;
String Location;
String Salary;
String Responsibility;
String Company;
String Contact;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_job_json_parsing);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
PostName = in.getStringExtra(TAG_POSTNAME);
Location = in.getStringExtra(TAG_LOCATION);
Salary = in.getStringExtra(TAG_SALARY);
Responsibility = in.getStringExtra(TAG_RESPONSIBILITY);
Company = in.getStringExtra(TAG_COMPANY);
Contact = in.getStringExtra(TAG_CONTACT);
// Displaying all values on the screen
TextView lblPostName = (TextView) findViewById(R.id.PostName_label);
TextView lblLocation = (TextView) findViewById(R.id.Location_label);
TextView lblSalary = (TextView) findViewById(R.id.Salary_label);
TextView lblResponsibility = (TextView) findViewById(R.id.Responsibility_label);
TextView lblCompany = (TextView) findViewById(R.id.Company_label);
TextView lblContact = (TextView) findViewById(R.id.Contact_label);
lblPostName.setText(PostName);
lblLocation.setText(Location);
lblSalary.setText(Salary);
lblResponsibility.setText(Responsibility);
lblCompany.setText(Company);
lblContact.setText(Contact);
// listeners of our button
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.share:
shareTextUrl();
break;
}
}
};
// our button
findViewById(R.id.share).setOnClickListener(handler);
}
// Method to share either text or URL.
private void shareTextUrl() {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide
// what to do with it.
share.putExtra(Intent.EXTRA_SUBJECT, "Job Information:");
share.putExtra(Intent.EXTRA_TEXT, PostName);
share.putExtra(Intent.EXTRA_TEXT, Location);
share.putExtra(Intent.EXTRA_TEXT, Salary);
share.putExtra(Intent.EXTRA_TEXT, Responsibility);
share.putExtra(Intent.EXTRA_TEXT, Company);
share.putExtra(Intent.EXTRA_TEXT, Contact);
startActivity(Intent.createChooser(share, "Share via"));
}
}
Could anyone help ?
Concatenate the six strings into one larger string, and share that larger string.
You can Concatenate the individual strings to larger string, and can get it
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
String j = (String) b.get("name");
JSONObject name = new JSONObject(j);
Textv.setText(name.getString("postName"));
TextvDesc.setText(name.getString("location"));
}
What's wrong with your actual code
Let's first understand why you only get the last piece of data.
Your problem is by convention in Java (and this also applies to the android.content.Intent.html#putExtra(String, String[]) method you are using) the methods "putXXX" replace the actual value (if it exists) with the new one you are passing.
This is similar to java.util.Map.html#put(K, V) method.
First possible solution
For your current code to work, you would have needed to use a different key for your extra data each time, that is, something like that:
share.putExtra(SingleJobActivity.EXTRA_TEXT_NAME, PostName);
share.putExtra(SingleJobActivity.EXTRA_TEXT_LOCATION, Location);
share.putExtra(SingleJobActivity.EXTRA_TEXT_SALARY, Salary);
share.putExtra(SingleJobActivity.EXTRA_TEXT_RESPONSIBILITY, Responsibility);
share.putExtra(SingleJobActivity.EXTRA_TEXT_COMPANY, Company);
share.putExtra(SingleJobActivity.EXTRA_TEXT_CONTACT, Contact);
This would work fine (assuming you declare as public static final the keys used, and you respect the Android contract for extra data keys, such as using the full package name for the key (e.g. public static final EXTRA_TEXT_NAME = "com.yourpackage.EXTRA_DATA_NAME";).
Second possible solution
Another way of doing it is to pass one extra with a String[] (see method documentation).
String[] extraParams = new String[6];
extraParams[0] = PostName;
extraParams[1] = Location;
extraParams[2] = Salary;
extraParams[3] = Responsibility;
extraParams[4] = Company;
extraParams[5] = Contact;
share.putExtra(SingleJobActivity.EXTRA_TEXT, extraParams);
Then in your new activity you retrieve this array using android.content.Intent.html#getStringArrayExtra(String) method.
Intent intent = getIntent();
String[] extraParams = intent.getStringArrayExtra(SingleJobActivity.EXTRA_TEXT);
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";
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.