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");
Related
i am in a pickle at the moment to how to approach making 3 buttons within a single dialog box make the option selected change the text of the button used to show the dialog box, so far only managed to get option3 to work as i suppose its the last intent so the only button that works would be the button for option3
here is the code im trying to pass to the main button from the dialog
public class LabelDialog extends AppCompatDialogFragment {
private Button option1, option2, option3;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.label_dialog, null);
builder.setView(view);
//option 1 and 2
option3 = view.findViewById(R.id.label_lecturebtn);
option3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String option3 = "Lecture";
Intent intent3 = new Intent(getContext(), AddTask.class);
intent3.putExtra("lecture", option3);
startActivity(intent3);
dismiss();
}
});
and the main code
protected void onCreate(Bundle savedInstanceState) {
//...
label_button = findViewById(R.id.button_labels);
label_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
checkLabelResult();
}
public void openDialog() { //Labels dialog
//code to open dialog
}
public void checkLabelResult() {
//intents 1 and 2, same format as 3 but keys changed accordingly
Intent intent3 = getIntent();
String option3 = intent3.getStringExtra("lecture");
label_button.setText(option3);
}
Code for Option 1
option1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String option1 = "Important";
Intent intent = new Intent(getContext(), AddTask.class);
intent.putExtra("important", option1);
startActivity(intent);
dismiss();
}
Code for Option 2
option2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String option2 = "To Do";
Intent intent2 = new Intent(getContext(), AddTask.class);
intent2.putExtra("to do", option2);
startActivity(intent2);
dismiss();
}
This question already has answers here:
RecyclerView: how to catch the onClick on an ImageView?
(2 answers)
Closed 4 years ago.
What I am trying to accomplish is to create a listener for the ImageView inside the row of RecyclerView.
This code is working already, but this is not the solution that I wanted to have, because you need to double click the ImageView before getting the desired result.
// row click listener
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
ImageView viewContent = (ImageView)view.findViewById(R.id.btnViewContent);
ImageView deleteContent = (ImageView)view.findViewById(R.id.btnDeleteContent);
viewContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "VIEW CONTENT", Toast.LENGTH_SHORT).show();
}
});
deleteContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "DELETE CONTENT", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onLongClick(View view, int position) {}
}));
Any idea how to translate this into single click solution? Advice or even a single comment would help me a lot.
This is not the right way as one of our friend suggested onBindViewHolder is caleed again and again during scrolling so it is not the best practice to add listener there.
Best way is to add it on ViewHolder as I suggested. Check my answer above.
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.btnClassAddCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}
Then there is no need to implement recyclerView.addOnItemTouchListener , inside Viewholder just add clicklistener on the view(image) you want below is the example for reference.
` public static class HeaderViewHolder extends RootViewHolder {
#BindView(R.id.cardview)
CardView cardview;
#BindView(R.id.main_container)
LinearLayout main_container;
#BindView(R.id.music_cardview)
CardView music;
#BindView(R.id.shabad_cardview)
CardView shabadvaani;
#BindView(R.id.news_cardview)
CardView news;
#BindView(R.id.donate_cardview)
CardView donate;
#BindView(R.id.bs_cardview)
CardView bs;
#BindView(R.id.bl_cardview)
CardView bl;
#BindView(R.id.bng_cardview)
CardView bng;
#BindView(R.id.more_cardview)
CardView more;
#BindView(R.id.vid_cardview)
CardView vid;
#BindView(R.id.medi_cardview)
CardView medi;
//
// #BindView(R.id.ama_cardview)
// CardView ama;
public HeaderViewHolder(final View itemView,final OnItemClickListener mOnItemClickListener) {
super(itemView);
ButterKnife.bind(this, itemView);
news.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//Intent i= new Intent(ctx,);
//open drawer code
}
});
shabadvaani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, IndexActivity.class);
ctx.startActivity(i);
}
});
music.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, MainActivity.class);
i.putExtra("slug","audiobhajan");
ctx.startActivity(i);
//open drawer code
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent(ctx, stayrocks.jambh.vani.auth.MainActivity.class);
// ctx.startActivity(i);
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//open drawer code
}
});
bs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(ctx, AmaActivity.class);
ctx.startActivity(intent);
}
});
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, ItemListActivity.class);
ctx.startActivity(i);
//open drawer code
}
});
bng.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, WallpaperActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
medi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, stayrocks.jambh.vani.activities.jyot.MainActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
vid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, VideoListDemoActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
// ama.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//// String appPackage = "com.my.bishnoi.nextgen";
//// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
//// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent= new Intent(ctx, AmaActivity.class);
// ctx.startActivity(intent);
// //open drawer code
// }
// });
}
}
`
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}
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);
}
}
}
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);
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.