From my Sudoku.java I make call to Game.java and pass the difficulty level along with.
private void startGame(int i) {
Log.d(TAG, "clicked on " + i);
Intent intent = new Intent(Sudoku.this, Game.class);
intent.putExtra(Game.KEY_DIFFICULTY, i);
startActivity(intent);
}
Here's part of my Game.java
public class Game extends Activity {
private static final String TAG = "Sudoku" ;
public static final String KEY_DIFFICULTY = "org.example.sudoku.difficulty" ;//What is this?
public static final int DIFFICULTY_EASY = 0;
public static final int DIFFICULTY_MEDIUM = 1;
public static final int DIFFICULTY_HARD = 2;
private int puzzle[] = new int[9 * 9];
private PuzzleView puzzleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate" );
int diff = getIntent().getIntExtra(KEY_DIFFICULTY,DIFFICULTY_EASY); //What is this?
puzzle = getPuzzle(diff);
calculateUsedTiles();
puzzleView = new PuzzleView(this);
setContentView(puzzleView);
puzzleView.requestFocus();
}
}
My question is what is happening in line
public static final String KEY_DIFFICULTY = "org.example.sudoku.difficulty" ;
KEY_DIFFICULTY is final, how will i ever change it.
Also, while fetching the extra data info from intent, how is it storing it?
the value of this public static final String KEY_DIFFICULTY = "org.example.sudoku.difficulty" ; is not changing but imagine intent has a bucket(a hashmap) and KEY_DIFFICULTY is a key in it
You are storing a value against that key and getting it back via intent. You never change the key it self as it is final.
Even if you remove final it will work but you must retrieve the value with the same key you set it with.
So KEY_DIFFICULTY never changes but the value against it in extras bundle is set and retrieved.
public static final String KEY_DIFFICULTY =
"org.example.sudoku.difficulty" ;//What is this?
=> First of all, Intent stores data in a key-value pairs, same like HashMap. So whatever data you would want to store/fetch into/from it, you have to have KEY name.
Now as you have already made KEY_DIFFICULTY as static final, you won't be able to change it as it becomes constant.
Key is used to get the extra data so it should not be changed. And an intent can contain or storing datas via a Bundle. And for more clarification please look at Android Intents.
Cheers
Related
https://developer.android.com/training/basics/firstapp/starting-activity
public class MainActivity extends AppCompatActivity {
public static final String SIGNUP_EMAIL = "com.example.myapplication.SIGNUP_EMAIL";
public static final String SIGNUP_PASSWORD = "com.example.myapplication.SIGNUP_PASSWORD";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void signup(View view) {
Intent intent = new Intent(this, SignupResultActivity.class);
EditText signup_email = (EditText) findViewById(R.id.signup_email);
EditText signup_password = (EditText) findViewById(R.id.signup_password);
String email = signup_email.getText().toString();
String password = signup_password.getText().toString();
intent.putExtra(SIGNUP_EMAIL, email);
intent.putExtra(SIGNUP_PASSWORD, password);
startActivity(intent);
}
}
public static final String SIGNUP_EMAIL = null;
public static final String SIGNUP_PASSWORD = null;
why should not use "null" in this code?
if you put SIGNUP_EMAIL=null and SIGNUP_PASSWORD=null, is not working
Intent is similar to Map, the value of these variables are the keys to index this map. Not only those keys must be non-null, but they must be different from each other.
Quoted from Start another activity (emphasis mine):
The putExtra() method adds the EditText's value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrieve the text value. It's a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.
SIGNUP_EMAIL and SIGNUP_PASSWORD are not default values for mail and password, they are string keys used to pass ang get the values, so they cannot be null.
They are public constants so that the intent can know them to retreive the value.
EDIT: note that the strings are declared final so that the keys cannot be changed afterwards, having a property declared final with a null value should have raised a mental flag as it is a bit useless..
when you want to pass a data from one activity to another one you should use intent.putExtra(name,data);
first parameter is the name and second is data that you want to send
you can use any string that you want for name parameter but it cant be null
in second activity you use it to get data from first activity by this code :
intent.getStringExtra(name)
You can use any unique string to map the values. Null wont work but "null" will work. But keep one thing in mind that for two different values you need to assign different keys also.
Like this:
public static final String SIGNUP_EMAIL = "null";
public static final String SIGNUP_PASSWORD = "Null";
I am storing my JSON data into a arraylist of objects, my object class is Venue and I am passing that data into another activity using serializable from fragment but I am not receiving any values in the actvity. It is receiving the extra. bundle is not null.
My code is:
Fragment:
Intent intent = new Intent(getActivity(), SearchVenueActivity.class);
//pass values
Bundle bundle = new Bundle();
bundle.putSerializable("arrayListVenue",arrayListVenue);
intent.putExtras(bundle);
startActivity(intent);
Activity:
if (getIntent().hasExtra("arrayListVenue")) {
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
rowItems = (ArrayList<Venue>) bundle.getSerializable("arrayListVenue");
else
Log.e("null","null");
}
Venue Class:
public class Venue implements Serializable{
String venue_id;
String venue_name;
String venue_address;
String venue_city;
public String getVenue_city() {
return venue_city;
}
public void setVenue_city(String venue_city) {
this.venue_city = venue_city;
}
public Venue(String venue_id, String venue_name, String venue_address, String venue_city, String venue_zip, String venue_phone, String venue_mobile) {
this.venue_id = venue_id;
this.venue_name = venue_name;
this.venue_address = venue_address;
this.venue_city = venue_city;
this.venue_zip = venue_zip;
this.venue_phone = venue_phone;
this.venue_mobile = venue_mobile;
}
public String getVenue_id() {
return venue_id;
}
public void setVenue_id(String venue_id) {
this.venue_id = venue_id;
}
public String getVenue_name() {
return venue_name;
}
public void setVenue_name(String venue_name) {
this.venue_name = venue_name;
}
}
try this way may this help you
First you want to make
Class Venue implements Serializable
public class Venue implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
}
In your FirstActivity do this way
ArrayList<Venue> VenueArrayList = new ArrayList<Venue>();
Intent intent = new Intent(this,secondActivity.class);
intent.putExtra("VenueArrayList", VenueArrayList);
In your SecondActivity do this way
ArrayList<Venue> VenueArrayList;
VenueArrayList = (ArrayList<Venue>) getIntent().getSerializableExtra(
"VenueArrayList");
Learn from my mistakes.
I've tried to send Arrays and big objects using Serializablethen my app got really slow. Did some tests and found out that when it took a lot of cpu and time to parse it. Therefore (altough its not what you would call best practice) i've created a CacheManager that store object for short time periods and used it to pass larger object between fragments activities.
If you want to make a more readical change to your design (later on in my project i did exactly that) then seperate the data from your fragment/activity completely and load it by LoaderManagers and pass only specific id's or stuff like that (stored stuff in the db in my case so it was easier).
Use intent.putParcelableArrayListExtra("arrayListVenue",arrayListVenue); for putting arraylist to intent and use intent.getParcelableArrayExtra("arrayListVenue") for get arraylist back from intent in your SearchVenueActivity activity
Edit
Tutorial for using parcelable
Use Array List instead of Bundle Elements.
In your Main Activity, try this:
Intent intent = new Intent(this, newactivity.class);
intent.putParceableListArrayExtra("your_array_list_name", arrayList);
In the next activity where you want to retreive it, just use:
getIntent().getExtra("your_array_list_name", new ArrayList<> arrayList2);
I have created a class that holds common variables and functions and is inherited by the activity classes that interface with the different UI pages in my app. I have been passing information between classes and activities using getVariable() and setVariable(input) functions. Suddenly, I can no longer pass information this way (it had been working well until recent edits, and now I can't figure out which change screwed this up). I have used Log outputs to determine that the data is storing properly - with the setVariable(input) functions - but when called later with the getVariable() functions it returns null. Any thoughts?
*Note, I recently started incorporating fragments into my project, extending FragmentActivity instead of Activity on my main class. I don't think this is causing the problem, but could it? If it does, whats the best practice to pass global variable info, and use fragments?
Code samples:
Main Inherited class:
public class MenuBarActivity extends FragmentActivity {
private String keyA;
private String keyB;
private int token;
private String Salt;
private long expires;
public String getKeyB() {
return keyB;
}
public String getKeyA() {
return keyA;
}
public int getTokenID() {
return token;
}
public void setToken(int tkn) {
token = tkn;
}
public void setKeyB(String kyB) {
keyB = kyB;
}
public void setKeyA(String kyA) {
keyA = kyA;
}
//Other common functions
}
LogIn Activity Class (gets log in info from web, stores into global variables):
public class WebContentGet extends MenuBarActivity{
public int tryLogOn(String uEmail, String pw) {
//call to get new keys on start up
JSONObject jObSend = new JSONObject();
try {
jObSend.put("email", uEmail);
jObSend.put("password", pw);
t.start();
t.join();
if(getStatus() == USER_STATUS_SUCCESSFULLOGIN){
String data = getData();
JSONObject jObReturn = new JSONObject(data);
String kyA = jObReturn.getString("keyA");
String kyB = jObReturn.getString("keyB");
int tkn = Integer.parseInt(jObReturn.getString("tokenID"));
String salt = jObReturn.getString("salt");
long exp = Long.parseLong(jObReturn.getString("expiration"));
int uID = Integer.parseInt(jObReturn.getString("userID"));
// Log outputs confirm data being read properly, and reported to setX() functions
setToken(tkn);
setKeyA(kyA);
setKeyB(kyB);
setSalt(salt);
setExpires(exp);
Log.d("WebContentGet tryLogIn","login values stored");
}
return getStatus();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getStatus();
}
}
Activity Class, checks if keyA/B/etc stored:
public class UserLogIn2 extends MenuBarActivity implements EmailListener {
String emailIn;
String pwIn;
Context context = this;
#Override
public void onEmailLogInClick(String email, String pw) {
Log.d("UserLogin2", "onEmailLogInClick");
emailIn = email;
pwIn = pw;
emailIn = emailIn.trim();
emailIn = emailIn.toUpperCase();
Log.d("prepped email", emailIn);
pwIn = pwIn.trim();
WebContentGet webOb = new WebContentGet();
int webLog = webOb.tryLogOn(emailIn, pwIn);
if (webLog == USER_STATUS_SUCCESSFULLOGIN) {
int tkn = getTokenID();
long exp = getExpires();
String kya = getKeyA();
String kyb = getKeyB();
String slt = getSalt();
Log.d("UserLogIn2 - token", String.valueOf(tkn));
//Log statements confirm that getX() functions returning null
session.storeLoginSession(emailIn, pwIn, thisUser, tkn, exp, kya, kyb, slt);
Intent intent1 = new Intent(context, MainActivitiy.class);
startActivity(intent1);
} else {
showDialog(this, "Log in failure", "Incorrect Password");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userlogin2);
}
}
This cannot work, because you have two differend instances of your MenuBarActivity. Also that is not the way to pass data from one activity to another in android.
If you want to use data from one activity in another activity, you have to add them to an intent in the activity which provides the data, and extract them in the other. For more information see here: How do I pass data between Activities in Android application?
If you don't want to start the activity and send the data with the intent, you have to store the data somewhere e.g. SharedPreferences and fetch them again: How to use SharedPreferences in Android to store, fetch and edit values
i need to sum the values in the second activity. I can not get it to total correctly. would someone be kind enough to help me?
final EditText et = (EditText)findViewById(R.id.etwalkingburned);
final EditText ed = (EditText)findViewById(R.id.etrunningburned);
mcardiototalbutton = (Button)findViewById(R.id.cardiototalbutton);
mcardiototalbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int walkingburned = Integer.parseInt(et.getText().toString());
int runningburned = Integer.parseInt(ed.getText().toString());
Intent myIntent = new Intent(getApplicationContext(),TotalActivity.class);
myIntent.putExtra("CardioTotal",walkingburned);
myIntent.putExtra("CardioTotal",runningburned);
startActivity(myIntent);
}
});
}
public class TotalActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.totalactivity);
Bundle extras = getIntent().getExtras();
int walkingburned = extras.getInt("CardioTotal");
int runningburned = extras.getInt("CardioTotal");
int cardiototal = walkingburned + runningburned;
TextView tv = (TextView)findViewById(R.id.cardiototalresult);
walkingburned = walkingburned + 0;
runningburned = runningburned + 0;
cardiototal = walkingburned + runningburned;
tv.setText("Cals.:" + cardiototal);
}
The problem is the way you are putting and getting extras to/from your intent.
myIntent.putExtra("CardioTotal",walkingburned);
myIntent.putExtra("CardioTotal",runningburned);
Think of an extra as a key-value pair. You should have a different string as the first parameter each time you call putExtra, otherwise you will overwrite the value of what you've already put in. So basically you put in the walkingburned value and then overwrote it with the runningburned value because you used the same key string.
Likewise, in your second activity you need to reference the values by their unique string "key" or you will just get the same value two times.
In this situation, there is more than one way to skin a cat. More specifically, you could do the addition in your first activity and only store one extra (the sum) to avoid the confusion of multiple extras. But, I think it would benefit you more to understand how extras and intents works.
For starters, instead of using "CardioTotal"for each extra, you can simply call the string something similar to your variable name. This is what I do and it would make your code easier to understand in my opinion.
myIntent.putExtra("Walking Burned",walkingburned);
myIntent.putExtra("Running Burned",runningburned);
It doesn't really matter what String you put in the first parameter as long as you know that they are supposed to represent different values.
The second change you would then need to make is how you get the extra out of the intent.
int walkingburned = extras.getInt("CardioTotal");
int runningburned = extras.getInt("CardioTotal");
What you are currently doing is retrieving the same value (you are using the same key string therefore it is the same value) to two separate variables. So the value you would be seeing is double the runningburned value.
Now, since you have two different Strings for the two different variables in your intent, you can just say:
int walkingburned = extras.getInt("Walking Burned");
int runningburned = extras.getInt("Running Burned");
The rest of your code is fine.
You also don't need these lines in your TotalActivity
walkingburned = walkingburned + 0;
runningburned = runningburned + 0;
Sorry this was a really long answer but I wanted to explain a few things.
Hope it helps!
okay so in my other android activity I have it display a button on the screen if a certain string is in the array. I will be using the split function on a stored string to turn my string back into an array and then assinging that array into my private favorites array. In this example I am trying to get it to display a button if the string "UltimateBP" is in the private array favorites.
if i assign it directly using:
favorites[1]="UltimateBP";
it works and the button shows up correctly.
however if I assign it using the method below. it will not show up.
It does the same thing when I use the TextUtils split() method.
public class SampleApplication extends Application{
private String mStringValue;
private int numOfFavorites=1;
private String[] favorites = new String[150];
#Override
public void onCreate() {
mStringValue = "SavageLook.com";
favorites[0] = "None";
String someWords = "UltimateBP|Orange|Yellow";
String aColors[] = someWords.split("\\|");
numOfFavorites++;
String X = aColors[0];
favorites[1]=X;
super.onCreate();
}
Instead of using:
String aColors[] = someWords.split("\\|");
You just need to show "|" like:
String aColors[] = someWords.split("|");