Switching Activitys - java

I am trying to switch activity's with the use of a button.
Skillz.java
Button b2 =(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myintent = new Intent();
String packageName="marco.skillz.app";
String className="marco.skillz.app.act2";
myintent.setClassName(packageName, className);
startActivity(myintent);
}
});
act2.java
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
}
When the app run in the emulator I get the following error:
The application "app name" (process marco.skillz.app) has stopped unexpectedly.
FIXED!! I feel so stupid i had android:name=".act1" when it should be android:name=".act2".
Thanks for all your input :P

Please check like this
public void onClick(View v) {
Intent myintent = new Intent(Skillz.this,act2.class);
startActivity(myintent);
}
Add act2 activity in the manifest file

Try this Skillz.java in oncreate
Button b2 =(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener()
{public void onClick
(View v) {
Intent i = new Intent(getApplicationContext(), act2.class);
startActivity(i);
}
});

Related

I have a problem when I try to use a variable from a getStringArrayListExtra()

When I use getStringArrayListExtra() to transport a variable from SecondActivity to the MainActivity, and when I use the variable, my app always crash. This is the code where there is a problem :
in MainActivity :
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}
}
in SecondActivity :
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
ArrayList tag = new ArrayList();
EditText edit;
Button button;
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
edit = (EditText) findViewById(R.id.edit);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
tag.add(name);
Toast.makeText(getApplicationContext(), tag.toString(), Toast.LENGTH_SHORT).show();
}
});
Button button2;
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
Button button3;
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
startActivity(retourgameActivity);
}
});
}
}
Thank you so much for your help !
EDIT:
This is the error log (logcat):
021-06-24 15:43:16.734 11451-11451/fr.apprentissage.version2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.apprentissage.version2, PID: 11451
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.apprentissage.version2/fr.apprentissage.version2.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at fr.apprentissage.version2.MainActivity.onCreate(MainActivity.java:158)
at android.app.Activity.performCreate(Activity.java:8086)
at android.app.Activity.performCreate(Activity.java:8074)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
You are starting MainActivity from SecondActivity without any extras.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retourgameActivity = new Intent(SecondActivity.this, MainActivity.class);
//add arraylist here in intent
retourgameActivity .putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
}
});
//in your second activity ,make sure you have extras in intent.
if(getIntent!=null && getIntent().getStringArrayListExtra("tag")!=null){
List<String> maSuperlist= getIntent().getStringArrayListExtra("tag");
System.out.println(maSuperlist);
//TextView DisplayList;
//DisplayList = (TextView) findViewById(R.id.DisplayListt);
//DisplayList.setText(maSuperlist.toString());
CharSequence[] testlist= maSuperlist.toArray(new CharSequence[maSuperlist.size()]);
//Toast.makeText(getApplicationContext(),testlist,Toast.LENGTH_SHORT).show();
}}
You are initiating an arraylist and before populating list you are sending it to your MainActivity.So you are passing null list to MainActivity. You should pass your list to other activity on button click.
Just do this inside your button3 listener:
Intent retourgameActivity = new Intent(MainActivity.this, SecondActivity.class);
retourgameActivity.putStringArrayListExtra("tag", tag);
startActivity(retourgameActivity);
Remove
retourgameActivity.putStringArrayListExtra("tag", tag);
from here
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putStringArrayListExtra("tag", tag);
Good Practices:
Always put null check before sending arraylist to other activity and also check null before using arraylist.size() or getting some indexes of arralist.

Move data by intent without startActivity

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

Starting different activities from MainActivity

I'm new here and I think I have made a mistake in Java but I have no idea how to correct it. Most of the people with similar issue had much more complicated projects and I couldn't resolve my issue by looking at their code.
I want to use different buttons (9 of them) to start different activities, but when I started with adding the second, only the activity 1 (LeftArmActivity) popped up. Whatever I changed in the XML to call the proper method for HeadActivity to launch, only the LeftActivity launches. I've got a hint from other topics that it may be caused by overwriting of the intent, but I have no idea how to fix this. I tried to use getActivity() but it just crashed. Could you please help me with this?
#UPDATE
Okay, I used the switch recommended below, but now the app won't start at all :/
public class MainActivity extends AppCompatActivity {
Context context = this;
Button LeftArmOpener = (Button) findViewById(R.id.LeftArmOpener);
Button HeadOpener = (Button) findViewById(R.id.HeadOpener);
Button RightArmOpener = (Button) findViewById(R.id.RightArmOpener);
Button CreditsOpener = (Button) findViewById(R.id.CreditsOpener);
Button TrunkOpener = (Button) findViewById(R.id.TrunkOpener);
Button NextOpener = (Button) findViewById(R.id.NextOpener);
Button RightLegOpener = (Button) findViewById(R.id.RightLegOpener);
Button ExitOpener = (Button) findViewById(R.id.ExitOpener);
Button LeftLegOpener = (Button) findViewById(R.id.LeftLegOpener);
protected View.OnClickListener mClick;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RightArmOpener: {
Intent i1 = new Intent(context, LeftArmActivity.class);
startActivity(i1);
break;
}
case R.id.HeadOpener: {
Intent i2 = new Intent(context, HeadActivity.class);
startActivity(i2);
break;
}
case R.id.LeftArmOpener: {
Intent i3 = new Intent(context, LeftArmActivity.class);
startActivity(i3);
break;
}
case R.id.CreditsOpener: {
Intent i4 = new Intent(context, CreditsActivity.class);
startActivity(i4);
break;
}
case R.id.TrunkOpener: {
Intent i5 = new Intent(context, TrunkActivity.class);
startActivity(i5);
break;
}
case R.id.NextOpener: {
Intent i6 = new Intent(context, NextActivity.class);
startActivity(i6);
break;
}
case R.id.RightLegOpener: {
Intent i7 = new Intent(context, RightLegActivity.class);
startActivity(i7);
break;
}
case R.id.ExitOpener: {
Intent i8 = new Intent(context, ExitActivity.class);
startActivity(i8);
break;
}
case R.id.LeftLegOpener: {
Intent i9 = new Intent(context, LeftLegActivity.class);
startActivity(i9);
break;
}
//create this for all 9 buttons
}
}
};
LeftArmOpener.setOnClickListener(mClick);
HeadOpener.setOnClickListener(mClick);
RightArmOpener.setOnClickListener(mClick);
CreditsOpener.setOnClickListener(mClick);
TrunkOpener.setOnClickListener(mClick);
NextOpener.setOnClickListener(mClick);
RightLegOpener.setOnClickListener(mClick);
ExitOpener.setOnClickListener(mClick);
LeftLegOpener.setOnClickListener(mClick);
}
}
Update your Code with this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openHead(View view){
startActivity(new Intent(MainActivity.this, LessonOne.class));
//startActivity(t);
}
public void openLeftArm(View view){
Intent i = new Intent(MainActivity.this, LeftArmActivity.class);
startActivity(i);
}
}
//the problem is you are calling startActivity() two time and Passing getActivity() from Actvity.
You said you have 9 buttons so i think u should use switch case in such scenarios see the following code:-
Here is how my Button looks in xml no android:onClick is used here
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
This part goes in Activity:-
Context context = this;
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn9 = (Button) findViewById(R.id.btn9);
btn1.setOnClickListener(mClick);
btn2.setOnClickListener(mClick);
btn9.setOnClickListener(mClick);
View.OnClickListener mClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1: {
Intent i1 = new Intent(context, First.class);
startActivity(i1);
break;
}
case R.id.btm2: {
Intent i2 = new Intent(context, Second.class);
startActivity(i2);
break;
}
//create this for all 9 buttons
}
}
};
On the top declare your button; (before the oncreate method)
Button yourbuttonname;
Then on the oncreate method:
declare the view of the button:
yourbuttonname = (Button) findViewById(R.id.buttonNameInYourXML);
yourbuttonname.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActualActivity.this, ActivityYouWantToGo.class);
intent.putExtra("tag",valueassociatedtotag); // if you want to pass some data
startActivity(intent)
}
});

How to call the MainActivity from another Activity

I have my MainActivity, and I create an Intent to a SecondActivity, when a button is pressed,
I want to return to activity. But when I create the intent and pass (this, MainActivity.class) through the constructor, I get an error: The intent constructor is undefined. Can someone help me?
public void goBackToMainActivity(View view) {
//Button for retrieving the user's current location:
final Button backButton = (Button) findViewById(R.id.back_button);
//Listens for button presses and releases:
backButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//When the button is pressed:
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//Change image for touch indication:
backButton.setBackgroundResource(R.drawable.back_button);
//When the button is released:
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//Change image back to default:
backButton.setBackgroundResource(R.drawable.back_button_selected);
goBackToMainActivity();
}
return false;
}
});
}
public void goBackToMainActivity() {
finish();
Intent startIntent = new Intent(this, MainActivity.class);
startActivity(startIntent);
}
I guess you are creating the intent inside an OnClickListener, thus you need to use the code below:
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
The reason is that if you do not specify SecondActivity.this, you are actually passing the OnClickListener into the intent constructor.
Change your goback method:
public void goBackToMainActivity() {
Intent startIntent = new Intent(CurrentActivityName.this, MainActivity.class);
startActivity(startIntent);
finish();
}
First clear all the existing activities by writing code:
startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
Then call the intent to the MainActivity
Intent i=new Intent(CurrentActivity.this, MainActivity.class);
startActivity(i);
Try calling finish() on button click in second activity to return to the main activity.
public void onClick(View v) {
finish();
}

Android: Set Text View's text from another activity Not working

I have 2 activities and 2 classes.
In my Main class, when i click submit button it will start another activity. here is the code.
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, NewActivity.class));
newActivity.setViewValues(fNameET.getText().toString(), lNameET.getText().toString(), mInitialET.getText().toString(), "Female", "birthday", addressET.getText().toString(), cNumberET.getText().toString());
}
The newActivity is an object of the other activity and the setViewValues is the method of it.
This doesn't work, this is how i do it in java gui. Maybe something is missing.
Could anyone help me with this?
You should pass the data like this.
MainActivity.java
Intent intent = new Intent(MainActivity.this, NewActivity.class));
intent.putExtra("firstName",fvalue);
intent.putExtra("lastname",lname);
......
startActivity(intent);
NewActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutname);
Intent intent = getIntent();
String firstName = intent.getStringExtra("firstName");
String lastName = intent.getStringExtra("lastname");
}

Categories

Resources