Get string from one class to another class in Android? - android

I need to get the string variable from one class of my project to another class,
in First class, I made a string type variable and that is Global, like this:
the name of class is firstclass
public String firstClassVar;
and I am assigning the value to it in this method
public String requestForServerData(String strURL) throws IOException, UnknownHostException, IllegalArgumentException, Exception {
//additional code
firstClassVar = myObject.getString("values");
//additional code
}
Now in second class, I am doing something like this:
public firstclass getVar;
public void method{
String secondClassVar;
secondClassVar=getVar.firstClassVar;
}
By doing this it crashes. I have done another thing in firstclass that is
public String getStringPublically() {
return firstClassVar;
}
and for accessing it another class I am doing like this
secondClassVar =getVar.getStringPublically();
and by doing this it also crashes the app.
Now I am bit new to Android, and don't know the basic way to access the string from another class.

Use public static String firstClassVar; in First Class and in Second Class use secondClassVar=FirstClass.firstClassVar;

Try this..
pass values:
Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);
getvalues:
Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);
IF it is Fragment
Send:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Retrieve:
Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue)

You can use SharedPreferences to set/get values in any class you want.
Here is a good topic about it

Try Using putExtra and getExtra with Intent

The app crashed because vetVar was not initialized. Try with
public firstclass getVar = new firstclass();
in the second class

Related

Android : Can't put a string through an intent from a fragment to an activity

I'm new in android development and I have an issue with simple string in an intent.
I create an Intent in a fragment to launch a new activity. I have no error but I can't put a string through the intent.
Here is my code :
public class AboutFragment extends Fragment {
private static Context mContext;
I have this in the onCreateView method :
mContext = this.getContext();
This method in the same class
public static void openModalPolicy() {
Intent intent = new Intent(mContext, ModalActivity.class);
intent.putExtra("section", "policy");
mContext.startActivity(intent);
}
And in my new activity :
String section = this.getIntent().getStringExtra("section");
So the problem is that section is never equal to "policy"
If someone can help me :) Have a good day !
Just to be sure, you are using section.equals("policy") for your equality check.
Not section == "policy". Right?
Check out this post for more information: How do I compare strings in Java?

Static initializer per Activity (just like Fragment)

We are encouraged to use static initializer (a.k.a. the newInstance() pattern) per Fragment when we are passing arguments. In case of Activity, there is no mentioning of such. And every time we are going to start an activity, we have to first create an Intent first, like below:
public class FirstActivity extends Activity {
...
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
...
}
And if there are some parameters we would like to pass, this gets even more complicated, since we need to give each parameter a name, like below:
public class FirstActivity extends Activity {
...
int age = 10;
int count = 20;
String message = "hello";
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Age", age);
intent.putExtra("Count", count);
intent.putExtra("Message", message);
startActivity(intent);
...
}
and in the SecondActivity we should retrieve these parameters with the same name:
public class SecondActivity extends Activity {
...
int mAge;
int mCount;
String mMessage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAge = getIntent().getIntExtra("Age", 0);
mCount = getIntent().getIntExtra("Count", 0);
mMessage = getIntent().getStringExtra("Message");
}
...
}
Furthermore, these names we have used, "Age", "Count" and "Message" is hard-coded and error-prone. Most of the time we use a helper class, called something like IntentExtraKeys and use names from that class, like below:
public class IntentExtraKeys{
public static final String AGE_KEY = "age_key";
public static final String COUNT_KEY = "count_key";
public static final String MESSAGE_KEY = "message_key";
}
and in the activities:
public class FirstActivity extends Activity{
...
intent.putExtra(IntentExtraKeys.AGE_KEY, age);
...
}
and
public class SecondActivity extends Activity{
...
mAge = getIntent().getIntExtra(IntentExtraKeys.AGE_KEY, 0);
...
}
Instead of this, we could have something like below:
public class FirstActivity extends Activity{
....
SecondActivity.startActivity(this, age, count, message);
...
}
and
public class SecondActivity extends Activity{
...
private static final String AGE_KEY = "age_key";
private static final String COUNT_KEY = "count_key";
private static final String MESSAGE_KEY = "message_key";
public static void startActivity(Context context, int age, int count, String message){
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(AGE_KEY, age);
intent.putExtra(COUNT_KEY, count);
intent.putExtra(MESSAGE_KEY, message);
context.startActivity(intent);
}
...
}
This way, we save ourselves from writing code for creating an Intent every time we want to start the activity and if we are going to pass some parameters, we don't need to give them name. Only the activity we are starting knows their name, and it looks a lot cleaner, just like in fragments.
Is this bad design? Why is this uncommon?
The static initializer pattern is used in fragments because even though you instantiate the fragment yourself for the first time the default constructor must exist so the platform can instantiate it again on it's own when the activity is rebuilt because of a configuration change.
Activities on the other hand are always instantiated by the system and they must not need any special factory method nor constructor in order to retain their ability to be exported as intents for use by other apps and the system itself; that's why static initializers don't make a whole lot of sense on Activities. They are quite valid though and you can use them if you want but they might complicate having custom initialization code for activities that perform the same function in various slightly-different ways and they create a false sense of coupling.
For fragment
There are some reasons to use static function to create Fragment
Having single point to create Fragment instances. This makes sure the multi Fragment initializing having the same input arguments handling, etc.
It helps developers avoid to create Non-static Nested fragment. Fragment & Activity must be de-coupling.
The utility function can be invoked multi times. For example: The fragment is being used in TabLayout, ViewPager.
For Activity
You can create utility like you did. No problem. It is hard to say it is bad code or uncommon code.
If you will use the function More than one Or the Activity has input arguments. You can create the Utility function like you did.

copy string from activity to another Android

at begining i want to say sorry for my bad english i hope u understand me.
I want to copy one string to another activity so i create :
package com.example.kliker;
import android.app.Application;
public class GlobalClass extends Application{
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getEmail() {
return email;
}
public void setEmail(String aEmail) {
email = aEmail;
}
}
and in activity to set i use:
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setEmail("1");
globalVariable.setName("1");
and when i want get:
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
a = globalVariable.getEmail();
b = globalVariable.getName();
mTextView.setText(a);
But it doesn't work ? I should refresh activity or something like that ?
http://speedy.sh/dvt94/Desktop.rar
Manifest,activity from i get and set, activity set, activity get
I would like to make one activity outstay data about category and food also i want to make another activity when we are in it and when we click on food it send informations about itself category and chosen food, main activity download that information and by means of them it build graphic sentence
Use Bundle API - http://developer.android.com/reference/android/os/Bundle.html.
In your A Activity -
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("value", "String Value");
intent.putExtras(bundle);
startActivity(intent);
And, in B Activity -
Intent i = getIntent();
Bundle extras = i.getExtras();
String value = extras.getString("value");
You would be interested in this http://hmkcode.com/android-passing-data-to-another-activities/
You are instantiating your GlobalClass class twice so you are getting different variables. Try something like this in the same activity and see if it works.
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setEmail("1");
globalVariable.setName("1");
a = globalVariable.getEmail();
b = globalVariable.getName();
mTextView.setText(a);
I can think of at least three decent choices:
1) Use a singleton (pros - simple; cons - won't persist across application lifetime).
2) Use SharedPreferences (easy enough to research); if you're really using it for something like username for the application (which is what it appears from the example) then SharedPreferences are appropriate.
3) Use an Intent to trigger the next activity from your current one, and pass the string as an extra (intent.putExtra(...), intent.getStringExtra(...)).

Send String from an Activity to a Fragment of another Activity

I have two Activities (A and B) and a Fragment F
The Fragment F is contained in the Activity B
I'd like to send Strings from Activity A to Fragment F
How can do that?
Thanks!
It is Almost same as you would exchange data between activities. you should just use getActivity() in the beginning in order to access in fragments.
check below code:
In Activity A:
Intent intent = new Intent(this,ActivityB.class);
intent.putExtra("data",data); //data is a string variable holding some value.
startActivity(intent);
In fragment F of Activity B
String data = getActivity().getIntent().getStringExtra("data");
First, you'll actually send that string to your activity B. For example:
Intent intent = new Intent(this, YourActivityClass.class);
intent.putExtra("myString", "this is your string");
startActivity(intent);
then later read that string from your activity B and inject into your fragment before executing the fragment-transaction. For example:
Bundle args = new Bundle();
args.putString("myString", getIntent().getExtras().getString("myString"))
yourFragment.setArguments(args);
Later, use getArguments() in your fragment to retrieve that bundle.
Or alternatively, use the following in your fragment to directly access the activity intent and fetch your required value:
String str = getActivity().getIntent().getStringExtra("myString");
For more info, read this.
In Fragment.java file add the following code,
public static String name= null;
public void setName(String string){
name = string;
}
In MainActivity.java from which you want to send String add the following code,
String stringYouWantToSend;
Fragment fragment = new Fragment();
fragment.setName(stringYouWantToSend);

How to send a Parcelable object to a DialogFragment?

I'm able to send my data from Activity1 to Activity2 with the typical..
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("state", getIntent().getParcelableExtra("state"));
intent.putExtra("schools", temp);
startActivity(intent);
and that works fine once I'm at the Activity2, the issue is how to make it work from Activity1 to a DialogFragment? How do you send the parcelable objects and retrieve them once I'm coding the DialogFragment? Any example available out there you can point me at?
I think this can help.
Basically by using setArguments() and later getArguments() in the Dialog's onCreate().
Use Bundle to pass Parcelable object to your DialogFragment.
http://developer.android.com/reference/android/os/Bundle.html
(EDIT:)
Let's say you need a TimePicker DialogFragment somewhere in your Activity1:
// This is a static inner class which resides inside your Activity1
// so you will face this limitation :
// You can only access static method from inside this. You also can
// not remove static keyword or you will face memory leak.
public static class StartTimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
static StartTimePickerFragment newInstance (int arg, YourParcelableObj obj) {
StartTimePickerFragment DialogFrag = new
StartTimePickerFragment();
Bundle args = new Bundle();
args.putInt("Whatever", arg);
// for Parcelable :
args.putParcelable ("Whatever2", obj);
DialogFrag.setArguments(args);
return DialogFrag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("whatever");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// now here you can not directly access class methods and
// and data members. so get the Activity object and then
// you are good to 'set/get' them here in your
// DialogFragment
Activity1 activity = (Activity1) getActivity();
activity.your_non_static_method(hourOfDay, minute);
activity.your_non_static_activitidy_member_Data = "whatever";
}
}

Categories

Resources