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)
}
});
Related
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.
So here's my code:
public class MainActivity extends AppCompatActivity {
/* access modifiers changed from: protected */
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.button: // Text
intent = new Intent(this,"Faiz Ahmed \nLove music forever\nTCSS 450");
break;
case R.id.button2: // Image
intent = new Intent(this, ImageActivity.class);
break;
case R.id.button3: // Web
intent = new Intent("android.intent.action.VIEW");
intent.setData(Uri.parse("http://developer.android.com"));
break;
case R.id.button4: // Toast
Toast.makeText(this, "Here's to a new quarter!", Toast.LENGTH_SHORT)
.show();
break;
case R.id.button5: // Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("I am a dialog").setTitle("Some Title").create().show();
}
intent = null;
if (intent != null) {
startActivity(intent);
}
}
}
All the import's are there I just for some reason none of the buttons are working. The first 2 (Text & Image) I know I need a lot more code, but the last 3 should work & they're not for some reason. Any know what I'm doing wrong & how to fix it?
Nothing of the buttons will work because in the switch-case statement you initialize the intent according to which button was pressed.
After that you set intent to null and lastly you start the activity if the intent is not null, but it always is (since you set it before to null).
Short story delete intent = null; statement.
// intent = null; delete this line
if (intent != null) {
startActivity(intent);
}
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();
}
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);
}
});
In my application im trying to switch the visibility of two transparent buttons (i know this is rather hackish) within a RealViewSwitcher. I am changing the visibility based upon the current page of the RealViewSwitcher. I can get the first button to work, however the second never becomes active. Here is my code:
///////////////
if(realViewSwitcher.getCurrentScreen() == 0)
{
final Button btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.test.com"));
startActivity(intent);
btn1.setVisibility(View.GONE);
}
});
}
else if(realViewSwitcher.getCurrentScreen() == 2)
{
final Button btn2 = (Button)findViewById(R.id.btn2);
btn2.setVisibility(0);
btn2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = { "info#email.com" };
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.setType("message/rfc882");
Intent.createChooser(intent, "Choose Email Client");
}
});
}
///////////////
//end
/////////////////////
And here is the xml
<Button
android:id="#+id/btn1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#null"/>
<Button
android:id="#+id/btn2"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#null"
android:visibility="gone"/>
Your code just needs a little cleaning.
First of all, your buttons should be declared as fields. As it is, they are simply instance variables of the if statement.
The click listeners should be declared outside the if statement, for the same reason. Declare them in onCreate() or wherever suits your fancy.
Set up a switch for the getCurrentWindow(). It's easier to work with than an if... else if... else if....
Might I suggest:
final Button btn1 = (Button) findViewById(R.id.btn1);
final Button btn2 = (Button )findViewById(R.id.btn2);
//Inside onCreate() or similar
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.test.com"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Required to start a new activity
startActivity(intent);
btn1.setVisibility(View.GONE);
}
});
//In the same place
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = { "info#email.com" };
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.setType("message/rfc882");
Intent.createChooser(intent, "Choose Email");
btn2.setVisibility(View.VISIBLE);
}
});
//Later, in your other functional code
switch (realViewSwitcher.getCurrentScreen()) {
case 0:
//do your stuff
break;
case 2:
//other stuff
break;
default: //If you need it
throw new Exception("Oops...");
}