I was wondering if anyone could tell me how I could check a checkBox in an activity from another activity.
I'm making a homework app and I want to put a check next to the questions that have been completed.
So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.
You should use SharedPreferences for that. call this in the first activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.putBoolean("KEY", <your value>).apply();
and something similar in another activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isTicked = prefs.getBoolean("KEY", <default boolean value>);
where KEY can be anything, for example, your question's number
You should use intent and bundle logic for passing data between activities.(in most cases)
In the first activity, whenever you are creating the second activity, you pass your data.
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("checked",checkBox.isChecked());
startActivity(intent);
In the second activity you receive your data by using :
Intent receivedIntent = getIntent();
boolean finalChecked = receivedIntent.getExtras().getBoolean("checked");
//now you can apply your logic with finalChecked variable
You can save checked check question to a bundle and pass it as extra to your second activity through intent and read it from that intent inside your second activity
In your first activity do something like this
public class FirstActivity extends Activity {
public static final String EXTRA_CHECKED_QUESTION = "Checked Question";
// other codes here
private void startSecondActivity() {
String checkedQuestion = getCheckedQuestion(); // a method to get checked question
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(FirstActivity.EXTRA_CHECKED_QUESTION, checkedQuestion);
startActivity(intent);
}
}
then in your second activity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstance) {
// other codes
String checkedQuestion = getIntent().getStringExtra(FirstActivity.EXTRA_CHECKED_QUESTION);
// do whatever you want with checkQuestion
}
}
Please note that the string which you pass as first parameter to putExtra() method in FirstActivity, should be same as the string you are using with getStringExtra() to retrieve your extra in SecondActivity, otherwise you can not retrieve your passed extra in SecondActivity.
Also, I did not write these codes inside idea, so there might be syntax error
Read more about intent here
Related
Consider you have a Button A and button B both of them when clicked it start Activity1 which contains only one TextView.
Now When I click on Button A it should start Activity1 and setTextView to "The click was from A"
and when clicked on B it should set the text to "The click was from B".
So I figure out that by making a global Boolean variable but I wanted to know is there any other way that is more efficient than making a global Boolean variable(the code become really messy with Boolean)
And this all is just an example in reality I want to add a lot of code instead of just setting the text.
TL;DR
Pass arguments with your Intent object that launches Activity2. Use putExtra methods. That is the default way of passing small pieces of data.
Explained
"making a global Boolean variable" is a bad solution (nothing personal, it just does not fit the given problem) in this situation as anyone has access to that variable and the value can be changed at any point in time making it unreliable.
When you launch activity with Intent you can use putExtra methods on it (example of such method in docs).
For example, there is a putExtra that accepts boolean as a value: link. Using that method you can remove the global variable, but the code still could be messy.
If this boolean variable is simply deciding which label to show you can pass the label itself using these putExtra methods. It would look like this:
// From Activity1 when you click Button A
buttonA.setOnClickListener {
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra(Activity2.SOME_KEY, "This label is from buttonA.");
startActivity(intent);
}
// From Activity1 when you click Button B
buttonB.setOnClickListener {
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra(Activity2.SOME_KEY, "This label is from buttonB. A slightly different one.");
startActivity(intent);
}
Activity2.SOME_KEY is some public static variable that you should declare to be sure that you use the same key for setting and getting back the value. You can name it differently. It must be of String type. There is no need to declare it in Activity2 class but since it is the key for passing arguments for Activity2 only I think that is the most fitting place.
And now in you can get that value back in Activity2:
class Activity2 extends Activity {
public static String SOME_KEY = "some string value";
private String labelValue = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
labelValue = getIntent().getStringExtra(SOME_KEY);
// ... other stuff here like setContentView
// use `labelValue` to set text into some TextView.
}
}
I'm new to android studio and going through intents. I'm creating a registration app which takes user information in first 4 activities and display them altogether in respective views the 5th activity.
My app has personal, professional,address and other detailed activities that are to be retrieved from edit texts and later displayed on the very last screen.
I can only retrieve data only on the next consecutive screen but not save them and add to last activity later on.
Is there any way that i can do the storing and retrieving part using only intents between 2 activities that are not consecutive to each other ? Any help will be appreciated...!!
Yes you can do so by sending the data form one activity to the other activity in chain.
Let say your app starts at ActivityOne then goes to ActivityTwo then to ActivityThree then to ActivityFour then to ActivityFive and submits the data here in ActivityFive. Each activity has a EditText to enter data and a button which on clicking goes to the next activity.
In ActivityOne create and then start an intent on the button click i.e. inside onClick():
Intent i = new Intent(ActivityOne.this,ActivityTwo.class);
i.putExtra("Name",edittext.getText().toString());//get sting from 1st edittext
startActivity(i);
Now your second activity has been started i.e. ActivityTwo.
In that activities onCreate() method create an IntentIntent a = getIntent();
Now in onClick method for the button of this activity do the following:
Intent i = new Intent(ActivityTwo.this,ActivityThree.class);
i.putExtra("Address",edittextTwo.getText().toString());//This line fetches the data from the activities edittext
i.putExtra("Name", a.getStringExtra("Name"));//This line fetches the data from the intent which called this activity.
startActivity(i);
Now in the third activity which has been started i.e. ActivityThree.
Do the same thing in the activities onCreate() method i.e. create an IntentIntent a = getIntent();
Now in onClick method for the button of this activity do the same thing that you did previously but also fetch the data passed from the previous activity:
Intent i = new Intent(ActivityThree.this,ActivityFour.class);
i.putExtra("email",edittextThree.getText().toString());//This line fetches the data from the activity's edittext
i.putExtra("Name", a.getStringExtra("Name"));//This line fetches the data from the intent which called this activity.
i.putExtra("Address", a.getStringExtra("Address"));//This line fetches the data from the intent which called this activity.
startActivity(i);
Continue this in all the activities and in the end you will be able to get all the data in the final activity.
The logic here is to pass the data from one activity to the other and keep on adding data on the go.
There are many ways to pass the data.One easy and efficient way to implement.create a public class in your package.In that class declare your values as static like below.
public class MyDataClass {
public static String name;
public static String userid;
}
you can pass the values like below
MyDataClass myobj=new MyDataClass();
myobj.name="Jhon";
myobj.username="Jhon#gmail.com";
To fetch the value from anywhere Activity or fragment use this
String val=myobj.name;
String val=myobj.username;
You can use singleton class
Create one model class and add the data from that four activites
public class MySingleton {
private UserModel user_details;
private static MySingleton ourInstance = new MySingleton();
public static MySingleton getInstance() {
return ourInstance;
}
private MySingleton() {
}
public void setUserDetails(UserModel news) {
this.user_details= news;
}
public UserModel getUserDetails() {
return user_details;
}
}
//add user details
MySingleton mysingleton= MySingleton .getInstance();
mysingleton.setUserDetails(userdetails); // userdetails - model class object
Use SharedPreference to save your data using key-value pairs. And then you can retrieve the data in any activity using the respective key. Just make sure you use the proper key to save a variable.
public SharedPreferences sharedPref;
public SharedPreferences.Editor editor;
sharedPref = getSharedPreferences("name_of_your_preference", Context.MODE_PRIVATE);
editor = sharedPref.edit();
editor.putString("key" , "value"); //use to save a value
editor.commit();
sharedPref.getString("key", null); // retrieve the data
I'm also new but why not create One Activity which hold the DataModels and collect the UserInformation within Fragments and set them to the Activity on nextBtnClick?
Something like this:
final Button nextFragmentButton = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((MyActivity)getActivity()).setUserDataModel(dataModel)
});
Isnt it a bad design, if you have a lot of activities and put data thru them?
If you would use Fragments, the root activity could hold all the data and would datahandling simplify.
I have a string in activity2
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng);
I want to insert this string into text field in activity1. How can I do that?
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Then you can set the text in the TextView:
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
You can send data from one actvity to another with an Intent
Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);
You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.
Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);
Then all you have to do is call setText on your TextView and use that string.
TWO CASES
There are two situations possible when we talk about passing data between activities.
Let's say there are two activities A and B and there is a String X. and you are in Activity A.
Now let's see the two cases
A-------->B
A<--------B
CASE 1:
String X is in A and you want to get it in Activity B.
It is very straightforward.
In Activity A.
1) Create Intent
2) Put Extra value
3) startActivity
Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)
In Activity B
Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).
Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");
Case 2:
This case is little tricky if u are new to Android
development Because you are in Activity A, you move to Activity B,
collect the string, move back to Activity A and retrieve the
collected String or data. Let's see how to deal with this situation.
In Activity A
1) Create Intent
2) start an activity with a request code.
Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);
In Activity B
1) Put string X in intent
2) Set result
3) Finish activity
Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent); // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();
Again in Activity A
1) Override onActivityResult method
onActivityResult(int req_code, int res_code, Intent data)
{
if(req_code==your_req_code)
{
String X = data.getStringExtra("KEY")
}
}
Further understanding of Case 2
You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)
reqCode is useful when you have to identify from which activity you are getting the result from.
Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.
resCode: is useful when you have to distinguish between how results are coming back to requesting activity.
For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.
Relevant Links
Read more on Getting result
Say there is EditText et1 in ur MainActivity and u wanna pass this to SecondActivity
String s=et1.getText().toString();
Bundle basket= new Bundle();
basket.putString("abc", s);
Intent a=new Intent(MainActivity.this,SecondActivity.class);
a.putExtras(basket);
startActivity(a);
now in Second Activity, say u wanna put the string passed from EditText et1 to TextView txt1 of SecondActivity
Bundle gt=getIntent().getExtras();
str=gt.getString("abc");
txt1.setText(str);
Intent intent = new Intent(activity1.this, activity2.class);
intent.putExtra("message", message);
startActivity(intent);
In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Intents are intense.
Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.
You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher
In order to insert the text from activity2 to activity1, you first need to create a visit function in activity2.
public void visitactivity1()
{
Intent i = new Intent(this, activity1.class);
i.putExtra("key", message);
startActivity(i);
}
After creating this function, you need to call it from your onCreate() function of activity2:
visitactivity1();
Next, go on to the activity1 Java file. In its onCreate() function, create a Bundle object, fetch the earlier message via its key through this object, and store it in a String.
Bundle b = getIntent().getExtras();
String message = b.getString("key", ""); // the blank String in the second parameter is the default value of this variable. In case the value from previous activity fails to be obtained, the app won't crash: instead, it'll go with the default value of an empty string
Now put this element in a TextView or EditText, or whichever layout element you prefer using the setText() function.
For those people who use Kotlin do this instead:
Create a method with a parameter containing String Object.
Navigate to another Activity
For Example,
// * The Method I Mentioned Above
private fun parseTheValue(#NonNull valueYouWantToParse: String)
{
val intent = Intent(this, AnotherActivity::class.java)
intent.putExtra("value", valueYouWantToParse)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent)
this.finish()
}
Then just call parseTheValue("the String that you want to parse")
e.g,
val theValue: String
parseTheValue(theValue)
then in the other activity,
val value: Bundle = intent.extras!!
// * enter the `name` from the `#param`
val str: String = value.getString("value").toString()
// * For testing
println(str)
Hope This Help, Happy Coding!
~ Kotlin Code Added By John Melody~
So I was doing this but my output is weird ,
this is the 1st activity
up = findViewById(R.id.button);
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, updatestudents.class);
intent.putExtra("updating",updating);
startActivity(intent);
}
});
this is the 2nd activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
Current_Value = getIntent().getStringExtra("updating");
}
u = findViewById(R.id.text);
u.setText("updating " + Current_Value);
Here I am retrieving String in 2nd Activity
And this is my output
enter image description here
I have 3 activities, First Activity(Main), Middle Activity, and Final Activity. Currently, I'm sending Serializable Arraylists via Intent. Which works great when I create an intent to start Final Activity from within First Activity, although it skips over Middle Activity which needs to be displayed. The problem I'm running into is that all of the data originates in First Activity, and I can't seem to send it from First Activity, to Final Activity, and still display Middle Activity. I'm wondering if I should try to send the Arraylists via SharedPreferences instead?
List<String> proStrings = new ArrayList<>();
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SendButton:
Intent intent = new Intent(FirstActivity.this, MiddleActivity.class);
intent.putExtra("proGolferArray", String.valueOf(i));
//CREATE BUNDLE AND ADD ARRAYLIST AS SERIALIZABLE
Bundle bundle = new Bundle();
bundle.putSerializable("PROGOLFER", (Serializable) proStrings);
//START NEW INTENT WITH ARRAYLIST BUNDLE PASSED IN
intentFinal = new Intent(this, FinalActivity.class);
intentFinal.putExtra("KEY", bundle);
startActivity(intent);
//startActivity(intentFinal);
//this doesn't look right, I must be doing this wrong....
break;
}
}
}
From MiddleActivity, I start the FinalActivity, but when I do, the data from the ArrayList in First Activity doesn't appear in FinalActivity at all. Is there a way to start 'finalIntent' from Middle Activity so that the data is sent to FinalActivity properly?
If you are trying to display MiddleActivity and then FinalActivity, try the following?
Launch MiddleActivity from FirstActivity along with the arraylist
Get the arraylist in onCreate() of MiddleActivity
Start FinalActivity from MiddleActivity along with the arraylist retrieved in step 2
And by the way the code you posted in the question is wrong. You should attach the bundle to intent and not finalintent
I'm using Eclipse for windows 7 and I am making an informative application(just text and offline content).
In my app I have about 180 buttons. Each button will lead to another screen. I need to know how to make each button lead to a specific screen?
And also, is there a way to like duplicate the code and not spend hours copying and pasting the code 180 times?
Check my code below for the first two screens:
That's for the MainActivity.java:
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
}
});
}
I mean that code is only for one single button. Am I supposed to repeat this for every single button?
and also a question, how many classes should I do? 180 main activities, 180 fragment_main.xml and 180 activity_main.xml?
That's my idea, since your application is just a "informative application" you can create two activities:
Main activity with buttons
"Information page"
To do it i need info about how you get this informations:
In a SQLite Database.
In a string-array
Personally, i prefer a SQLite DB it allows you to improve it without problems in the future.
About the Information activity:
Example: in your layout you have a TextView where will be added the text which this activity should be passed.
To make it dynamic in your case we pass the string to show using Intents, in our onCreate we add something like this:
Intent intent = getIntents();
String stringToDisplay = null;
if (intent != null)
{
stringToDisplay = intent.getStringExtra (EXTRA_STRING_CONTENT);
}
getIntents will get the Intent object which is created and passed to it by our main activity. getStringExtra is a simple method which says to Android: i want to get the string which is saved with the key EXTRA_STRING_CONTENT (it's something like a Map)
EXTRA_STRING_CONTENT is a field which we used to make sure we don't make any error in passing data, since we need to use the same name when we pass it (in MainActivity) and when we read it (InformationActivity)
public static final String EXTRA_STRING_CONTENT = "EXTRA_STRING_CONTENT";
Ok, we are done.
We now only need to set the string to our TextView:
TextView infoTextView = (TextView) findViewById(R.id.infotextview);
infoTextView.setText (stringToDisplay);
Stop it.
Now we should go to our MainActivity code and modify our addListenerOnButton
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
}
});
Well, i will focus on this two lines
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
We need to pass the string to display here, how?
Before we used getStringExtra now it's similar (note: it's the same Intent class) but now we need the putExtra method, the compiler will select the correct overload for us so we just need to do
String stringToDisplay = "Hello world";
intent.putExtra(InformativeActivity.EXTRA_STRING_CONTENT, stringToDisplay);
(Note: InformativeActivity.EXTRA_STRING_CONTENT)
With the current code we will always sent Hello world to the second activity but we need something of dynamic based on the button... well now this depends on how you get the data.
If it's a string-array, you can save the string-array in an array and then based on the button (if it's the first sent string index 0, etc.).
An example:
int buttonId = 1; // it will be a general variable, if it's button 1 it will be 0, if 2-1 etc.
String[] informations = getResources().getStringArray(R.array.infos); // in a real code you should move it outside the `onClick` code and put it in a static final field.
intent.putExtra(InformativeActivity.EXTRA_STRING_CONTENT, informations[buttonId]); // it's the same of above
If you understand the concept you will know how to adapt the code based on your needs.
There are some cases where you need more info or what you want to sent is something which is better if managed by the second activity (example: in a sqlite database you could sent only the id of the line and read lines in the second activity based on this id)
Some things which you could change:
Avoid to call it MainActivity2, it's not so helpful as name
You don't need really to save Context, you could just use MainActivity.this
Try to make your addListenerOnButton more general, example take as argument a Button and set the listener to it.. don't read it from XML you will end up with 180 methods for every button.