Display value to another activity [duplicate] - java

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

Related

Using multiple buttons within dialog box with intents to change text of main button

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

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

Opening AlertDialog inside Dialog Fragment

I have a custom Dialog Fragment and I need to display an Alert dialog inside it.
Is it possible to do without closing the Dialog fragment?
When I do it with the context provided for the Dialog fragment it just closes the Dialog fragment and open the Alert dialog.
case R.id.deleteButton:
new AlertDialog.Builder(context)
.setTitle(context.getResources().getString(R.string.discard_changes))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
onItemClickListener.onItemClick(Device, DELETE_DOC);
dismiss();
})
.setNegativeButton(android.R.string.no, null).show();
break;
EDIT
As requested, the whole Dialog code:
public class InstallationDocumentDeviceAddFormDialog extends Dialog implements View.OnClickListener {
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private Context context;
private Button btn_cancel;
NavBar navBar;
Button addDeviceButton;
ImageButton deleteButton;
boolean isEditMode;
public static int EDIT_INSTALLATIONDOC = 1;
public static int DELETE_INSTALLATIONDOC = 2;
private InstallationDocumentDevice installationDocumentDevice;
public interface OnItemClickListener {
void onItemClick(InstallationDocumentDevice installationDocumentDevice, int action);
}
#NonNull
private OnItemClickListener onItemClickListener;
public InstallationDocumentDeviceAddFormDialog(#NonNull Context context, InstallationDocumentDevice installationDocumentDevice, boolean isEditMode, #NonNull OnItemClickListener onItemClickListener) {
super(context);
this.context = context;
this.onItemClickListener = onItemClickListener;
this.installationDocumentDevice = installationDocumentDevice;
this.isEditMode = isEditMode;
Log.i("DocumentController", "dialog device: " + installationDocumentDevice.toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_device_form);
RecyclerView accessoriesRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceAccessoriesRecycler);
RecyclerView guidancesRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceGuidancesRecycler);
RecyclerView testsRecyclerView = (RecyclerView) findViewById(R.id.addNewDeviceTestsRecycler);
navBar = findViewById(R.id.navBar);
if(isEditMode) navBar.setTitle(context.getResources().getString(R.string.editing_device) + " " + installationDocumentDevice.getLocalizedDeviceName());
else navBar.setTitle(context.getResources().getString(R.string.adding_new_device) + " " + installationDocumentDevice.getLocalizedDeviceName());
addDeviceButton = findViewById(R.id.btnAddNewDevice);
addDeviceButton.setOnClickListener(this);
deleteButton = (ImageButton) findViewById(R.id.deleteButton);
if(isEditMode){
deleteButton.setVisibility(View.VISIBLE);
deleteButton.setOnClickListener(this);
addDeviceButton.setText(context.getResources().getString(R.string.add_new_device_title));
} else {
deleteButton.setVisibility(View.GONE);
}
// navBar.getBackButton().setOnClickListener(view -> dismiss());
accessoriesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
guidancesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
testsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
accessoriesRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.ACCESSORIES));
guidancesRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.GUIDANCES));
testsRecyclerView.setAdapter(new InstallationDocumentDeviceAddFormAdapter(installationDocumentDevice, this::onClick, InstallationDocumentDeviceAddFormAdapter.TESTS));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddNewDevice:
onItemClickListener.onItemClick(installationDocumentDevice, EDIT_INSTALLATIONDOC);
dismiss();
break;
case R.id.deleteButton:
new AlertDialog.Builder(context)
.setTitle(context.getResources().getString(R.string.datapick_discard_changes))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
onItemClickListener.onItemClick(installationDocumentDevice, DELETE_INSTALLATIONDOC);
dismiss();
})
.setNegativeButton(android.R.string.no, null).show();
// onItemClickListener.onItemClick(installationDocumentDevice, DELETE_INSTALLATIONDOC);
// dismiss();
break;
}
dismiss();
}
private void onClick(int position, int tag) {
switch (tag) {
//Case Accessory
case 1:
// Toast.makeText(context, "Accessory pos: " + position + ". Is checked: " + installationDocumentDevice.getAccessories().get(position).isChecked(), Toast.LENGTH_SHORT).show();
break;
//Case Guidance
case 2:
// Toast.makeText(context, "Guidances pos: " + position, Toast.LENGTH_SHORT).show();
break;
//Case Tests
case 3:
// Toast.makeText(context, "Tests pos: " + position, Toast.LENGTH_SHORT).show();
break;
}
}
}
/* Yes This is Possible You Can Grow through Below My Code which I Use In Recycler Adapter in Holder View Click Event.*/
holder.calendar_day_gridcell.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1) {
// holder.txt_InTime.setText("Helllo");
try {
// Date parsedDate = dateFormatter.parse(date_month_year);
//Log.d(tag, "Parsed Date: " + parsedDate.toString());
DoubleClickPerform.preventTwoClick(v1);
final Dialog dialog = new Dialog(context,R.style.Theme_AppCompat_Dialog_Alert);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Calendar calendar;
int currentHour;
int currentMinute;
TextView txt_dialog_InTime,txt_dialog_OutTime,txt_dialog_SaveInTime,/*txt_dialog_Delete_InTime*/txt_dialog_SaveOutTime/*txt_dialog_Delete_OutTime*/;
ImageView img_clean_in_time,img_clean_out_time;
Button btn_close;
View view1 = context.getLayoutInflater().inflate(R.layout.in_out_time_dialog, null);
txt_dialog_InTime = view1.findViewById(R.id.txt_dialog_InTime);
txt_dialog_OutTime = view1.findViewById(R.id.txt_dialog_OutTime);
txt_dialog_SaveInTime = view1.findViewById(R.id.txt_dialog_SaveInTime);
// txt_dialog_Delete_InTime = view1.findViewById(R.id.txt_dialog_Delete_InTime);
txt_dialog_SaveOutTime = view1.findViewById(R.id.txt_dialog_SaveOutTime);
// txt_dialog_Delete_OutTime = view1.findViewById(R.id.txt_dialog_Delete_OutTime);
img_clean_in_time = view1.findViewById(R.id.img_clean_in_time);
img_clean_out_time = view1.findViewById(R.id.img_clean_out_time);
btn_close = view1.findViewById(R.id.btn_close);
calendar = Calendar.getInstance();
currentHour = calendar.get(Calendar.HOUR_OF_DAY);
currentMinute = calendar.get(Calendar.MINUTE);
txt_dialog_InTime.setText(holder.txt_InTime.getText().toString());
if(txt_dialog_InTime.getText().toString().equals(""))
{
txt_dialog_OutTime.setEnabled(false);
}
else
{
txt_dialog_OutTime.setEnabled(true);
}
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
txt_dialog_InTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog= new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Time time = new Time(hour, minute, 0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
txt_dialog_InTime.setText(s);
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
});
dialog.setContentView(view1);
dialog.show();
img_clean_in_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_dialog_InTime.setText("");
}
});
img_clean_out_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_dialog_OutTime.setText("");
}
});
txt_dialog_OutTime.setText(holder.txt_OutTime.getText().toString());
txt_dialog_OutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog= new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Time time = new Time(hour, minute, 0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
txt_dialog_OutTime.setText(s);
}
}, currentHour, currentMinute, false);
timePickerDialog.show();
}
});
dialog.setContentView(view1);
dialog.show();
/* txt_dialog_Delete_InTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_InTime.setText("");
dialog.dismiss();
}
});
txt_dialog_Delete_OutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_OutTime.setText("");
dialog.dismiss();
}
});
*/
txt_dialog_SaveInTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_InTime.setText(txt_dialog_InTime.getText().toString());
apiforSaveTime(txt_dialog_InTime.getText().toString(),txt_dialog_OutTime.getText().toString(), finalRevereseDate);
dialog.dismiss();
}
});
txt_dialog_SaveOutTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.txt_OutTime.setText(txt_dialog_OutTime.getText().toString());
if(!txt_dialog_InTime.getText().toString().equals(""))
{
apiforSaveTime(txt_dialog_InTime.getText().toString(),txt_dialog_OutTime.getText().toString(), finalRevereseDate);
dialog.dismiss();
}
else
{
Snackbar snackbar = Snackbar
.make(holder.itemView, "In Time Is Required", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});

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.

android java search listview clickedItem

I'm fairly new
I have succeeded to display my search results in my listview using an EditText.
Now when I click my result to bring up the "details" it gives me a wrong database record. The question is how to get the record of the clickedItem from my searchresults.
This is the List.java
public class List extends ActionBarActivity {
DatabaseManager db;
java.util.List<Passwords> passwordLijst = new ArrayList<Passwords>();
java.util.List<String> passwordsTitelLijst = new ArrayList<String>();
EditText inputSearch;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
SwipeRefreshLayout mSwipe = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
ImageView imageView=new ImageView(this);
imageView.setImageResource(R.drawable.ic_add_white_24dp);
FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
.setContentView(imageView)
.setBackgroundDrawable(R.drawable.selecter_button)
.build();
actionButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), addPass.class);
startActivity(intent);
}
}
);
mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
setRefreshListener();
}
});
initDatabaseManager();
}
private void setRefreshListener() {
construeerPasswordLijsten();
constueerScherm();
SwipeRefreshLayout mSwipe = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipe.setRefreshing(false);
}
#Override
protected void onResume(){
super.onResume();
construeerPasswordLijsten();
constueerScherm();
}
private void construeerPasswordLijsten(){
passwordLijst = db.getAllPassword();
passwordsTitelLijst = Passwords.constructTitleList(passwordLijst);
}
private void constueerScherm(){
final ListView myListView = (ListView) findViewById(R.id.mylist);
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),R.layout.rowlist, passwordsTitelLijst);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
int index = position;
Passwords clickedItem = passwordLijst.get(index);
Intent detailIntent = new Intent(getApplicationContext(), ListDetail.class);
detailIntent.putExtra("clickedItem", clickedItem);
startActivity(detailIntent);
}
});
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
ArrayList<String> temp = new ArrayList<String>();
int textlength = inputSearch.getText().length();
temp.clear();
for (int i = 0; i < passwordsTitelLijst.size(); i++) {
if (textlength <= passwordsTitelLijst.get(i).length()) {
if (inputSearch.getText().toString().equalsIgnoreCase(
(String)
passwordsTitelLijst.get(i).subSequence(0,
textlength))) {
temp.add(passwordsTitelLijst.get(i));
}
}
}
myListView.setAdapter(new ArrayAdapter<String>(List.this, R.layout.rowlist, temp));
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
int index = position;
Passwords clickedItem = passwordLijst.get(index);
Intent intent1 = new Intent(List.this, ListDetail.class);
intent1.putExtra("clickedItem", clickedItem);
startActivity(intent1);
}
});
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
}
Here is the ListDetail.java
public class ListDetail extends ActionBarActivity {
EditText showPW;
CheckBox mcbPW;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_detail);
initialise();
setEditButtonListener();
setSaveButtonListener();
setDeleteButtonListener();
showPW = (EditText) findViewById(R.id.text_detail_pw);
mcbPW = (CheckBox) findViewById(R.id.cbPW);
mcbPW.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
showPW.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
showPW.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
}
private void setDeleteButtonListener() {
Button deleteBtn = (Button) findViewById(R.id.delete_detail_button);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = getIntent();
Passwords clickedItem = (Passwords) i.getSerializableExtra("clickedItem");
DatabaseManager db = DatabaseManager.getInstance();
db.deletePasswords(clickedItem);
Toast toast = Toast.makeText(getApplicationContext(), "Password Deleted!", Toast.LENGTH_SHORT);
toast.show();
Intent j = new Intent(getApplicationContext(),List.class);
startActivity(j);
}
});
}
private void setEditButtonListener() {
Button editBtn = (Button) findViewById(R.id.update_detail_button);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText txtView_title = (EditText) findViewById(R.id.text_detail_title);
txtView_title.setEnabled(true);
EditText txtView_user = (EditText) findViewById(R.id.text_detail_username);
txtView_user.setEnabled(true);
EditText txtView_pw = (EditText) findViewById(R.id.text_detail_pw);
txtView_pw.setEnabled(true);
EditText txtView_notes = (EditText) findViewById(R.id.text_detail_notes);
txtView_notes.setEnabled(true);
EditText txtView_url = (EditText) findViewById(R.id.text_detail_url);
txtView_url.setEnabled(true);
EditText txtView_expDate = (EditText) findViewById(R.id.text_detail_expDate);
txtView_expDate.setEnabled(true);
}
});
}
private void setSaveButtonListener() {
Button saveButton = (Button) findViewById(R.id.save_detail_button);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
Passwords clickedItem = (Passwords)intent.getSerializableExtra("clickedItem");
EditText txtView_title = (EditText) findViewById(R.id.text_detail_title);
String title = txtView_title.getText().toString();
EditText txtView_user = (EditText) findViewById(R.id.text_detail_username);
String user = txtView_user.getText().toString();
EditText txtView_pw = (EditText) findViewById(R.id.text_detail_pw);
String pw = txtView_pw.getText().toString();
EditText txtView_notes = (EditText) findViewById(R.id.text_detail_notes);
String notes = txtView_notes.getText().toString();
EditText txtView_url = (EditText) findViewById(R.id.text_detail_url);
String url = txtView_url.getText().toString();
EditText txtView_expD = (EditText) findViewById(R.id.text_detail_expDate);
String expD = txtView_expD.getText().toString();
Passwords aangepastePW = new Passwords();
aangepastePW.setId(clickedItem.getId());
aangepastePW.setTitle(title);
aangepastePW.setUsername(user);
aangepastePW.setPassword(pw);
aangepastePW.setNotities(notes);
aangepastePW.setUrl(url);
aangepastePW.setExpDate(expD);
DatabaseManager db = DatabaseManager.getInstance();
db.updateStudent(aangepastePW);
Toast.makeText(ListDetail.this, "Information Changed!", Toast.LENGTH_SHORT).show();
Intent j = new Intent(getApplicationContext(),List.class);
startActivity(j);
}
});
}
private void initialise() {
Intent intent = this.getIntent();
Passwords clickedItem = (Passwords)intent.getSerializableExtra("clickedItem");
EditText txtView_title = (EditText) findViewById(R.id.text_detail_title);
txtView_title.setText(clickedItem.getTitle());
txtView_title.setEnabled(false);
EditText txtView_username = (EditText) findViewById(R.id.text_detail_username);
txtView_username.setText(clickedItem.getUsername());
txtView_username.setEnabled(false);
EditText txtView_pw = (EditText) findViewById(R.id.text_detail_pw);
txtView_pw.setText(clickedItem.getPassword());
txtView_pw.setEnabled(false);
EditText txtView_notes = (EditText) findViewById(R.id.text_detail_notes);
txtView_notes.setText(clickedItem.getNotities());
txtView_notes.setEnabled(false);
EditText txtView_url = (EditText) findViewById(R.id.text_detail_url);
txtView_url.setText(clickedItem.getUrl());
txtView_url.setEnabled(false);
EditText txtView_expD = (EditText) findViewById(R.id.text_detail_expDate);
txtView_expD.setText(clickedItem.getExpDate());
txtView_expD.setEnabled(false);
}
In the onItemClick of your listview replace the below line
Passwords clickedItem = passwordLijst.get(index);
with
Passwords clickedItem = adapter.getItem(index);
it retrieves the item at the given position in the adapter.

Categories