Timer countdown in Android - java

Im new to android application development, sorry if i had made any mistakes. How can i start the timer countdown each time when i visit homeActivity as per my code.I appreciate everyone who tried to help me. Thank you.
public class homeActivity extends AppCompatActivity {
private TextView userEmail; // Declaring email textview
private TextView timerDisplay; // Declaring Timer Display textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userEmail = (TextView) findViewById(R.id.userEmailID);
timerDisplay = (TextView) findViewById(R.id.timer);
// Retriving the the email id of the user which was passed from the sigin Activity
userEmail.setText(getIntent().getExtras().getString("Email"));
//use of a timer to display the notification 40 seconds as default for testing purposes
new CountDownTimer(40000, 1000) {
public void onTick(long millisUntilFinished) {
// Displaying the following timer on the textview
timerDisplay.setText("seconds remaining: " + millisUntilFinished / 1000);
}
//once the timer stops the following notification message is being Displayed
public void onFinish() {
final String title1="Break!";
String subject1="It is time to take a break";
String body1="20 minutes have passed";
// Break taken is displayed on the textview
timerDisplay.setText("Break Taken");
// notification is diplayed
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle(title1).setContentText(body1).
setContentTitle(subject1).setSmallIcon(R.mipmap.iclauncher).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
}.start();
}
// Directed to rate us Activity
public void rateusOperation (View v){
Intent intent = new Intent(homeActivity.this,rateUsActivity.class);
startActivity(intent);
}
// Directed to daily offers Activity
public void dailyOffersOperation (View v){
Intent intent = new Intent(homeActivity.this,dailyOffersActivity.class);
startActivity(intent);
}
// directed to statistics Activity
public void statisticsOperation (View v){
Intent intent = new Intent(homeActivity.this,statisticsActivity.class);
startActivity(intent);
}
// directed to privacy policy Activity
public void privacyPolicyOperation (View v){
Intent intent = new Intent(homeActivity.this,privacyPolicyActivity.class);
startActivity(intent);
}
// Directed back to sign in Activity
public void logoutOperation (View v){
AlertDialog.Builder altDial = new AlertDialog.Builder (homeActivity.this);
altDial.setMessage("Are You Sure ? ").setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(homeActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = altDial.create();
alert.setTitle("You want to Logout ");
alert.show();
}
}

public class homeActivity extends AppCompatActivity
{
private TextView userEmail; // Declaring email textview
private TextView timerDisplay; // Declaring Timer Display textview
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userEmail = (TextView) findViewById(R.id.userEmailID);
timerDisplay = (TextView) findViewById(R.id.timer);
// Retriving the the email id of the user which was passed from the sigin Activity
userEmail.setText(getIntent().getExtras().getString("Email"));
final CounterClass timer2 = new CounterClass(4000, 1000);
timer2.start();
}
// Directed to rate us Activity
public void rateusOperation (View v){
Intent intent = new Intent(homeActivity.this,rateUsActivity.class);
startActivity(intent);
}
// Directed to daily offers Activity
public void dailyOffersOperation (View v){
Intent intent = new Intent(homeActivity.this,dailyOffersActivity.class);
startActivity(intent);
}
// directed to statistics Activity
public void statisticsOperation (View v){
Intent intent = new Intent(homeActivity.this,statisticsActivity.class);
startActivity(intent);
}
// directed to privacy policy Activity
public void privacyPolicyOperation (View v){
Intent intent = new Intent(homeActivity.this,privacyPolicyActivity.class);
startActivity(intent);
}
// Directed back to sign in Activity
public void logoutOperation (View v){
AlertDialog.Builder altDial = new AlertDialog.Builder (homeActivity.this);
altDial.setMessage("Are You Sure ? ").setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(homeActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = altDial.create();
alert.setTitle("You want to Logout ");
alert.show();
}
public class CounterClass extends CountDownTimer
{
TextView conter;
public CounterClass(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
final String title1="Break!";
String subject1="It is time to take a break";
String body1="20 minutes have passed";
// Break taken is displayed on the textview
timerDisplay.setText("Break Taken");
// notification is diplayed
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle(title1).setContentText(body1).
setContentTitle(subject1).setSmallIcon(R.mipmap.iclauncher).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished)
{
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
timerDisplay.setText(hms);
}
}
}

Related

Pass textview value between activity

i have a problem.
I have 2 textviews that are increased on button click, but i don't know how to pass textview's value to the next activity that also have the same 2 textviews. Like increasing the value by 1 on first activity then on the second activity on the same textview there will be the value 1 and so on...
I'm trying to pass the textview value to next activity, i tried a few methods with putextra methods, but it didn't worked.
There is the code
Button btnIncrement;
private CheckBox i1, i2, i3;
public Button bckbutton;
TextView rspCorecte;
TextView rspGresite;
int counterCorecte=0;
int counterGresite=0;
private void initialStates(Intent intent) {
i1=findViewById(R.id.q1_1);
i2=findViewById(R.id.q1_2);
i3=findViewById(R.id.q1_3);
}
Then...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intrebarea_1);
initialStates(getIntent());
final AlertDialog.Builder alert2=new AlertDialog.Builder(Intrebarea1.this);
LayoutInflater factry=LayoutInflater.from(Intrebarea1.this);
final View view2=factry.inflate(R.layout.raspuns_corect, null);
alert2.setView(view2);
alert2.setPositiveButton("", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
final AlertDialog.Builder alertadd = new AlertDialog.Builder(Intrebarea1.this);
LayoutInflater factory = LayoutInflater.from(Intrebarea1.this);
final View view = factory.inflate(R.layout.raspuns1, null);
alertadd.setView(view);
alertadd.setPositiveButton("", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
startActivity(new Intent(Intrebarea1.this,Intrebarea2.class));
finish();
}
});
// SEMNUL INTREBARII
//reference of button added in the main layout
final Button raspuns = findViewById(R.id.arataraspuns);
//setting click event listener to button
raspuns.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Intrebarea1.this);
View view = LayoutInflater.from(Intrebarea1.this).inflate(R.layout.raspuns1, null);
builder.setView(view);
builder.show();
}
});
bckbutton=(Button) findViewById(R.id.backbutton);
bckbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
btnIncrement=findViewById(R.id.btnIncrement);
rspCorecte=findViewById(R.id.rspCorecte);
rspGresite=findViewById(R.id.rspGresite);
btnIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(i1.isChecked() && !i2.isChecked() && !i3.isChecked()){
alert2.show();
counterCorecte++;
}
else if (i1.isChecked() && i2.isChecked() && i3.isChecked()){
alertadd.show();
counterGresite++;
}
else if(i2.isChecked() && i3.isChecked()){
alertadd.show();counterGresite++;
}
else if(i1.isChecked() && i2.isChecked()){
alertadd.show();counterGresite++;
}
else if(i1.isChecked() && i3.isChecked()){
alertadd.show();counterGresite++;
}
else if(i2.isChecked()){
alertadd.show();counterGresite++;
}
else if(i3.isChecked()){
alertadd.show();counterGresite++;
}
btnIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
raspuns.setVisibility(View.VISIBLE);
btnIncrement.setVisibility(View.GONE);
}
});
rspCorecte.setText(String.valueOf(counterCorecte));
rspGresite.setText(String.valueOf(counterGresite));
}
}); }
public void bckButton(){
Intent intent=new Intent(this, AlegeMediulDeInvatare.class);
startActivity(intent);
finish();
}
public void openMainMenu(){
Intent intent=new Intent(this, MainMenu.class);
startActivity(intent);
finish();
}
public void onBackPressed(){
AlertDialog.Builder inchiziteoria = new AlertDialog.Builder(Intrebarea1.this, R.style.AlertDialogStyle);
LayoutInflater inchizi=LayoutInflater.from(Intrebarea1.this);
View view=inchizi.inflate(R.layout.inchizi_teoria, null);
inchiziteoria.setView(view);
// Set the positive button
inchiziteoria.setPositiveButton("DA", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
openMainMenu();
}
});
// Set the negative button
inchiziteoria.setNegativeButton("NU", null);
// Create the alert dialog
AlertDialog dialog = inchiziteoria.create();
// Finally, display the alert dialog
dialog.show();
((Button)dialog.getButton(dialog.BUTTON_POSITIVE)).setTypeface(null, Typeface.BOLD);
((Button)dialog.getButton(dialog.BUTTON_NEGATIVE)).setTypeface(null, Typeface.BOLD);
// Change the alert dialog background color
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
public void openUrmatoarea(View v){
Intent intent=new Intent(this, Intrebarea2.class);
startActivity(intent);
finish();
}
}
Can someone tell me how to pass the textview value to the next activity?
Thanks in advance.
Intent intent = new Intent(getBaseContext(), MainActivity.class);
// change the MainActivity if you want to pass the value to another activity
intent.putExtra("text", text);
startActivity(intent);
And in the next activity where you want to get the value :
Intent intent = getIntent();
String text = intent().getStringExtra("text");

Stop CountDownTimer when we click on the home button

How do I stop the CountDownTimer when I leave the application (when I click on the home button on my smartphone) the CountDownTimer remains running
  I tried with this code but when I leave the application a message appears in my smartphone "app name has stopped." Close the application
help me please
here is the code that I use
CountDownTimer timer = new CountDownTimer(120000, 1000) {
#SuppressLint("DefaultLocale")
public void onTick(long millisUntilFinished) {
tv.setText(String.format("%d : %d ",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_cum, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smile_lost);
message.setText("You have exceeded \n your time of reflection");
builder1.setPositiveButton("Replay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}.start();
}
is the code in onStop ()
#Override
public void onStop() {
super.onStop();
timer.cancel();
}
I suggest two way
1
Create global variable like
private isInForgrand = false;
And in onStop() or onPause() and onResume() change it
#Override
public void onStop() {
isInForgrand = false;
super.onStop();
}
#Override
public void onResume() {
super.onResume();
isInForgrand = true;
}
And in onFinish() check it
#Override
public void onFinish() {
if(isInForgrand){
//do what you want
}else{
//your app NOT in Forgrannd
}
2
You can cancel CountDownTimer in onStop()
#Override
public void onStop() {
super.onStop();
mCountDownTimer.cancel();
}

How to pass int value on button click from one activity to another?

I'm new to android. I'm trying to make a quiz app which has categories (history, sports...).
There is only one table with 60 questions in database. First 10 question are from category one(history) and 10 to 20 from category second(sports) and so on. I want that on click of First category only first 10 questions will be fetched and on click on second category only 10 to 20 questions will be fetched. Can we solve this problem passing some value through intent in onclick() and use that value in if else for bounding the questions?
QuestionActivity.java
public class QuestionActivity extends Activity {
List<Question> quesList;
int score = 0;
Random r = new Random();
int qid= (r.nextInt(60) + 0);
Question currentQ;
TextView txtQuestion, times, scored;
Button button1, button2, button3;
CounterClass timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuizHelper db = new QuizHelper(this); // my question bank class
quesList = db.getAllQuestions(); // this will fetch all quetonall
questions
currentQ = quesList.get(qid); // the current question
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from
question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which score will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
// method which will set the things up for our game
setQuestionView();
times.setText("00:00:30");
// A timer of 30 seconds to play for, with an interval of 1 second
(1000 milliseconds)
timer = new CounterClass(30000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText("Score : "+ score);
}
else {
// if unlucky start activity and finish the game
timer.cancel();
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
// passing the int value
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
if (qid < 60) {
// if questions are not over then do this
currentQ = quesList.get(qid);
setQuestionView();
} else {
// if over do this
timer.cancel();
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
Intent intent = new Intent(QuestionActivity.this,
ResultActivity.class);
timer.cancel();
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid= (r.nextInt(60) + 0);
}
}
Home.java
public class Home extends Activity {
Button play,about,help,quit;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
play=(Button)findViewById(R.id.play);
about=(Button)findViewById(R.id.about);
quit=(Button)findViewById(R.id.quit);
help=(Button)findViewById(R.id.help);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent(getApplicationContext(),QuestionActivity.class);
startActivity(intent);
finish();
}
});
quit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
about.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),about.class);
startActivity(intent);
}
});
help.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),help.class);
startActivity(intent);
}
});
}
}
After you create an Intent object but before you call startActivity(intent); use: intent.putExtra("name",123); When you want to get the integer in the other activity simply use: int foo = getIntent().getIntExtra("name");
In the activity where you calculated that int value and you would like to go to the other Activity:
int magicVariable = 100;
Intent intent = new Intent(this, OtherClassToGo.class);
intent.putExtra("EXTRA_VALUE_KEY", magicVariable);
startActivity(intent);
In the OtherClassToGo's onCreate() method:
Intent intent = getIntent();
int magicVariableFromOtherClass = intent.getIntExtra("EXTRA_VALUE_KEY");
Of course for "EXTRA_VALUE_KEY" you can use a public static variable so it is easier to "remember" it.
create variable int page and max, use setterPage getterPage page on question activity. and give value max = listquestion.size, and then use set and get value page on your button

Activity does not even call onActivityResult

I know,I have seen the duplicates. But none of them solved my issue.
I want my code to get newMessage from EditMessage activity and pass it to the SendMessage Activity, and I know I may not need to use onActivityResult tough I still want to learn what's the issue here.
I'have added log messages to check where my problem is but it doesn't even run my Log inside the onActivityResult.
Here's the code:
EditMessageActivity:
public static final String MESSAGE = "message";
EditText currentTextEditText;
Button sendButton;
Button saveButton;
Button cancelButton;
Button concatenateButton;
private String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_message_layout);
message = getIntent().getStringExtra(SendMessageActivity.MESSAGE);
currentTextEditText = (EditText) findViewById(R.id.currentText_EditText);
sendButton = (Button) findViewById(R.id.sendButton);
saveButton = (Button) findViewById(R.id.saveButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
concatenateButton = (Button) findViewById(R.id.concatenateButton);
if (message != null) //Activity may be started via "edit" Button
currentTextEditText.setText(message);
currentTextEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
message = currentTextEditText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
message = currentTextEditText.getText().toString();
}
});
concatenateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String[] messages = getResources().getStringArray(R.array.messages_array);
AlertDialog.Builder builder = new AlertDialog.Builder(EditMessage.this);
builder.setTitle("Sonuna Ekle").setItems(messages, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
char lastChar = message.charAt(message.length() - 1);
String messageToAdd = messages[which];
if (lastChar == '!' || lastChar == '?' || lastChar == '.') {
message += " " + messageToAdd;
} else {
message += " " + messageToAdd.toLowerCase();
}
currentTextEditText.setText(message);
dialog.cancel();
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EditMessage.this, NumberSelectActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
finish();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent(EditMessage.this, SendMessageActivity.class);
intent.putExtra(MESSAGE, message);
setResult(RESULT_OK);
startActivityForResult(intent, SendMessageActivity.REQUEST_NEW_MESSAGE);
finish();
Log.i("Custom", "Custom Message created :" + message);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
SendMessageActivity:
public static final String MESSAGE = "message";
public static final int REQUEST_NEW_MESSAGE = 1001;
private static String message;
ListView messageListView;
Button createMessage;
ArrayList<String> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
//Retrive Pre-Defined Messages
//TODO Add in-app message defining
String[] dbMessages = getResources().getStringArray(R.array.messages_array);
for (int i = 0; i < dbMessages.length; i++) {
messageList.add(dbMessages[i]);
}
//Create the array adapter
//TODO Upgrade this to a custom adapter which will also show an small image related to the message
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, messageList);
createMessage = (Button) findViewById(R.id.createMessageBtn);
createMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startEditMessage("");
}
});
messageListView = (ListView) findViewById(R.id.messagesListView);
messageListView.setAdapter(adapter);
//Make this one clickable
messageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
message = messageList.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(SendMessageActivity.this);
builder.setTitle("Send Message");
builder.setMessage(message);
builder.setPositiveButton("Gönder", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(SendMessageActivity.this, NumberSelectActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
}
});
builder.setNeutralButton("Düzenle", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Create new activity to edit message and send it or just cancel it
//Todo and return back
startEditMessage(message);
}
});
builder.setNegativeButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Custom", "Result OK değil :" + message);
if (resultCode == RESULT_OK) {
Log.i("Custom","Result OK:" + message);
if (requestCode == REQUEST_NEW_MESSAGE) {
Log.i("Custom","request is ok :" + message);
String newMessage = getIntent().getStringExtra(EditMessage.MESSAGE);
if (newMessage != null) {
Log.i("Custom","Message is not null :" + message);
messageList.add(newMessage);
//TODO Create new method to load all messages from database and just call that method
ArrayAdapter<String> updatedAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, messageList);
messageListView.setAdapter(updatedAdapter);
Log.i("Custom", "Updated adapter :" + message);
}
}
}
}
public void startEditMessage(String message) {
Intent intent = new Intent(SendMessageActivity.this, EditMessage.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
}
Any help will be appriciated.Thanks.
I want my code to get newMessage from EditMessage activity and pass it
to the SendMessage Activity.
Lets say there are three activities A(MainActivity), B(EditMessageActivity), C(SendMessageActivity).
To get message from B to A, you startActivityForResult() from A. When required value is retreived in B, you setResult() in B and then call finish().
The result will be received in A by overriding onActivityResult(). And then start C, and put the value in intent.
For example, reporting value back to MainActivity from EditMessageActivity:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent();
intent.putExtra(MESSAGE, message);
setResult(RESULT_OK, intent);
finish();
Log.i("Custom", "Custom Message created :" + message);
}
});
If there are only two activities, then no need of onActivityResult(). You can directly pass the message to SendMessageActivity using Intent.
For example, sending value from MainActivity to EditMessageActivity without onActivityResult():
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent(EditMessageActivity.this, SendMessageActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
Log.i("Custom", "Custom Message created :" + message);
}
});
Use
int request = 0;// Any number to identify your request
startActivityForResult(intent,request);
Instead of
startActivity(intent);
And don't use
finish()
;// function from the calling activity which will remove the activity from the stack.

How to wait for an okay button before starting a new activity

Good day.I have a problem, I am displaying a message box when a button is clicked.The message box simple shows a confirmation of registration.After that I open a new activity.
The problem is that it shows the messagebox and then starts the new activity without waiting for the ok button to be clicked.How can I only display the new activity upon clicking the ok button.
Below is the code I used.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Button btn = (Button)findViewById(R.id.registerButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage("You have successfully Registered.Please Press okay to continue");
dlgAlert.setTitle("Registration");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(false);
dlgAlert.create().show();
startActivity(intent);
finish();
}
});
Changed the code to
#Override
public void onClick(View view) {
// Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage("You have successfully Registered.Please Press okay to continue");
dlgAlert.setTitle("Registration");
dlgAlert.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
startActivity(intent);
}
});
dlgAlert.setCancelable(false);
dlgAlert.show();
Don't start activity there. Remove the line startActivity(intent) and finish(). You need to do this
builder.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(your arguments here)
startActivity(intent);
}
});
builder.show();
So all you need to do is change the line to setPositiveButton and use as given above.
As per your style, you are not setting action to the dialog but to the button that displays the dialog.
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Button btn = (Button)findViewById(R.id.registerButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage("You have successfully Registered.Please Press okay to continue");
dlgAlert.setTitle("Registration");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(false);
dlgAlert.create().show();
dlgAlert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
startActivity(intent);
}
});
}
});

Categories