How do I pass string from SecondActivity to MainActivity on Android Studio? - java

I have a public String stringPass in SecondActivity.java that I want to pass to MainActivity.java so that when I click a button, the string from the SecondActivity.java updates a TextView tv that is declared in MainActivity.java.
The bug I'm getting is that when I press the button, the string in the SecondActivity.java is not shown.
Instead, It goes from "Hello World!" to no text displayed.
FYI, i'm going to add strings to MainActivity.java from multiple activities, so I want it this particular way for my organization.
Thanks!
SecondActivity.java
public class SecondActivity extends AppCompatActivity{
public String stringPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stringPass = "this is from SecondActivity";
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = findViewById(R.id.tv);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(new SecondActivity().stringPass);
}
});
}
}
activity_main.xml
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Is there much content in the second activity? Is it an actual activity with much going on? If not replace it with a dialog box, when the ok button is clicked it can update the text box.

Related

I can't start an Activitiy by clicking a Button

i'm trying to start an Activitiy by clicking a Button. If the user clicks the PLAY button in the MenuActivity the GameActivity should be started. But it doesn't work.
public class MenuActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
}
public void startGameEngine(View view) {
Intent myintent = new Intent(this, GameActivity.class);
startActivity(myintent);
}
Here is the GameActivity class which should be started when the user click on the PLAY-Button.
public class GameActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Intent intent = getIntent();
}
Here is the menu.xml file which includes the button
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/menubackground_color"
tools:context="com.example.vincenzoauricchio.example.MenuActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="381dp"
android:layout_height="67dp"
android:layout_marginBottom="440dp"
android:layout_marginTop="88dp"
android:fontFamily="#font/vt323"
android:text="#string/logo2"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#android:color/black"
android:textSize="36sp"
android:textStyle="bold|italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.666"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/btnPlay"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_marginBottom="265dp"
android:layout_marginTop="87dp"
android:fontFamily="#font/vt323"
android:onClick="startGameEngine"
android:text="#string/button_play"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.0" />
Try implementing the on click listner :
public class MenuActivity extends AppCompatActivity implements View.OnClickListener
Try below code snippet :
Button btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(MainActivity.this);
#Override
public void onClick(View view)
{
if(view == btnPlay)
{
Intent intent = new Intent(MenuActivity.this, GameActivity.class);
startActivity(intent);
}
}
Add your GameActivity to manifest.
Try this.
public class MenuActivity extends AppCompatActivity implements View.OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Button btnPlay= (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnPlay:
Intent myintent = new Intent(MenuActivity.this, GameActivity.class);
startActivity(myintent);
break;
}
}
}
Check your Activity in your Manifestfile.xml or not
Add this to your AndroidManifest.xml
<activity android:name=".GameActivity"/>
The clickOn on the layouts.xml are not always a good practice but they work fine.
Instead of setting your on click listener in the xml, set it programatically in the activities on create.
btnPlay.setOnClickListener(new onClickListener{
void onCLick(){
startGameEngine();
}});
and remove View view from startGameEngine()'s input value.
and make sure you add the GameActivity in the manifest.xml

Android Studio: Boolean function crashes my app

Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.
Code:
MainActivity.java
package com.leuchtstein.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView) ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void triggerlight(View view) {
if (stat == false) {
text.setText("ON");
stat = true;
} else {
text.setText("OFF");
stat = false;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.leuchtstein.flashlight.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/desc_textview"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
app:layout_constraintHorizontal_bias="0.95"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="triggerlight"
android:text="Turn on/off"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.387" />
Well, thanks in advance.
Don't call
TextView text = (TextView) findViewById(R.id.textView) ;
in initialisation, rather call it in onCreate() method.
This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.
Put
text = (TextView) findViewById(R.id.textView);
in onCreate() and put
TextView text;
in initialisation instead.
Try this :
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :
TextView text = (TextView) findViewById(R.id.textView);
Change your code to look like this :
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.

How i can compare the value of an id with java

I have a simple xml with a question and two buttons. When one of buttons is pushed i will compare if the id of the pushed button is equal to "Blanco" or "Negro".
The XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/pregunta" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Blanco"
android:onClick="respuesta"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Negro"
android:onClick="respuesta"/>
</LinearLayout>
</LinearLayout>
This is de java code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void respuesta(){
//The doubt.
//Here the if/else to compare ID with the button text
}
}
Don't do it like that. Create an onClickListener for each Button, so you know exactly which one is being pressed. For example:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener{
public void onClick(View v) {
// call code here, knowing that button1 was pressed
}
});
button2.setOnClickListener(new View.OnClickListener{
public void onClick(View v) {
// call code here, knowing that button2 was pressed
}
});
}
}
implement onClickListener into your Activity.
public class MainActivity extends ActionBarActivity implements OnClickListener
Declare the Button variables inside your class
Button btblanco, btnegro;
Implement the clickListener event on onCreate
btblanco = (Button) findViewById(R.id.button1);
btnegro = (Button) findViewById(R.id.button2);
btblanco.setOnClickListener(this);
btnegro.setOnClickListener(this);
And put this inside onClickListener method.
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
Toast.makeText(getApplicationContext(), "Blanco", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Negro", Toast.LENGTH_SHORT).show();
break;
}}
if you are interested in just knowing which button was clicked, then add a onclicklistener to the button objects. Google for it a bit and the samples you find will show you how to use a switch case structure to d actions based on which button was clicked.

Edittext, on submit need to show on another window in android

In android,i want to get a string from user using EditText and on click of submit button the string need to be show on another page/pane.
here is my fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText android:id="#+id/msg"
android:hint="#string/entertheip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text"
/>
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Button1"
/>
<TextView android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/thetext"
android:visibility="invisible"
/>
</LinearLayout>
and corresponding java class is this
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button bu = (Button)findViewById(R.id.button1);
bu.setOnClickListener(new View.OnClickListener() {
private TextView tv = (TextView)findViewById(R.id.tv);
#Override
public void onClick(View v) {
// to view the ip in another page
try{
EditText et = (EditText)findViewById(R.id.msg);
String t = et.getText().toString();
tv.setText(t);
}catch(NullPointerException e){
e.printStackTrace();
}
}
});
}
}
But i am getting the Edit Text and Button only, the text is not showing in another page. Kindly help in this.
place this inside onClick
tv.setVisibility(View.VISIBLE);
You will have to use an Intent to go to another activity, like
Intent i=new Intent(MainActivity.this, someClass.class);
startActivity(i);
save the string in app preference and use the preference tag in that class and set the string to some textview you want there ...
try below way:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button bu = (Button)findViewById(R.id.button1);
TextView tv = (TextView)findViewById(R.id.tv);
EditText et = (EditText)findViewById(R.id.msg);
bu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// to view the ip in another page
try{
String t = et.getText().toString();
tv.setText(t);
}catch(NullPointerException e){
e.printStackTrace();
}
}
});
}
Remove this line from TextView tag of your XML File:-
android:visibility="invisible"
You can navigate between activities using Intent and also pass data with it
Using Intents to Create Flows
Simple way on your case is
On Button click
Intent i = new Intent(MainActivity.this, ActivityTwo.class);
i.putExtra("username", "foobar");
startActivity(i); // brings up the second activity
On Another Activity
// ActivityTwo.java (subactivity) can access any extras passed in
protected void onCreate(Bundle savedInstanceState) {
String username = getIntent().getStringExtra("username");
}
You have not added onClick to button: Fix that.
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Button1"
android:onClick="onBtnClick"
/>
And you need not override onClick if you are not implementing onClickListener in activity.
public void onBtnClick(View v) {
// to view the ip in another page
try{
EditText et = (EditText)findViewById(R.id.msg);
String t = et.getText().toString();
tv.setText(t);
tv.setVisibility(View.VISIBLE); //as you have kept visibility invisible in xml
}catch(NullPointerException e){
e.printStackTrace();
}
}
Hope it helps.

"Unfortunately, <App Name> has stopped." Common unexplained Error

I am having a problem when debugging apps that respond to user input. An ordinary app that just displays text works fine, but when I give a button an event handler I get a generic message "Unfortunately, 'App Name' has stopped.". I have tried many solutions, but to no avail. I am using IntelliJ IDEA 12.0.4 (Community Edition).
Sorry for asking a very common question but it seems the solution is different for everyone.
Edit - new working code
Source Code:
package com.example.Android_Test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static com.example.Android_Test.R.*;
public class MyActivity extends Activity {
EditText editText;
TextView textView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare all widget controls.
editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
textView = (TextView) findViewById(R.id.lblText);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText());
}
};
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtEdit" android:layout_gravity="left|center_vertical"
android:layout_alignParentLeft="true" android:layout_marginLeft="0dp" android:layout_alignParentTop="true"
android:layout_marginTop="0dp" android:layout_alignParentRight="true" android:hint="Type here change text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Text"
android:id="#+id/btnChange"
android:layout_alignLeft="#+id/txtEdit" android:layout_below="#+id/txtEdit"
android:layout_alignRight="#+id/txtEdit"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change this text"
android:id="#+id/lblText"
android:layout_alignLeft="#+id/txtEdit" android:layout_below="#+id/btnChange"
android:layout_alignRight="#+id/txtEdit" android:textSize="18dp"/>
</RelativeLayout>
Logcat is very long so I pasted it here: http://pastebin.com/2qaY8ZJj.
Everyone's Logcat is so much shorter i don't know why
Move this code
// Declare all widget controls.
EditText editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
TextView textView = (TextView) findViewById(R.id.lblText);
inside onCreate() and use R.id... .
Edit
I edited youre code
public class MyActivity extends Activity {
EditText editText;
TextView textView;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare all widget controls.
editText = (EditText) findViewById(R.id.txtEdit);
Button button = (Button) findViewById(R.id.btnChange);
textView = (TextView) findViewById(R.id.lblText);
button.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText().toString);
}
};
}

Categories