I have a simple app that generates notifications on button Click. I also have an editText so that the content Text is typed by the user. I have two buttons that generates two different notifications. My requirement is that on every button click there should be only one notification generated and the rest should be in the notification stack. I have tried using notification setGroup property but the method doesn't seem to work. I have attached my code below for further reference.
Main Activity(Java file):-
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final String GROUP_NOTIFICATIONS="group_notifications";
NotificationCompat.Builder notification;
NotificationCompat.Builder notification1;
PendingIntent pIntent;
NotificationManager manager,manager1;
Intent resultIntent;
Button button,button1;
EditText editText;
int a=0,b=100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= (EditText) findViewById(R.id.edittext);
button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startNotification();
}
});
button1= (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Notifications();
}
});
}
public void buttonClick(View view)
{
startNotification();
}
public void startNotification()
{
// Intent intent=new Intent(MainActivity.this,MyService.class);
// intent.putExtra("id",Integer.toString(a));
// startService(intent);
// PendingIntent pendingIntent=PendingIntent.getService(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
String str=editText.getText().toString();
notification=new NotificationCompat.Builder(this);
notification.setContentTitle("ABC");
notification.setContentText(str);
notification.setTicker("New Message Arrived");
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setGroup(GROUP_NOTIFICATIONS);
notification.setGroupSummary(true);
int num=0;
// notification.setNumber(++num);
Uri uri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.setSound(uri);
manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(a,notification.build());
a++;
}
public void Notifications()
{
String str=editText.getText().toString();
notification1=new NotificationCompat.Builder(MainActivity.this);
notification1.setContentTitle("ABC");
notification1.setContentText(str);
notification1.setTicker("New Message Arrived");
notification1.setSmallIcon(R.mipmap.ic_launcher);
notification1.setGroup(GROUP_NOTIFICATIONS);
notification1.setGroupSummary(true);
int num=0;
// notification1.setNumber(++num);
Uri uri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification1.setSound(uri);
manager1= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager1.notify(a,notification1.build());
a++;
}
}
activity_main.xml(XML file)
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pratik.stacked.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edittext"
android:textColor="#color/colorPrimary"
android:textSize="20sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Stacked Notification"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Stacked notifiction 1"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignLeft="#+id/button"
android:layout_alignStart="#+id/button"
/>
</RelativeLayout>
AndroidManifest.xml(Manifest file)
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
This is all about setting properly flags.
FLAG_GROUP_SUMMARY
The problem is that you are incrementing (a++) the notification ID:
manager1.notify(a,notification1.build());
a++;
If you want to update an existing notification you should call notify with the notification ID that you want to update. You can refer to the documentation
If you are on Android >= 4.1 you can use expanded layouts. Take into account that in this case you may want to ensure compatibility following these guidelines.
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.
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>
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.
I am developing an app that requires the user to press a button and it goes to another activity. The problem is that I cannot continue from there. I want to be able to simulate a button press and go back to the previous activity it was on. Here is my code.
package com.example.guy.smsclassproject;
import android.os.Looper;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by ksl130230 on 11/5/2015.
*/
public class DraftsActivityTest extends ActivityInstrumentationTestCase2<DraftsActivity> {
private DraftsActivity tester;
private EditText searchText;
private Button searchButton;
private DraftsDatabase draftsDatabase;
private MessageObject messageObject1;
private MessageObject messageObject2;
private MessageObject messageObject3;
Button[] draftButtons;
ArrayList<MessageObject> messagesToBeDisplayed;
public DraftsActivityTest() {
super(DraftsActivity.class);
}
#Override
#UiThreadTest
public void setUp() throws Exception {
super.setUp();
if (Looper.myLooper() == null)
{
Looper.prepare();
}
draftsDatabase = new DraftsDatabase();
draftsDatabase.clearData();
messageObject1 = new MessageObject("hi", "5554",null, true);
messageObject2 = new MessageObject("hi hi", "5555554",null, true);
messageObject3 = new MessageObject("sup", "5435555554",null, true);
draftsDatabase.addMessage(messageObject1);
draftsDatabase.addMessage(messageObject2);
draftsDatabase.addMessage(messageObject3);
tester = getActivity();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
searchText = (EditText) tester.findViewById(R.id.searchText);
searchButton = (Button) tester.findViewById(R.id.searchButton);
}
#SmallTest
#UiThreadTest
public void testSearch() {
searchText.setText("hij");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word hi", 0, messagesToBeDisplayed.size());
searchText.setText("sup");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word sup", 1, messagesToBeDisplayed.size());
searchText.setText("yo");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word yo", 0, messagesToBeDisplayed.size());
searchText.setText("i");
searchButton.performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Messages with the word i", 2, messagesToBeDisplayed.size());
}
#SmallTest
#UiThreadTest
public void testRedisplay()
{
assertNotNull(tester.draftButtons[0]);
tester.draftButtons[0].performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("Size of the list after deletion is 2", 2, messagesToBeDisplayed.size()); //presses the first button, which deletes it from the drafts
getActivity();
String buttonText0 = tester.draftButtons[0].getText().toString();
if(buttonText0.equals("5555554: hi hi")) assertSame("Text redisplayed on the first button", buttonText0, messageObject2.toString()); //gets the text of the current button, since the messageobject1 was in draftsButtons0 before, not it should have messageobject2
assertNotNull(tester.draftButtons[1]);
String buttonText1 = tester.draftButtons[1].getText().toString();
if(buttonText1.equals("5435555554: sup"))
assertSame("Text redisplayed on the second button", buttonText1, messageObject3.toString());
}
#SmallTest
#UiThreadTest
public void testMessageButtons()
{
assertNotNull(tester.draftButtons[0]);
tester.draftButtons[0].performClick();
//THE PROBLEM IS LOCATED HERE.
//As soon as I press the button, the app goes to another activity.
//I want it to go back from the activity.
assertNotNull(tester.draftButtons[1]);
tester.draftButtons[1].performClick();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
assertEquals("The draftsDatabase now only contains 1 message", 1, messagesToBeDisplayed.size());
assertNotNull(tester.draftButtons[0]);
tester.draftButtons[0].performClick();
assertNull(draftsDatabase); //after you press all the buttons, the draftsDatabase should be empty because all the messages have been deleted
}
}
This is my code of application which I recently made. If user press a button it goes to another activity from this you will be to simulate a button press and go back to the previous activity and I also have made some modification that you can pass data from text view to second activity
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent i = new Intent(this, Main2Activity.class);
final EditText inputText = (EditText) findViewById(R.id.inputText);
String mesg = inputText.getText().toString();
i.putExtra("mm",mesg );
startActivity(i);
}
}
Main2Activity
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.Transition;
import android.transition.TransitionManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
ViewGroup RLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle data = getIntent().getExtras();
if(data == null){
return;
}
String mm = data.getString("mm");
final TextView textVieww = (TextView) findViewById(R.id.textVieww);
textVieww.setText(mm);
RLayout = (ViewGroup) findViewById(R.id.RLayout);
RLayout.setOnTouchListener(
new RelativeLayout.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
moveButton();
return true;
}
});
}
public void onClickk(View view) {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.razaali.third" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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=".Main2Activity"
android:label="#string/title_activity_main2" >
</activity>
</application>
</manifest>
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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#53ff00">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="First Screen"
android:id="#+id/textView"
android:layout_above="#+id/inputText"
android:layout_centerHorizontal="true"
android:layout_marginBottom="33dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClick" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputText"
android:width="250dp"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp" />
</RelativeLayout>
activity_main2.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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.razaali.third.Main2Activity"
android:background="#fff306"
android:id="#+id/RLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Secound Screen"
android:id="#+id/textVieww"
android:layout_above="#+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change"
android:id="#+id/button2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClickk" />
</RelativeLayout>
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!