Activity does not even call onActivityResult - java

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.

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");

close Alert Dialog without using negative Buttons

I created an AlertDialog, which will either refresh the activity (when btnConfirm1 is pressed), or does nothing and simply closes down (when btnDisconfirm1 is pressed). Everything is working apart from btnDisconfirm1. How can I close the dialog?
So apparently AlertDialog does not have a dismiss or cancel method, but is there another way without using negative buttons? The thing is, I created a layout file for this dialog and I don't know how to put a negative button in my xlm-file.
Or should I use a completely different approach apart from AlertDialog? Thanks!
btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder2 = new AlertDialog.Builder(ScoreScreen.this);
View mView2 = getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null);
Button btnConfirm1=(Button) mView2.findViewById(R.id.btnConfirm1);
Button btnDisconfirm1=(Button) mView2.findViewById(R.id.btnDisconfirm1);
btnConfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.setPlayerScore(0);
player2.setPlayerScore(0);
player3.setPlayerScore(0);
player4.setPlayerScore(0);
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
btnDisconfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT DO I PUT HERE???
}
});
mBuilder2.setView(mView2);
AlertDialog dialog = mBuilder2.create();
dialog.show();
}
});
First you should create the AlertDialog with
AlertDialog mDialog = mBuilder2.create();
And secondly you can dismiss the dialog inside the OnClickListener with
mDialog.dismiss();
You can put this method in your Util class. and use callbacks
public interface OnDialogDismiss {
void onPositiveClick();
void onNegativeClick();
}
Modify it as your requirement.
public void showDialogForMultipleCallback(Context context, String title, String message, boolean cancellable, String neutralBbtn, String negativeBtn, String positiveBtn, final OnDialogDismiss onDialogDismiss) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(cancellable);
if (neutralBbtn != null) {
builder1.setNeutralButton(neutralBbtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (negativeBtn != null) {
builder1.setNegativeButton(negativeBtn,
new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (positiveBtn != null) {
builder1.setPositiveButton(positiveBtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
onDialogDismiss.onPositiveClick();
}
});
}
alert11 = builder1.create();
alert11.show();
}

Timer countdown in Android

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);
}
}
}

Display value to another activity [duplicate]

This question already has answers here:
how to pass value data between classes/activity in Android?
(6 answers)
Closed 5 years ago.
I want to pass the value of textview1 of Income.java onClick of btn_save to the MainActivity. And also want to sum the value of MainActivity.java when again new value passed Please help me...
Income.java
public class Income extends AppCompatActivity implements AdapterView.OnItemSelectedListener,Calculator.OnDialogReturnListener,View.OnClickListener{
Spinner spinner1;
String[] name,name1;
Button btn_cancel, btn_save,acc_btn,button,updatebtn;
TextView textView1,textView2,accountTV,wantupdate,income;
//EditText textView1;
int yy,mm,dd;
private Income_class i_class;
DatabaseHandler mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.income);
textView1 = (TextView) findViewById(R.id.income_tv);
textView2 = (TextView) findViewById(R.id.date_tv);
accountTV = (TextView) findViewById(R.id.acc_tv);
income = (TextView) findViewById(R.id.incometv);
wantupdate = (TextView) findViewById(R.id.notupdate);
btn_cancel = (Button) findViewById(R.id.cancel_btn);
updatebtn = (Button) findViewById(R.id.up_btn);
acc_btn = (Button) findViewById(R.id.account_btn);
btn_save = (Button) findViewById(R.id.save_btn);
button = (Button) findViewById(R.id.btn);
final AlertDialog.Builder dialog = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog1 = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog2 = new AlertDialog.Builder(Income.this);
final AlertDialog.Builder dialog3 = new AlertDialog.Builder(Income.this);
final EditText editText = new EditText(Income.this);
dialog.setView(editText);
final DatabaseHandler db = new DatabaseHandler(Income.this);
mydb = new DatabaseHandler(this);
button.setOnClickListener(this);
// for calculator
final Calculator cdd = new Calculator(Income.this);
cdd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
cdd.setOnDialogReturnListener(this);
cdd.show();
// for displaying date
final Calendar c = Calendar.getInstance();
yy = c.get(Calendar.YEAR);
mm = c.get(Calendar.MONTH);
dd = c.get(Calendar.DAY_OF_MONTH);
//set current date into text..
textView2.setText(new StringBuilder()
//month os 0 based. Just add 1
.append(dd).append("-").append(mm + 1).append("-").append(yy));
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Income.this,MainActivity.class);
startActivity(intent);
finish();
}
});
acc_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Income.this,Account_detail.class);
startActivity(intent);
finish();
}
});
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cat = button.getText().toString();
String acc = accountTV.getText().toString();
String text = textView1.getText().toString();
if(text.equals("0")){
dialog3.setTitle("You must enter amount.");
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface ialog, int which) {
}
});
dialog3.show();
}
else if(cat.equals("Select Category")){
dialog1.setTitle("Please Select category");
dialog1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*Intent intent = new Intent(Income.this, Income.class);
startActivity(intent);
finish();*/
button.requestFocus();
}
});
dialog1.show();
}
else if(acc.equals("")){
dialog2.setTitle("Please Select Account");
dialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acc_btn.requestFocus();
}
});
dialog2.show();
}
else {
String value = accountTV.getText().toString();
String value2 = textView1.getText().toString();
String value3 = button.getText().toString();
db.update_income(value, value2, value3);
Toast.makeText(getBaseContext(), "Updated Successfully...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Income.this, Acc_income.class);
startActivity(intent);
finish();
}
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cat = button.getText().toString();
String acc = accountTV.getText().toString();
String text = textView1.getText().toString();
if(text.equals("0")){
dialog3.setTitle("You must enter amount.");
dialog3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface ialog, int which) {
}
});
dialog3.show();
}
else if(cat.equals("Select Category")){
dialog1.setTitle("Please Select category");
dialog1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*Intent intent = new Intent(Income.this, Income.class);
startActivity(intent);
finish();*/
button.requestFocus();
}
});
dialog1.show();
}
else if(acc.equals("")){
dialog2.setTitle("Please Select Account");
dialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acc_btn.requestFocus();
}
});
dialog2.show();
}
else {
String balance2 = textView1.getText().toString();
String name = accountTV.getText().toString();
String category = button.getText().toString();
db.income_insert(name, category, balance2);
Toast.makeText(getBaseContext(), "Account Added...",
Toast.LENGTH_SHORT).show();
}
}
});
wantupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(Income.this);
dialog.setTitle("Enter Income");
final EditText editText = new EditText(Income.this);
dialog.setView(editText);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value1 = textView1.getText().toString();
String value2 = editText.getText().toString();
if(textView1.equals("0")){
String a = editText.getText().toString();
textView1.setText(a);
}
else if(value2.equals("")){
Toast.makeText(Income.this,"Please Enter Amount.",Toast.LENGTH_LONG).show();
}
else {
int a = Integer.parseInt(value1);
int b = Integer.parseInt(value2);
int sum = a + b;
textView1.setText(Integer.toString(sum));
}
}
});
dialog.show();
}
});
Intent intent = getIntent();
accountTV.setText(intent.getStringExtra("ppp"));
}
public void addnumber(){
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name2 = name[position];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onReturn(String data) {
textView1.setText(data);
}
#Override
public void onClick(View v) {
/*String cat = button.getText().toString();
if(cat.equals("Select Category")){
button.setError("Please Select category");
button.requestFocus();
}
else */
final CharSequence[] items = {"Automobile", "Entertainment", "Family", "Food And Drinks", "Gasoline", "Gifts And Donations",
"Groceries", "Health And Fitness", "Housing", "Medical", "Other", "Parking", "Shopping", "Utilities"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
button.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Income.this,MainActivity.class);
startActivity(intent);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button expance,income,account,budget,calander,report,more,transfer;
TextView incomeTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
incomeTv = (TextView)findViewById(R.id.incometv);
expance = (Button)findViewById(R.id.button_expanse);
income = (Button)findViewById(R.id.button_income);
account = (Button)findViewById(R.id.button_account);
budget = (Button)findViewById(R.id.button_budget);
transfer = (Button)findViewById(R.id.button_moneytransfer);
calander = (Button)findViewById(R.id.button_calander);
report = (Button)findViewById(R.id.button_report);
more = (Button)findViewById(R.id.button_more);
expance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Expense.class);
startActivity(intent);
finish();
}
});
income.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Income.class);
startActivity(intent);
finish();
}
});
account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_detail.class);
startActivity(intent);
finish();
}
});
transfer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_Transfer.class);
startActivity(intent);
finish();
}
});
budget.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Acc_income.class);
startActivity(intent);
finish();
}
});
calander.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Account_detail_2.class);
startActivity(intent);
finish();
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Update.class);
startActivity(intent);
finish();
}
});
}
You can use
intent.putExtra("key", value);

how pass result from alertDialog to onActivityResult

I have Activity_A an Activity_B.
I use onActivityResult and i have a problem:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=3, result=-1, data=Intent { (has extras)
}} to activity {com.example.sellcar/com.example.sellcar.View_Offer}:
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
I guess that I can not pass this way 'result' from alertDialog to onActivityResult.
I do not know how to solve this problem :/
Please help
Activity_A:
bBUTTON.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity_A.this,Activity_B.class);
startActivityForResult(intent, 3);
}
});
...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK){
String pId = data.getStringExtra("MyData");
Toast.makeText(Activity_A.this,pId,Toast.LENGTH_LONG).show();
}
}
Activity_B:
AlertDialog.Builder builder=new AlertDialog.Builder(View_Sell.this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
Intent intent = new Intent();
intent.putExtra("MyData", ostatnioDodanaSprzedaz);
setResult(RESULT_OK, intent);
onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
AlertDialog ad = builder.create();
ad.show();
Try to replace:
setResult(RESULT_OK, intent);
onBackPressed();
on:
if (getParent() == null) {
setResult(RESULT_OK, intent);
} else {
getParent().setResult(RESULT_OK, intent);
}
finish();
You can follow the Observer pattern.
First, create an Interface in the Activity class itself:
public interface ResultListener {
void onResultSet(String text);
}
Then, create an object of ResultListener globally:
ResultListener = rl;
Implement the onResultSet(String text) method inside the onCreate method:
rl = new ResultListener() {
#Override
public void onPositiveResult(String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
Next, create the AlertDialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
tl.onResultSet(ostatnioDodanaSprzedaz);
// onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
builder.show();
Here's how the final code will look:
public class MainActivity extends Activity {
ResultListener rl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
rl = new ResultListener() {
#Override
public void onPositiveResult(String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("UWAGA !").setMessage("blablabla");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String ostatnioDodanaSprzedaz="XYZ";
rl.onResultSet(ostatnioDodanaSprzedaz);
// onBackPressed();
} });
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
} });
builder.show();
} //onCreate closed
public interface ResultListener {
void onResultSet(String text);
}
} //MainActivity Class closed

Categories