I am a noob at this, so going to keep it short.
This is a practice app which sends data from first activity to second activity as a message and then the first activity receives data from the second activity as a message. The tutorial I'm following instructed me to use the StartActivityForResult() function to extract data from a second activity to the first activity. I have two questions:
What is wrong with this code:
I. The MainActivity.java file
package com.example.android.twoactivitiesredo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
//LOG_TAG contains the name of the class package, encapsulated for ease
public static final String EXTRA_MESSAGE =
"com.example.android.twoactivities.extra.MESSAGE";
//This will be used as the unique key to send data to the second Activity
public static final int TEXT_REQUEST = 1;
//This is used to define the key for a particular type of response that
you're interested in.
private EditText mMessageEditText;
//This EditText is used to send the message to the second activity
private TextView mReplyHeadTextView;
private TextView mReplyTextView;
//These private variables hold the reply header and the reply TextViews
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessageEditText = (EditText) findViewById(R.id.editText_main);
mReplyHeadTextView = (TextView) findViewById(R.id.textHeaderReply);
mReplyTextView = (TextView) findViewById(R.id.textMessageReply);
}
public void launchSecondActivity(View view) {
Log.d(LOG_TAG, "Button Clicked!");
Intent intent = new Intent(this, SecondActivity.class);
String message = mMessageEditText.getText().toString();
//Gets the data from EditText, converts it to String, and stores it in message
intent.putExtra(EXTRA_MESSAGE,message);
startActivityForResult(intent, TEXT_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == TEXT_REQUEST){
if(resultCode == RESULT_OK){
String reply = data.getStringExtra(SecondActivity.EXTRA_REPLY);
mReplyHeadTextView.setVisibility(View.VISIBLE);
mReplyTextView.setText(reply);
mReplyTextView.setVisibility(View.VISIBLE);
}
}
}
}
II. The SecondActivity.java file
package com.example.android.twoactivitiesredo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity{
public static final String EXTRA_REPLY =
"com.example.android.twoactivities.extra.REPLY";
//This tag will be used as a key to send reply to first activity
private EditText mReply;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
//Gets the intent that activated this activity
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//This extracts the extra text sent along with this key String, thus
receiving the text
TextView textView = (TextView) findViewById(R.id.text_message);
textView.setText(message);
mReply = (EditText) findViewById(R.id.replyEditText);
//Do not reuse the intent from the first activity, create a new one
Intent replyIntent = new Intent();
setResult(RESULT_OK,replyIntent);
//RESULT_OK has the value -1 and is used as a Result code in the Activity
class
//to check that the data is send without a complication
finish();
}
public void returnReply(View view) {
}
}
III. The activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_main"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="#string/sendButton"
android:onClick="launchSecondActivity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText_main"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toStartOf="#id/button_main"
android:layout_toLeftOf="#+id/button_main"
android:hint="Enter Your Message Here"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textHeaderReply"
android:text="#string/textHeaderReply"
android:visibility="invisible"/>
<!--The visibility mode is used to select how the attribute will be before data is passed to it.-->
<!--Invisible means that the attribute will be invisible before data is passed to it, hence not confusing the user-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textMessageReply"
android:layout_below="#+id/textHeaderReply"
android:visibility="invisible"/>
IV. The activity_second.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_header"
android:layout_marginBottom="20dp"
android:text="#string/text_header"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textStyle="bold"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_main"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="#string/sendButton"
android:onClick="launchSecondActivity"/>
<TextView
android:id="#+id/text_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/text_header"
android:layout_margin="10dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/replyEditText"
android:onClick="returnReply"
android:layout_toLeftOf="#+id/button_main"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:hint="#string/replyText"
/>
</RelativeLayout>
V. The AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.twoactivitiesredo">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/secondActivity"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.android.twoactivitiesredo.MainActivity"/>
</activity>
</application>
</manifest>
I am sorry if the code is taking a lot of space, but I really needed help in clarifying my doubts and problems here, about why this code isn't working.
Thanks in advance to all the answers.
Replace your secondActivity.java with this:
package com.example.android.twoactivitiesredo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity{
public static final String EXTRA_REPLY =
"com.example.android.twoactivities.extra.REPLY";
//This tag will be used as a key to send reply to first activity
private EditText mReply;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = (TextView) findViewById(R.id.text_message);
textView.setText(message);
mReply = (EditText) findViewById(R.id.replyEditText);
}
public void returnReply(View view) {
Intent replyIntent = new Intent();
String replyMessage = mReply.getText().toString();
replyIntent.putExtra(EXTRA_REPLY, replyMessage);
setResult(RESULT_OK,replyIntent);
finish();
}
}
In activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_header"
android:layout_marginBottom="20dp"
android:text="#string/text_header"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textStyle="bold"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_main"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="Reply Button"
android:onClick="returnReply"
/>
<TextView
android:id="#+id/text_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/text_header"
android:layout_margin="10dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/replyEditText"
android:layout_toLeftOf="#+id/button_main"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:hint="#string/replyText"
/>
</RelativeLayout>
Related
I'm practicing Android Studio and I'm stuck on this part. The little app I built has two screens, the first has a welcome message and a button that when clicked will send the user to the second screen (the second activity). This second screen has four buttons, each of which is marked with a value (1 to 4). When the buttons are pressed their values are added to an ArrayList of integer values, those values are then sent back to the main activity and if they match the right order and size, the message on the main screen changes. I managed to get that working, except for matching the right numbers in order part. My issue now is that my app skips the main activity and goes straight to the second activity when launched. And when the array list is sent back to the main activity, and I go back to enter a new combination in the second activity and go back to the main activity, nothing changes anymore. How can I fix the activity skipping and also be able to cycle back and forth between the two activity and have them continously update depending on what happens on activity two?
Below is the MainActivity class code
package com.example.securityapp;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Integer> passcode = new ArrayList<Integer>(4);
TextView mainMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
passcode.add(1);
mainMessage = findViewById(R.id.main_message);
final ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == RESULT_OK) {
Intent data = result.getData();
Bundle extras = data.getExtras();
if(extras.getIntegerArrayList("keys").size() == 4) {
mainMessage.setText("Welcome to the App! The App is UNLOCKED!");
}
else {
mainMessage.setText("Welcome to the App! The App is LOCKED!");
}
}
}
}
);
Intent intent = new Intent(MainActivity.this , AccessControlActivity.class);
activityResultLauncher.launch(intent);
}
/** Called when user taps the Unlock button */
public void unlockApp(View view) {
Intent intent = new Intent(this, AccessControlActivity.class);
intent.putExtra("key", passcode);
startActivity(intent);
}
}
XML for MainActivity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity" >
<Button
android:id="#+id/btn_unlock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="308dp"
android:onClick="unlockApp"
android:text="#string/btn_unlock"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/main_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/main_message"
android:textAlignment="center"
android:textSize="16sp"
app:layout_constraintBottom_toTopOf="#+id/btn_unlock"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.949" />
</androidx.constraintlayout.widget.ConstraintLayout>
Second activity (AccessControlActivity)
package com.example.securityapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class AccessControlActivity extends AppCompatActivity {
private static final int[] numbers = {R.id.key_1, R.id.key_2, R.id.key_3, R.id.key_4};
private static int[] passcode = new int[4];
private Button[] button = new Button[numbers.length];
ArrayList<Integer> numbersList = new ArrayList<Integer>();
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_access_control);
TextView textView = findViewById(R.id.textView2);
submit = findViewById(R.id.btn_submit);
for(int i = 0; i < numbers.length; i++) {
button[i] = (Button) findViewById(numbers[i]);
button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.key_1:
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
numbersList.add(1);
break;
case R.id.key_2:
Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
numbersList.add(2);
break;
case R.id.key_3:
Toast.makeText(getApplicationContext(), "3", Toast.LENGTH_SHORT).show();
numbersList.add(3);
break;
case R.id.key_4:
Toast.makeText(getApplicationContext(), "4", Toast.LENGTH_SHORT).show();
numbersList.add(4);
break;
}
textView.setText(String.valueOf(numbersList));
}
});
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent keycode = new Intent(AccessControlActivity.this, MainActivity.class);
keycode.putExtra("keys", numbersList);
setResult(RESULT_OK, keycode);
finish();
}
});
}
}
XML for AccessControlActivity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".AccessControlActivity">
<Button
android:id="#+id/key_3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="#string/key_3"
app:layout_constraintBaseline_toBaselineOf="#+id/key_2"
app:layout_constraintEnd_toStartOf="#+id/key_4"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/key_2" />
<Button
android:id="#+id/key_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="312dp"
android:text="#string/key_1"
app:layout_constraintEnd_toStartOf="#+id/key_2"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="onSubmit"
android:text="#string/btn_submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/key_3"
app:layout_constraintVertical_bias="0.042" />
<Button
android:id="#+id/key_4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:text="#string/key_4"
app:layout_constraintBaseline_toBaselineOf="#+id/key_3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/key_3" />
<Button
android:id="#+id/key_2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="#string/key_2"
app:layout_constraintBaseline_toBaselineOf="#+id/key_1"
app:layout_constraintEnd_toStartOf="#+id/key_3"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/key_1" />
<TextView
android:id="#+id/key_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:text="#string/key_message"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/key_3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.922" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pass_key"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="526dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
The activity from which your app starts is declared in the android manifest. For example, in this code snippet, the launcher activity would be my splash activity.
<activity
android:name=".feature.planes.PlanDetailActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.Matatapp" />
<activity
android:name=".feature.splash.SplashActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.Matatapp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
But this doesn't appear to be your issue. You are currently launching an intent from your onCreate method, so even though you have MainActivity set as launcher, when your application launches MainActivity and goes through onCreate, it launches your AccessActivity so quickly you don't even notice. To test if MainActivity is being launched in first place, just run your app, and natively go back. If MainActivity is showed, then you know your issue is that you have to launch your intent from another method called when the user triggers something.
I would eagerly recommend you to look at ativity lifecycle.
Goal:
when you press the button a new line with new text should be displayed in textview.
Problem:
Based on source code it is not working in order to fulfill the goal.
What part am I missing?
Info:
*I'm new in android
*I'm using API 23
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jfdimarzio.netvork">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.jfdimarzio.netvork.MainActivity">
<Button
android:id="#+id/btn_send"
android:layout_width="349dp"
android:layout_height="54dp"
android:layout_alignEnd="#+id/edittxt_input"
android:layout_alignParentBottom="true"
android:layout_marginBottom="12dp"
android:onClick="inputData"
android:text="Send"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="441dp" />
<EditText
android:id="#+id/edittxt_input"
android:layout_width="348dp"
android:layout_height="39dp"
android:layout_above="#+id/btn_send"
android:layout_alignStart="#+id/txtview_display"
android:layout_marginBottom="19dp"
android:ems="10"
android:inputType="textPersonName"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="392dp" />
<TextView
android:id="#+id/txtview_display"
android:layout_width="348dp"
android:layout_height="355dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="16dp" />
</RelativeLayout>
package com.jfdimarzio.netvork;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import static com.jfdimarzio.netvork.R.id.txtview_display;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void inputData(View view)
{
EditText editText = (EditText) findViewById(R.id.edittxt_input);
String message = editText.getText().toString();
TextView myTextView = (TextView) findViewById(R.id.txtview_display);
myTextView.setText(message + "\n");
}
}
I think you want to display the content of editText in a new line along with the previous text. If so, you may change the function inputData() like this:
public void inputData(View view) {
EditText editText = (EditText) findViewById(R.id.edittxt_input);
String message = editText.getText().toString();
TextView myTextView = (TextView) findViewById(R.id.txtview_display);
String oldText = myTextView.getText();
myTextView.setText(oldText + "\n" + message);
}
Actually when you want setText right now from the activity , you have to refresh Activity and after that is not work becouse the string not saved by SharedPreferences. or you can create a method like this and add SharedPreferences
public class MainActivity extends AppCompatActivity {
private String message;
private TextView myTextView;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (TextView) findViewById(R.id.txtview_display);
editText = (EditText) findViewById(R.id.edittxt_input);
}
public void inputData(View view) {
message = editText.getText().toString().trim();
if (!message .isEmpty()){
MethodName(message);
}
}
public void MethodName(String message){
myTextView.setText(message + "\n");
}
}
I've created two activities. The first accepts the name of a student through an edit text and has a submit button. When the submit button is pressed, the next activity opens which has an edit text (to accept the marks) along with a back button.
I wish to return the marks entered to the first activity, when the back button of second activity is pressed so that the marks are displayed in the first edit text.
Kindly provide me with the code for the two activities.
You can use activity for result . An example is given here
Hello Akanksha Gahalout, if i understand your question, you want to pass Data between two activities and vice versa , if so, you should use Intent and use PutExtrat() method to pass data from one Activity to another,then you can recuperate data from the second Activity with using Bundle and getExtras() method.
Here's an example :
FirstActivity.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<EditText
android:id="#+id/EditTextFirstActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/StudentName"
android:ellipsize="start"
android:gravity="center_horizontal"
android:labelFor="#+id/EditText1" />
<Button
android:id="#+id/buttonFirstActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/OK" />
<TextView
android:id="#+id/TextViewFirstActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000000"
android:ellipsize="start"
android:gravity="center_horizontal"
android:textSize="20sp" />
</LinearLayout>
FirstActivity.java :
package dz.A;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class FirstActivity extends Activity implements OnClickListener {
private TextView textView;
private EditText editTextFirstActivity;
private Button buttonFirstActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
editTextFirstActivity = (EditText) findViewById(R.id.EditTextFirstActivity);
textView = (TextView) findViewById(R.id.TextViewFirstActivity);
buttonFirstActivity = (Button) findViewById(R.id.buttonFirstActivity);
buttonFirstActivity.setOnClickListener(this);
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
String marks = (String) b.get("STUDENT_MARKS");
textView.setText(marks);
}
}
#Override
public void onClick(View v) {
if (v == buttonFirstActivity) {
Log.i("OK", "onClickOK");
Intent i = new Intent(this, SecondActivity.class);
Log.i("OK", "IntentOK");
Log.i("OK", "startActivity(i)OK");
String studentName = editTextFirstActivity.getText().toString()
.trim();
Log.i("OK", "studentNameOK : " + studentName);
i.putExtra("STUDENT_NAME", "Student Name : " + studentName);
Log.i("OK", "i.putExtraOK");
startActivity(i);
finish();
Log.i("OK", "finish()OK");
}
}
}
SecondActivity.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/EditTextSecondActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="start"
android:gravity="center_horizontal"
android:hint="#string/Marks"
android:inputType="number"
android:labelFor="#+id/EditText1" />
<Button
android:id="#+id/buttonSecondActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sendMarks" />
<TextView
android:id="#+id/TextViewSecondActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
SecondActivity.java :
package dz.A;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SecondActivity extends Activity implements OnClickListener {
private TextView textViewSecondActivity;
private EditText editTextSecondActivity;
private Button buttonSecondActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
textViewSecondActivity = (TextView) findViewById(R.id.TextViewSecondActivity);
editTextSecondActivity = (EditText) findViewById(R.id.EditTextSecondActivity);
buttonSecondActivity = (Button) findViewById(R.id.buttonSecondActivity);
buttonSecondActivity.setOnClickListener(this);
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
String studentName = (String) b.get("STUDENT_NAME");
textViewSecondActivity.setText(studentName);
}
}
#Override
public void onClick(View v) {
if (v == buttonSecondActivity) {
String marks = editTextSecondActivity.getText().toString().trim();
Intent i = new Intent(this, FirstActivity.class);
i.putExtra("STUDENT_MARKS", "Student Marks : " + marks);
startActivity(i);
finish();
}
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dz.A"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="dz.A.FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="dz.A.SecondActivity"/>
</application>
</manifest>
String.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Project</string>
<string name="hello_world">Hello world!</string>
<string name="OK">OK</string>
<string name="Marks">Marks</string>
<string name="sendMarks">sendMarks</string>
<string name="StudentName">StudentName</string>
</resources>
I hope that helps you.
This is my main class that will be forwarding the username to my GoalActivity class. I cannot figure out where the issue is. It keeps crashing for an unknown reason to me. I've followed various tutorials, and I cannot figure out the issue. It seems that I retrieve the username correctly, and then convert it into a string. Then create an Intent and pass the username value with a key.
MainActivity.java
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.agray.carpediem.LoginDataBaseAdapter;
import com.example.agray.carpediem.R;
import com.example.agray.carpediem.SignUPActivity;
public class MainActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
//create reference to the buttons used
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Signup button w/onclick listener
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
//start the activity w/intent
startActivity(intentSignUP);
}
});
}
// Methods to handleClick Event of Sign In Button
public void signIn(View View)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
//get the References of views
final EditText editTextUserName=
(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=
(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
//Signin Button w/ onClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//store username and password as strings
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
//fetch the Password from the DB for respective username
String storedPassword=loginDataBaseAdapter.getSingleEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(MainActivity.this, "Congrats: Login is Successful " + userName,
Toast.LENGTH_LONG).show();
dialog.dismiss();
// final EditText editTextUserName=
// (EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
// String userName=editTextUserName.getText().toString();
//create intent that will start the goals activity w/some data
Intent intro = new Intent(getApplicationContext(), GoalActivity.class);
//put the username into intent
intro.putExtra("USER_NAME", userName);
startActivity(intro);
}
else
{
Toast.makeText(MainActivity.this, "Access Denied: User Name or Password " +
"does not match",
Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Here is my GoalActivity class that receives info from the MainActivity class.
GoalActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class GoalActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.goals_page);
//get the username from the intent
String enteredUserName = getIntent().getStringExtra("USER_NAME");
final TextView tv = (TextView)findViewById(R.id.user_name_forwarded);
tv.setText(enteredUserName);
}
}
login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editTextUserNameToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editTextPasswordToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="#+id/buttonSignIn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign In" />
</LinearLayout>
goals_page.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome_goals"
android:textSize="50sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/user_name_forwarded"
android:text="#string/emptyString"
android:layout_weight="0.09"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.agray.carpediem" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="CarpeD"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.agray.carpediem.MainActivity"
android:label="CarpeD" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignUPActivity"/>
<activity android:name=".GoalActivity"/>
</application>
</manifest>
Try this, e.g. in ActivityA:
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra("USER_NAME", userNameString);
startActivity(i);
In ActivityB:
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
String USERNAME = extras.getString("USER_NAME");
Solved. It was a very careless mistake. I had updated all the other activities in the Manifest but the activity tag for the GoalActivity.java. Thanks guys for all your help!
I am trying to use two views in one application to come up with the user's planetary weight. After rewriting the java several times, I finally have it working... mostly, but on the public class Planets it tells me "The public type planets must be defined in its own file." I went into the manifest and made an activity for it, but that didn't help anything. Planets is already the name of one of my xml files. How do I make the public type into its own file?
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/askwtTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="19dp"
android:text="#string/askwt" />
<EditText
android:id="#+id/inputwtEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/askwtTextView"
android:layout_below="#+id/askwtTextView"
android:layout_marginTop="26dp"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="#+id/enterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/inputwtEditText"
android:layout_below="#+id/inputwtEditText"
android:layout_marginTop="38dp"
android:onClick="buttonclick"
android:text="#string/enter" />
</RelativeLayout>
Planets.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/planetTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/planet" />
<TextView
android:id="#+id/textViewform2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/mercuryRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/mercury" />
<RadioButton
android:id="#+id/venusRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/venus" />
<RadioButton
android:id="#+id/earthRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/earth" />
<RadioButton
android:id="#+id/marsRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/mars" />
<RadioButton
android:id="#+id/jupiterRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/jupiter" />
<RadioButton
android:id="#+id/saturnRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/saturn" />
<RadioButton
android:id="#+id/uranusRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/uranus" />
<RadioButton
android:id="#+id/neptuneRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/neptune" />
<RadioButton
android:id="#+id/plutoRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pluto" />
</RadioGroup>
<Button
android:id="#+id/selectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonclick2"
android:text="#string/select" />
<TextView
android:id="#+id/textViewform2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout
JAVA:
package com.deitel.planetaryweight;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.*;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends Activity {
/* You should get used to declaring everything with the correct visibility. Good practice is to make everything private and use public mutator methods */
//Global variable
private double weight;
private Button enter; // creates a button
// Views
private EditText wtEntry;
private TextView txtForm2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Start with first screen
setContentView(R.layout.activity_main);
enter = (Button) findViewById(R.id.enterButton);
//creates an editext and assigns the resource id of the xml edittext.
wtEntry = (EditText)findViewById(R.id.inputwtEditText);
txtForm2 = (TextView)findViewById(R.id.textViewform2);
}
// Button clicks shouldn't do anything but perform clicky actions. Leave field initialization, view creation, etc to the Activity.
//buttonclick for form 1
public void buttonclick(View view){
//Receives the input from the edittext, converts it to a double (number).
weight = Double.parseDouble(wtEntry.getText().toString());
TextView t2 = null;
//change the value of the textview on screen 2 to the calculation value
t2.setText(Double.toString(weight));
// If you want a new layout, it's best to start a new activity.
// It looks like you want to get information back, so use startActivityForResult().
// setContentView(R.layout.planets);
Intent dataIntent = new Intent(this, Planets.class);
dataIntent.putExtra("com.deitel.identifier.DATA_WEIGHT", weight);
startActivityForResult(dataIntent, Activity.RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that the resultCode is the same as we started the activity with
if(resultCode == Activity.RESULT_OK){
// get the double from the Intent, using the same string name (package prefixed)
// or a default value if it didn't get set.
double resultWeight = data.getDoubleExtra("com.deitel.identifier.RESULT_WEIGHT", 0.0);
// Now do something with resultWeight
}
}
}
// PlanetChooser.class
public class Planets extends Activity {
// constants, usually denoted by uppercase and declared static and final
public static final double MERCURYFORCE = 0.38;
public static final double VENUSFORCE = 0.91;
public static final double EARTHFORCE = 1.00;
public static final double MARSFORCE = 0.38;
public static final double JUPITERFORCE = 2.34;
public static final double SATURNFORCE = 1.06;
public static final double URANUSFORCE = 0.92;
public static final double NEPTUNEFORCE = 1.19;
public static final double PLUTOFORCE = 0.06;
private RadioButton mercury, venus, earth, mars, jupiter, saturn, uranus, neptune, pluto;
// No need to use the Double object as opposed to the primitive unless you have good reason
private double mercurypf, venuspf, earthpf, marspf, jupiterpf, saturnpf, uranuspf, neptunepf, plutopf, weight;
// One variable will suffice, it seems.
private double resultForce;
public void onCreate(Bundle s){
super.onCreate(s);
setContentView(R.layout.planets);
mercury = (RadioButton) findViewById(R.id.mercuryRadio);
venus = (RadioButton) findViewById(R.id.venusRadio);
earth = (RadioButton) findViewById(R.id.earthRadio);
mars = (RadioButton) findViewById(R.id.marsRadio);
jupiter = (RadioButton) findViewById(R.id.jupiterRadio);
saturn = (RadioButton) findViewById(R.id.saturnRadio);
uranus = (RadioButton) findViewById(R.id.uranusRadio);
neptune = (RadioButton) findViewById(R.id.neptuneRadio);
pluto = (RadioButton) findViewById(R.id.plutoRadio);
}
public void buttonclick2(View view){
/*
It looks to me here you're looking to see which box is checked, and set a value based on
that planet. Since instance variables (in this case mercurypf, jupiterpf, etc) are initialized
to the default value (0), there's no need to set them manually.
*/
// Code used to determine which planet RadioButton is checked:
if(mercury.isChecked()) {
resultForce = MERCURYFORCE * weight;
}
if(venus.isChecked()){
resultForce = VENUSFORCE * weight;
}
if(earth.isChecked()){
resultForce = EARTHFORCE * weight;
}
if(mars.isChecked()){
resultForce = MARSFORCE * weight;
}
if(jupiter.isChecked()){
resultForce =JUPITERFORCE * weight;
}
if(saturn.isChecked()){
resultForce = SATURNFORCE * weight;
}
if(uranus.isChecked()){
resultForce = URANUSFORCE * weight;
}
if(neptune.isChecked()){
resultForce = NEPTUNEFORCE * weight;
}
if(pluto.isChecked()){
resultForce = PLUTOFORCE * weight;
}
// Create a new data Intent to pass back to the calling activity, set the result code,
// and manually finish() this activity.
Intent dataIntent = new Intent(this, null);
dataIntent.getDoubleExtra("com.deitel.identifier.RESULT_DATA", resultForce);
setResult(Activity.RESULT_OK, dataIntent);
finish();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.deitel.planetaryweight"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="Planets" android:label="#string/title_planets"></activity>
</application>
</manifest>
Your Java file is named MainActivity.java (the name of the public class it defines). Remove the Planets class from it, and put that class into a Planets.java file. That's pretty much just how Java wants it to be.