How to improve the code below? I'm new to Java, coming from iOS background. I think intent needs to go to a separate variable.
public void activityOpener(int a) {
if (a == 1) {
Intent intent = new Intent (this, proj1new.class);
startActivity(intent);
}else {
Intent intent = new Intent (this, BasicNumbers.class);
startActivity(intent);
}
}
public void activityOpener(int a) {
Intent intent;
if (a == 1) {
intent = new Intent (this, proj1new.class);
}else {
intent = new Intent (this, BasicNumbers.class);
}
startActivity(intent);
Is that what you mean? Code is now a bit cleaner
I'd refactor it like this:
public void activityOpener(int a) {
Class<?> cls = a == 1
? proj1new.class
: BasicNumbers.class;
Intent intent = new Intent(this, cls);
startActivity(intent);
}
Not much of a change, but it makes clear that only the new activity class depends on a.
If your style is to go for brevity, the whole thing can be reduced to a one-liner (at the expense of flexibility if you want to expand the logic in the future):
public void activityOpener(int a) {
startActivity(new Intent(this, a == 1 ? proj1new.class : BasicNumbers.class));
}
Related
In my app, there are so many activities which are referred to as levels. And one activity is Reward activity. when i win level-1, reward activity opens. Now i want to replay the level-1. For this i have used getExtra(). My app crashes when i click the replay button.
Houselevel1.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.Reward");
intent.putExtra("activity", "level1");
startActivity(intent);
}
}
HouseLevel2.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.Reward");
intent.putExtra("activity", "level2");
startActivity(intent);
}
}
Reward.java
public void replayLevel() {
replay = (ImageButton) findViewById(R.id.replay);
Intent intent= getIntent();
activity = intent.getStringExtra("activity");
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View paramView) {
if(activity.equals("level2")){
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.HouseLevel2");
startActivity(intent);
}
if(activity.equals("level1")){
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.Houselevel1");
startActivity(intent);
}
}
});
}
With the java code you've posted, in the Reward.java file, you're trying to create another Intent Object with the same name as the one declared in the scope right above it. Because of this, the build will never be successful.
Also, when you declare intents, you MUST pass on the activity_name.class file.
Something you can try:
1) HouseLevel1.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.Reward.class);
intent.putExtra("activity", "level1");
startActivity(intent);
}
}
2) HouseLevel2.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.Reward.class);
intent.putExtra("activity", "level2");
startActivity(intent);
}
}
3) Reward.java
public void replayLevel() {
replay = (ImageButton) findViewById(R.id.replay);
Intent intent= getIntent();
activity = intent.getStringExtra("activity");
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View paramView) {
if(activity.equals("level2")){
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.HouseLevel2.class);
startActivity(intent);
}
else if(activity.equals("level1")){
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.Houselevel1.class);
startActivity(intent);
}
}
});
}
Also, if you're simply using the Reward.java file to get the previous intent's data, perform some calculation, and send some data back to the calling, or parent activity, then you can simply use the startActivityForResult() method, which takes care what what you're trying to do manually.
Here's a small article that might be able to help you with the problem
http://www.vogella.com/tutorials/AndroidIntent/article.html#retrieving-result-data-from-a-sub-activity
If all you want is go from Activity 1 or to 2 to a Reward activity grab something and send that something back to either activity.
What you do is startActivityForResult You pass an Id (constant number) do what you do on the Reward activty, pack what you need to return in a Bundle, and set ActivtyResult to OK and close your activity.
Your app will go back to the Activity1 or 2 whoever call it. On those activties you override the method onActivityResult There you check if the id on which the result is coming from is the Id you sent on the startActivityForResult and if the status is OK.
Then you have whatever was set on the Reward activity. The Reward activity don't need to know from where it came from if only will grab some data. So you can later have an Activity3 that calls the Reward activity and you do not need to modify the Reward activity.
It is explain here check the accepted answer.
How to manage `startActivityForResult` on Android?
I have 2 Activities. On 2nd activity i have data which i want to move by button "Back" to 1st Activity.
Usually i moving by something like this:
button12.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pass=editText2.getText().toString();
Intent intent = new Intent(FirstActivity.this, MapsActivity.class);
intent.putExtra("pass_value", pass);
startActivity(intent);
}
});
But now i dont want to start Activity, instead of this i want close Activity, so i need to use finish()
Currently i created this, but no working:
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FirstActivity.class);
intent.putExtra("number", numberOfTrue);
finish();
}
});
I need something more in this code, but i dont know what.
Start a new activity with
Intent intent = new Intent(FirstActivity.this, MapsActivity.class);
intent.putExtra("pass_value", pass);
startActivityForResult(intent,1)
You can use setResult method to acheive your desired result
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
get Your result in FirstActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
int num = data.getIntExtra("pass_value");
}
}
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtra("number", numberOfTrue); }});
You need to open by function startActivityForResult
startActivityForResult(Intent intent, int requestCode)
And get the data returned in the function
onActivityResult
As an example you can see a face to the camera for a picture
I was creating notification Intent that opens one of two activities depending on condition. Worked as expected since I have all intent flags required for this.
I tried to optimize my method flow by extracting new Intent and Class, so optimized code looked like this:
Class ActivityClass;
if (siteId > 0) {
//...
ActivityClass = DetailActivity.class;
} else {
//...
ActivityClass = MainActivityWithMenu.class;
}
Intent notificationIntent = new Intent(appContext, ActivityClass);
But then my notification stopped opening activities, so I changed it to:
Intent notificationIntent = null;
if (siteId > 0) {
notificationIntent = new Intent(appContext, DetailActivity.class);
} else {
notificationIntent = new Intent(appContext, MainActivityWithMenu.class);
}
Second version works without any problems, but I was wondering what is the difference between Activity.class and Class class and why first snippet won't work with Intent?
Whole function:
String title = "Upcoming site:";
Intent notificationIntent = null;
if (siteId > 0) {
pref.setNewVar("notificationSiteId", String.valueOf(siteId));
notificationIntent = new Intent(appContext, DetailActivity.class);
} else {
notificationIntent = new Intent(appContext, MainActivityWithMenu.class);
}
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationIntent.putExtra("siteId", siteId);
PendingIntent pendingIntent = PendingIntent.getActivity(appContext, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification.Builder nBuilder = new Notification.Builder(appContext)
.setContentTitle("Neeco - " + title)
.setContentText(text)
.setSmallIcon(R.drawable.clock_start)
.setContentIntent(pendingIntent);
boolean updateNotification = true;
if (pref.getVar("notificationText") != null && !pref.getVar("notificationText").equals(text)) {
Log.d(TAG, "New text in notification - " + text);
nBuilder.setSound(alarmSound);
nBuilder.setPriority(priority);
pref.setNewVar("notificationText", text);
} else if (pref.getVar("notificationText") == null) {
nBuilder.setSound(alarmSound);
nBuilder.setPriority(priority);
pref.setNewVar("notificationText", text);
} else {
updateNotification = false;
}
if (updateNotification) {
Notification notification = nBuilder.build();
NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Config.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
}
Class
It's a compiled form of.Java file.
A class is a combination of methods, variables and data types. Every Java or Android project must have at least one class.
Android finally used this .class files to produce an executable Apk
Example:
public class Data{
int ID;
String Name;
public void First_Method()
{
}
}
Activity
An activity is the equivalent of a Frame/Window in GUI toolkits.
If we want to use an activity class, we must use extend Activity in your android project.
Example
public class Main_Activity extends Activity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
}
}
I have a stack of activities like A->B->C->D... Back function is enabled on all activities. Now on a specific action on activity D, I would like to move to activity B i.e. D&C gets finished now and activity B is resumed. How to achieve such transition ?
From Activity D, call Activity B with proper flags in the Intent. Intent.FLAG_ACTIVITY_CLEAR_TOP should do it.
Example code:
Intent intent = new Intent(this, B.class)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
If you want to follow proper and ideal flow , go for "onActivityResult" method. Suppose for your example when B goes to C, at that time it will start activity C using startActivityForResult and when C goes to D then again C will use statActivityForResult to go do D.
For your case,
public class B extends Activity
{
public static int RESULT_CODE=111;
public void onCreate(Bundle SavedInstance)
{
...
....
Intent intent = new Intent(B.this,C.class);
startActivityForResult(intent,REQUEST_CODE);
}
public void onActivityResult(int requestCode,int resultCode,Intent data)
super.onActivityResult(requestCode, resultCode, data);
if(requestcode == C.RESULT_OK)
{
//do you work when D is finished and comes back to B
}
}
public class C extends Activity
{
public static int RESULT_CODE=222;
public void onCreate(Bundle SavedInstance)
{
...
....
Intent intent = new Intent(C.this,D.class);
startActivityForResult(intent,REQUEST_CODE);
}
public void onActivityResult(int requestCode,int resultCode,Intent data)
super.onActivityResult(requestCode, resultCode, data);
if(requestcode == D.RESULT_OK)
{
setResult(RESULT_OK);
}
}
public class D extends Activity
{
public static int RESULT_CODE=333;
public void onCreate(Bundle SavedInstance)
{
...
....
}
//your back click function
public void onBackClick(View v)
{
setResult(RESULT_OK);
}
Just to clarify, use this API < 11:
Intent intent= new Intent(this, Login2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(Intent);
In API level 11 a new Intent Flag was added just for this: Intent.FLAG_ACTIVITY_CLEAR_TASK
Intent intent= new Intent(this, Login2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(Intent);
Try adding this code inside some action of D Activity
C close = new C();
close.finish();
D.this.finish();
And in activity tag of manifest file add this attribute
android:launchmode="singleTop" //Or singleTask
So that you can close both c and D activity and resume into B.
I have a problem with my code. I want to pass a String from the SecondActivity to FirstActvity. Note that the FirstActivity is not visible but its still open. when the SecondActivity is finish it passes a String to the FirstActivity.
My problem here is that when the SecondActivity ended and goes to FirstActivity, the whole application closes.
FirstActivity to SecondActivity:
Intent intent = new Intent(MainActivity.this, FileChooser.class);
startActivityForResult(intent, 0);
SecondActivity to FirstActivity:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("filePath", "/sdcard/path1");
setResult(0);
finish();
FirstActivity Result:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//TODO handle here.
Intent intent = getIntent();
this.filePath = intent.getExtras().getString("filePath");
}
What is wrong with the code?
When you set the result of your SecondActivity, you only set the result code. Instead of setResult(0) use setResult(0,intent)
Also, in your FirstActivity's onActivityResult get the extra from the data argument - this.filePath = data.getExtras().getString("filePath");
Try to use
data.getExtras().getString("filePath");
instead of
intent.getExtras().getString("filePath");`
Try with Bundle:
First Activity;
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), FIRSTACTIVITY.class);
Bundle bundle = new Bundle();
bundle.putString("filePath","/sdcard/path1");
intent.putExtras(bundle);
startActivity(intent);
}
Second Activity:
public void activity_value() {
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras !=null) {
value = extras.getString("filePath");
}
}
try this
example.It solves your problem.