https://stackoverflow.com/a/2508138/1508448
Please go through the link above.
My compiler is showing a problem in REQ_CODE_PICK_IMAGE.
It asks if I need to create a variable. What is it?
//you need to create an variable in your class
public final static int REQ_CODE_PICK_IMAGE=1
switch(case)
case 1: //instead of hardcoding here you need to declare the variable as integer
break;
case 2;
.
.
EDIT:
When an activity exits, it can call setResult(int) to return data back to its parent. It must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it can optionally return back an Intent containing any additional data it wants. All of this information appears back on the parent's Activity.onActivityResult(), along with the integer identifier it originally supplied.
Related
I don't understand the meaning, value, or importance of RESULT_FIRST_USER, other than that my own result codes must be greater than 1. Will someone please explain it? RESULT_OK and RESULT_CANCELED make perfect sense to an english speaker. But what in the world of android is RESULT_FIRST_USER? All the documentations says about it is
Start of user-defined activity results.
The answer to the question is actually the combination of comments from #CommonsWare and #Chris. So, for the sake of progeny, I am going to consolidate the comments and make it available in one place.
Basically, there are two predefined constants for the requestCode and they are Activity.RESULT_OK and Activity.RESULT_CANCELLED. However, android developers can also set custom codes for their apps by using the offset Activity.RESULT_FIRST_USER. Doing so ensures that there are no clashes between constants set at the OS level and the app level.
Purely, my opinion, I think that the FIRST USER suffix is meant to refer to developers – just like how end consumer refers to consumers of a said product – who are the first users before the app users.
Below is an example of how you can use this offset,
public static final int MY_RESULT_CODE = Activity.RESULT_FIRST_USER + 1;
When an activity ends, it can call setResult(int) to return data back to its parent.
It must always supply a result code, which can be the standard results
RESULT_CANCELED (Standard activity result: Operation canceled. Constant Value: 0)
RESULT_OK (Standard activity result: operation succeeded. Constant Value: -1), or any custom values starting at RESULT_FIRST_USER (Start of user-defined activity results. Constant Value: 1). In addition, it can optionally return back an Intent containing any additional data it wants.
So, bottom line since you must supply the result code Android "helps' you a bit by saying: please state if the result code of this Activity is OK, CANCELED or you have your own, custom made, result.
When you finish an activity, you can call setResult(RESULT_CODE) to send back data to another activity. If you don't call this method, the default value will be RESULT_CANCELLED (which equals 0)
Example of returning data:
Intent intent= new Intent();
intent.putExtra("data",data);
setResult(YOUR_RESULT_CODE,intent);
finish();
An activity result is a 32-bit integer. The possible values are divided into three ranges:
-2 and below: Unused.
-1 and 0: System-defined values. That is, activity results defined by Android.
1 and above: User-defined values. That is, activity results defined by app developers.
RESULT_FIRST_USER identifies the first value in the user-defined range. The following sample definitions show how system- and user-defined values fit together:
public static final int RESULT_OK = -1; // Defined by Android. You don't write this code.
public static final int RESULT_CANCELED = 0; // Defined by Android. You don't write this code.
public static final int RESULT_ENDED_GAME = RESULT_FIRST_USER + 0; // Defined by an app.
public static final int RESULT_ACTIVATED_RADAR = RESULT_FIRST_USER + 1; // Defined by an app.
public static final int RESULT_LAUNCHED_ROCKETS = RESULT_FIRST_USER + 2; // Defined by an app.
In my app I have a profile pic of the user. If he previously logged in, I download it from my server, otherwise he takes a pic from the camera or gallery. Either way, I store it in a class called DataStorage in a static public Bitmap variable thus:
public class DataStorage {
.
.
public static Bitmap origProfilePic; //not saved on app close
.
.
Now, if the user decides to re-do his profile, I log him out send him back to the profile creation screen, and I call:
DataStorage.origProfilePic = null;
(By the way, null is a legitimate value for this picture - we allow users to have no picture). The profile creation is through 2 activities - first choosing a username and password, then choosing a picture and other details. What's weird is that although I set the picture variable to null, somehow when I get to the end of the profile creation, it has gone back to it's original value, and I somehow have a user with the old profile picture (this is in the case where he did not select a new picture)
I've logged it n the OnCreate functions of the two activities:
onCreate SignUpActivity1, origPic = null
then
onCreate SignUpActivity2, origPic = android.graphics.Bitmap#42ba7438
But SignupActivity1 calls the intent for SignUpActivity2 and nowhere in SiugnupActivity1 is there a reference to DataStorage.origProfilePic except in my log statements.
I decided to check one more time in SignUpActivity1 if the value changes and I found...just as I invoke SignupActivity2:
Intent intent = new Intent(SignUpActivity1.this, SignUpActivity2.class);
intent.putExtra("EMAIL", email.toString());
intent.putExtra("PASSWORD", password.toString());
startActivity(intent);
Log.e("Kibi", "End SignUpActivity1, origPic = " + DataStorage.origProfilePic);
finish();
This somehow has:
End SignUpActivity1, origPic = android.graphics.Bitmap#42ba7438
This is quite repeatable in this specific case, though I certainly set the bitmap to null in other places and don't see it popping back up.
I saw a few things on SO about static Bitmaps being a danger for memory leaks, though I don't see a memory leak right now, I worry that I must be doing something very wrong if setting to null cannot be relied upon.
Can anyone explain what I am doing wrong and what the best way is to store this Bitmap in a basically volatile way?
It makes sense that both values change when you use DataStorage.origProfilePic in both activities. Since it's a static value, both activities are pointing to the same memory object.
DataStorage.origProfilePic is pointing to a piece of memory where your bitmap is stored. Assuming you use something like:
#SignUpActivity1
Bitmap origPic = DataStorage.origProfilePic;
#SignUpActivity2
Bitmap origPic = DataStorage.origProfilePic;
What happens here is that you create a reference to DataStorage.origProfilePic. That means you practically have the same value in SignUpActivity1.origPic and SignUpActivity2.origPic.
When you call this rule:
startActivity(intent);
The OnCreate method in SignUpActivity2 will be invoked. You probably will set here (or somewhere else) the value of DataStorage.origProfilePic, which means the value of SignUpActivity1.origPic and SignUpActivity2.origPic also changed (not entire true, but will have a different output).
Also be carefull with DataStorage.origProfilePic = null;. This only set the reference to null, but doesn't clear the bitmap from memory. Use DataStorage.origProfilePic.recycle(); to clear the bitmap from memory.
I am on page 301 of this book and it is an example of an Activity getting "extras" from the intent that started it. I am fairly new to Java so maybe am missing something pretty obvious but...
I thought that when you declare a variable as "final" it meant that it doesn't change.
There is a line of code initialising a final variable:
public static final String EXTRA_MESSAGE="msg";
and then later in onCreate method:
tv.setText(getIntent().getStringExtra(EXTRA_MESSAGE));
The text displayed in the activity is not "msg" but is the string passed from the intent "I am the other activity". Why do you have to have the variable declaration above for the code to work? I don't understand what its doing.
Thanks
You are getting the extra received from another Activity indexed by the key 'msg'.
Like when you do this with the Intent used to start your Activity:
intent.putExtra("msg", "text going in the TextView");
The key is 'msg', but the value you get for the TextView is 'text going in the TextView'
Yes, final means EXTRA_MESSAGE value won't change, but you're not displaying EXTRA_MESSAGE value, but
getIntent().getStringExtra(EXTRA_MESSAGE)
which actually contains the value put in the previous activity. Regarding your question
Why do you have to have the variable declaration above for the code to work?
You don't actually need that variable for the code to work, but it's a good practice to use constant values instead of just hardcoding string values such in.-
getIntent().getStringExtra("msg")
The parameter you pass to getStringExtra is the key to which the String is mapped. All the extras you put in an Intent are mapped as key-value, so if you want to get a value you have to know the key, which must be the same key you used in the previous activity to save the value (with putStringExtra).
http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)
I still am a beginner in Android development and will try to make my question as clear as possible with a schema of what I have in my mind.
Purpose of this application:
- I want the user to have the choice between a few buttons and when clicking on any of them, it would open a list view with different content according to the button.
ex : if you click on "Category_1" button, only elements with a fitting id will appear in the listview.
So far, I have :
- defined my "handler" class (extends SQLiteOpenHelper) : name/path of DB, definition of CRUD, .getReadableDatabase, etc.
- define a class for my table, in my case "Restaurants.java" with getters/setters and constructor.
- defined my MainActivity with empty listeners for my button.
- defined my "DatabaseAdapter.java" in which I want to define the methods/sql requests which will communicate with the database and get the information I want from it.
- defined my ListViewActivity with nothing to display so far.
Here is a schema of what I want with the idea of how to make it to try to optimize my application :
To sum up:
- I want a listener for each button setting a variable to a certain value (for example: "if you click on 1 then set the value of A to 1") and opening the ListViewActivity.
- There would be a method defined in "...Adapter.java" sending a request to the database and having the variable A defined earlier as an input.
- And then, when clicking on the button, the ListViewActivity will open and call the method from "..Adapter.java", and finally display the results.
So, here are my questions :
- First of all, is the design optimized enough to allow my application to run fast? I think it should as all the button open only one activity and there is only one method defined for all buttons.
- I have a hard time defining the method in "...Adapter.java" which will be called from my ListViewAcitivity. The input should be the variable obtained when clicking on the button but I don't really know how to get a variable in one activity, open a second activity where to display results by using the variable in a third activity... :s
Is it fine to set a variable to a certain value when we click on a button and use this variable in another class as an input for a method?
public findNameInTable(int A){
string sql = " select NAME from MY_TABLE where CAT1 = " + A;
c = database.rawQuery(sql, null); }
Thanks in advance for any indications, suggestions or links which could help me to make my application come true, and sorry if some questions really sounds newbie, I am starting !
Have a good day !
Part 1: The best way I have found to pass variables to other activities is with a putExtra(String, variable);. Say you change the variable name on a button press, you can then call:
YourNewActivityClassName var = new YourNewActivityClassName();
Intent i = new Intent(context, YourNewActivityClassName.class);
i.putExtra("name", name);
startActivity(i);
Then in the activity you just created, you can call this in the onCreate method:
Intent i = getIntent();
final String name = i.getStringExtra("name");
Of course this is assuming the variable was defined as a String before the putExtra was called.
If you want to use other variable types, there are different get***Extra commands you can call like getIntExtra(int, defaultval) but the putExtra will still be used to send it.
Part 2: For calling a method with a variable assigned in a button click, I have found the best way to do this is with a "holder class" this holder can be defined as a final, and a button press assigns a value to one of it's slots. Here is my holder for Integers:
public class holder {
int to;
public void setTo(int to){
this.to = to;
}
public int getTo(){
return to;
}
}
I instantiate my class as final within my on create final holder hold = new holder();
then call my hold.setTo(int); within a list click listener. When I want to get the data, I simply call hold.getTo(); and I have my integer.
Heres a similar post: Pass value outside of public void onClick
Hope this helps!
Mike
hi all I have a variable in first activity i need to add values returned from second activity and store it in this variables. Switching between activities happens multiple times.... Any ideas..?
here is a piece of code which stores current value each time and not the Sum of it...
double quantity = Double.parseDouble(s1[1]);
double amount = Double.parseDouble(s1[2]);
if(s1[3].equals(""))
{
totalint = (quantity*(amount));
Log.d("hitherebbbbbbb",((Double)totalint).toString());
grandTotal =+totalint;
}
else
{
deduction = Double.parseDouble(s1[3]);
totalint = ((quantity*(amount-deduction*amount/100)));
Log.d("hitherebbbbbbb",((Double)totalint).toString());
grandTotal =+totalint;
}
If the amount of variables stays the same you could always use sharedpreferences. They are super simple to use and you can add a sharedpreference listener to update your activity when a value is changed. If the amount of variables changes (eg you have 3 integers at one time but maybe your user can change it so you need 5) then I would do something a little more complex that may not be the best option but I like it because I find it more simple than a database. Let me know which scenario best describes your situation and I'll get you more documentation.
You probably want to return the values from the second activity through its return intent and do a startActivityForResult() in the first activity.
you would do this by creating an intent in your second activity, setting any relevant return data, and calling
setResult(Activity.RESULT_OK, returnIntent);
finish();
You will be called back in the onActivityResult() method when the second activity is finished. You would then extract the values from the return intent and update your local storage.