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(...)).
Related
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?
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.
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
i am new to Android development. I have two activities A and B. In activity A I use a xml parser to gain objects with each about 10 strings included. I want to pass these objects to activity B and there should be a listview showing all the objects. Clicking on a object in the listview should show the 10 strings.
I am not sure if I have to use a SQLite database or if I only can use SharedPreferences?
Or can I even store it on the internal memory?
The objects should be saved even if i kill the app.
Hope someone can give me some hints, thanks!
this may helps you
you can pass your string data both way as you like [1] Using Intent [2] Using Share Prefrence
like [1] Intent
in your First ActivityA
Intent myintent= new Intent(FirstActivity.this,SecondActivity.class);
myintent.putExtra("Name1", "your String");
myintent.putExtra("Name2", "your String");
myintent.putExtra("Name3", "your String");
myintent.putExtra("Name4", "your String");
startActivity(myintent);
in Second ActivityB
Intent myintent = getIntent();
if(null!=myintent.getExtras()){
String Name1 = myintent.getExtras().getString("Name1");
String Name2 = myintent.getExtras().getString("Name2");
String Name3 = myintent.getExtras().getString("Name3");
String Name4 = myintent.getExtras().getString("Name4");
Toast.makeText(getApplicationContext(),""+Name,12).show();
}
else
{
Toast.makeText(getApplicationContext(),"No Recor Here..",12).show();
}
like SharedPreferences[2]
in your First ActivityA
Intent myintent= new Intent(FirstActivity.this,SecondActivity.class);
SharedPreferences spref = this.getSharedPreferences("mynotifyid", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor spreedit = spref.edit();
spreedit.putString("Name1", str1.toString());
spreedit.putString("Name2", str2.toString());
spreedit.putString("Name3", str3.toString());
spreedit.putString("Name4", str4.toString());
spreedit.commit();
startActivity(myintent);
in your Second ActivityB
SharedPreferences spref = context.getSharedPreferences("mynotifyid", Context.MODE_WORLD_WRITEABLE);
String str1 = spref.getString("Name1","");
String str2 = spref.getString("Name2","");
String str3 = spref.getString("Name3","");
String str4 = spref.getString("Name4","");
for your object saving purpose use SharedPreferences
Let these objects implement the interface Serializable so you can pass the objects to another Activity using an Intent
Maybe this small(!) example can help you:
public class MyModel implements Serializable {
...
}
public A extends Activity {
public void onCreate(Bundle savedInstanceBundle) {
...
//fetchData
...
MyModel data = new MyModel(fetchedData);
Intent intent = new Intent(this, B.class);
intent.putExtra("KEY", data);
startActivity(intent);
}
}
public B extends Activity {
public void onCreate(Bundle savedInstanceBundle) {
Bundle extras = getIntent().getExtas();
MyModel data = (MyModel) extras.getSerializable("KEY");
...
//handle data
...
}
}
For those 10 strings I wouldn't use database.
SharedPreferences easy to use, lot of examples and will deal with your needs.
If a none string need later, than you can use internal memory ( binary mode ), but now no reason, imho.
So, I'm basically fooling around with some kind of login form, and trying to say a customized hello with the user name on the upcoming activity. The code compiles with no problem but the app crashes as soon as I click on the login button, the login worked successfully before I tried to implement the customized hello, so the problem has to be somewhere in the following code.
Here is where I call the activity:
Intent k = new Intent(this, MainActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
//login is the EditText variable name for the login text field
startActivity(k);
Here is where I retrieve the extra data and try to use it as described:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ProfileActivity extends Activity {
TextView helloString;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Bundle extras = getIntent().getExtras();
//Getting the hello text string
helloString = (TextView)findViewById(R.id.textHello);
String loginName = extras.getString("loginName");
helloString.setText("¡Hello, " + loginName + "!");
}
}
It somehow avoids the crash if I put in comment these two lines:
String loginName = extras.getString("loginName");
helloString.setText("¡Hello, " + loginName + "!");
Still, I can't be sure if the problem is really there or not, I thought it could have something to do with the type of data sent from the first activity not matching with the type being retrieved on the second, but still got no clue after trying some stuff around that.
Thanks in advance.
Editing:
I actually found out that I may have something to do with the fact that I am calling to mainActivity.class while the text is being shown in an activity called profileActivity.class, the problem is, profileActivity is being shown as a tab inside the mainActivity so I don't really know how should I approach that.
Editing 2:
So I solved it finally myself, for anyone interested I just sent the data to the MainActivity.class
Intent k = new Intent(this, MainActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
startActivity(k);
And, inside the Main Activity, when calling the ProfileActivity to set it up as a tab:
//Profile tab
intent = new Intent(this, ProfileActivity.class);
Bundle extras = getIntent().getExtras();
intent.putExtra("loginName", extras.getString("loginName"));
spec = mTabHost.newTabSpec("home")
.setIndicator("Home", res.getDrawable(R.drawable.profile_icon))
.setContent(intent);
mTabHost.addTab(spec);
Problem solved, thanks for the help everyone anyways.
Your intent is refering to MainACtivity.class and you are trying to fetch the extras in ProfileActivity. Try changing the MainActivity.class to ProfileActivity.class if that is what your flow is.Please cross check your activities flow.
Hope it helps.
Intent k = new Intent(this, ProfileActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
//login is the EditText variable name for the login text field
startActivity(k);
Since you stated that you want the data sent to ProfileActivity but need to open MainActivity, you can follow one of the 4 approaches.
NOTE: you should be checking when you use getExtra, that the returned value isn't null, and deal with it accordingly.
send the data first to the MainActivity, and then when you launch ProfileActivity from MainActivity, send the data that was previously passed in.
Put the data in a public static field in ProfileActivity. Public static variables can lead to issues, so I would recommend against this.
Save the data to a sharedPreferences file and read it when you need it in ProfileActivity.
SubClass Application, and you can set / access many variables there. The below was copied from Are static fields in Activity classes guaranteed to outlive a create/destroy cycle?:
public class MyApplication extends Application{
private String thing = null;
public String getThing(){
return thing;
}
public void setThing( String thing ){
this.thing = thing;
}
}
public class MyActivity extends Activity {
private MyApplication app;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = ((MyApplication)getApplication());
String thing = app.getThing();
}
}
On MainActivity:
String user = this.getIntent().getStringExtra("loginName");
And when you create the tabhost on MainActivity pass the string the same way:
Intent intent = new Intent().setClass(this, ProfileActivity.class);
intent.putExtra("loginName", user);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = mTabHost.newTabSpec("profile").setIndicator("Profile").setContent(intent);
mTabHost.addTab(spec);
Something like this.
But if you need the user name across the entire application use a Helper Class to store the user name.