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.
Related
I have a modal(dialog) with a edit text inside and a send button, what i'm trying to do is simply send the content inside the edit text when the button is clicked, the thing is, sending the content is working, but when i call mydialog.dismiss(); it doesn't work. It is using an instance of another class to call a method retrofit, and inside the "done" and "not done" buttons i have the "enviar"(send) button which is the one i'm trying to close the modal with.
Here is the adapter code:
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent){
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(sContext).inflate(R.layout.item_tasks, parent,false);
final Tasks presenteTask = taskData.get(position);
TextView taskTitle = (TextView) listItem.findViewById(R.id.tasksTitle);
taskTitle.setText(presenteTask.getTitle());
EditText taskColor = (EditText) listItem.findViewById(R.id.taskColor);
if(presenteTask.getHexaColor().isEmpty()){
HexaColor = "#FFFFFF";
}
else{
HexaColor = presenteTask.getHexaColor();
taskColor.setBackgroundColor(Color.parseColor(HexaColor));
}
TextView taskTime = (TextView) listItem.findViewById(R.id.taskTime);
taskTime.setText(presenteTask.getTimeStart().toString().substring(0,5));
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false);
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final EditText comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
final Calendario calendario = new Calendario();
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
return listItem;
}
}
Thank you very much!
Firstly you have to make your dialog un-cancelable, so that outside click doesn't dismiss it using tasksModal.setCancelable(false);
Secondly no need to repeat code to create dialog inside done/undone button click. So, remove it and move it to TasksAdapter constructor.
Thirdly You are not dismissing your dialog inside done button click. So, add this tasksModal.dismiss();
Check and try with below code:
EditText comentarios;
Calendario calendario;
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false); //make it un cancelable
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
calendario = new Calendario();
}
-------------------------------------------------------------
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(!comentario.equals("")){
tasksModal.dismiss(); //dismiss here
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
else{
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
else{
tasksModal.dismiss();
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
}
});
tasksModal.show();
}
});
I am trying pass data from my dialog box to a new Activity. So basically what i want to do for example in my Dialog box i have Name: John, when i click on my okay button it opens a new activity but i want that John to be set in my edit box on my new activity:
Here is my Activity where my Dialog box code is:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/** To change selected state view */
view.setSelected(true);
HashMap<String, Object> obj = (HashMap<String, Object>) ADAhere.getItem(position);
String SlectedName = (String) obj.get("NAME");
String SlectedPrice = (String) obj.get("PRICE");
String SlectedSize = (String) obj.get("SIZE");
String SlectedRange = (String) obj.get("RANGE");
String SlectedSupp = (String) obj.get("SUPPLIER");
// Toast.makeText(getActivity().getApplicationContext(), SlectedName, Toast.LENGTH_SHORT).show();
final Dialog dialog = new Dialog(getActivity());
dialog.getWindow();
//dialog.setTitle("Confirm your Vote");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.diaglog);
final TextView VName = (TextView) dialog.findViewById(R.id.Name);
final TextView VRange = (TextView) dialog.findViewById(R.id.Range);
final TextView VSUPPLIER = (TextView) dialog.findViewById(R.id.Supplier);
final TextView VSIZE = (TextView) dialog.findViewById(R.id.Size);
final TextView VPrice = (TextView) dialog.findViewById(R.id.Price);
VName.setText(SlectedName);
VRange.setText(SlectedRange);
VSUPPLIER.setText(SlectedSupp);
VSIZE.setText(SlectedSize);
VPrice.setText(SlectedPrice);
dialog.show();
Button cancelBtn = (Button) dialog.findViewById(R.id.cancel_btn);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button UpdateBtn = (Button) dialog.findViewById(R.id.btn_update);
UpdateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
}
});
Button deleteBtn = (Button) dialog.findViewById(R.id.btn_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
}
});
dialog.show();
}
});
so i want to pass VName.setText(SlectedName); to a new activity:
name1.setText(dialogactivityname);
Pass in as an extra:
instead of:
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
you should pass in the name
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
i.putExtra("string", SlectedName);
startActivity(i);
Then, on your Upvalence activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Bundle arguments = this.getIntent().getExtras();
String yourString = arguments.getString("string");
}
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);
In my application I am about to refresh the current viewed fragment after searching an item from API. My search bar is coming from Fragment activity and, when the result is there, it will be viewed in the second fragment, but the problem is, when I click search, it will reset into the 1st fragment.
Here's my code:
private ViewPager mPager;
private MyPagerAdapter mAdapter;
ImageView settings_btn;
EditText search;
//EditText search;
ImageView community_icon;
ImageView loyalty_icon;
ImageView tokens_icon;
Context context;
public CustomerAccount customerAccount;
private MyPagerAdapter pagerAdapter;
String offer = "cheese";
ProgressDialog progressDialog;
CustomListAdapterMerchant adapter;
String searchname;
ArrayList<RowItemMerchant> rowItem;
JSONObject offerlist;
int i;
JSONObject merchantList;
RowItemMerchant items;
ListView listView;
Bundle extras;
String empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if(savedInstanceState != null){
search.setText(savedInstanceState.getString("Key"));
}
search = (EditText) findViewById(R.id.searchView);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
ConstantSearch.SEARCHNAME = search.getText().toString();
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.d("SearchName",ConstantSearch.SEARCHNAME);
return true;
}
return false;
}
});
search.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
ConstantSearch.SEARCHNAME = "";
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.e("IME_TEST", "DEL KEY");
}
return false;
}
});
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null) {
String getName = (String) bd.get("IPUTTEDMERCHANT");
search.setText(getName);
}
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
showDialogGPS();
}
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);
final TextView ref1= (TextView) findViewById(R.id.ref1);
final TextView ref2= (TextView) findViewById(R.id.ref2);
final TextView ref3= (TextView) findViewById(R.id.ref);
final ImageView Image1 = (ImageView) findViewById(R.id.image1);
final ImageView Image2 = (ImageView) findViewById(R.id.image2);
final ImageView Image3 = (ImageView) findViewById(R.id.image3);
settings_btn = (ImageView) findViewById(R.id.settings_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent settings = new Intent(DashboardActivity.this, SettingsPromotion.class);
startActivity(settings);
}
});
ref1.setTextColor(ContextCompat.getColor(this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
ref1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
setToDefault();
ref1.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
}
});
loyalty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(1);
setToDefault();
ref2.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image2.setImageResource(R.drawable.ic_loyalty_on);
}
});
tokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(2);
setToDefault();
ref3.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image3.setImageResource(R.drawable.ic_tokens_on);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);{
String savedText = search.getText().toString();
savedInstanceState.putString("Key", savedText);
}
}
private void showDialogGPS() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Allow \"My App\" to access you location while you use tha app?");
builder.setMessage("My App uses this to help customers find places. connect with merchants and more");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void setToDefault()
{
TextView ref1 = (TextView) findViewById(R.id.ref1);
TextView ref2 = (TextView) findViewById(R.id.ref2);
TextView ref3 = (TextView) findViewById(R.id.ref3);
ImageView Image1 = (ImageView) findViewById(R.id.image1);
ImageView Image2 = (ImageView) findViewById(R.id.image2);
ImageView Image3 = (ImageView) findViewById(R.id.image3);
ref1.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image1.setImageResource(R.drawable.ic_community_off);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
private static final int NUM_ITEMS = 3;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
mFragmentTags = new HashMap<Integer, String>();
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragmentThree = new FragmentThree();
}
#Override
public int getCount()
{
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position)
{
if (position == 0)
{
return fragmentOne;
}
else if (position == 1)
{
return fragmentTwo;
}
else if (position == 2)
{
return fragmentThree;
}
else
{
Log.e("AuthActivity", "ViewPager invalid position");
return null;
}
}
}
I have editText in Setup Activity. I used SharedPreference for saving this value and get later. I passed this edittext value to another activity button text. Initially i need to hide the button. If edittext values are coming from sharedPreference i need to display the button.Thanks alot
public class Setup extends Activity implements AdapterView.OnItemSelectedListener {
EditText editText;
Button button;
Spinner spinner;
TextView text;
ArrayList<String> ar = new ArrayList<String>();
// String a=editText.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
button = (Button) findViewById(R.id.button1);
editText = (EditText) findViewById(R.id.ed1);
spinner = (Spinner) findViewById(R.id.spinner1);
text = (TextView) findViewById(R.id.back);
getnameButton();
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ar);
arr.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(arr);
spinner.setOnItemSelectedListener(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("sample", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",editText.getText().toString());
editor.putInt("position",spinner.getSelectedItemPosition());
editor.commit();
Intent myIntent = new Intent(Setup.this, MainActivity.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_setup, menu);
return true;
}
public void getnameButton() {
Intent intent = getIntent();
String text1 = intent.getStringExtra("text1");
String text2 = intent.getStringExtra("text2");
String text3 = intent.getStringExtra("text3");
String text4 = intent.getStringExtra("text4");
String text5 = intent.getStringExtra("text5");
String text6 = intent.getStringExtra("text6");
String text7 = intent.getStringExtra("text7");
String text8 = intent.getStringExtra("text8");
ar.add(text1);
ar.add(text2);
ar.add(text3);
ar.add(text4);
ar.add(text5);
ar.add(text6);
ar.add(text7);
ar.add(text8);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
editText.setText(ar.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
=>Activity Class
public class MainActivity extends Activity {
Button button1,button2,button3,button4,button5,button6,button7,button8;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button) findViewById(R.id.btn1);
button2=(Button) findViewById(R.id.btn2);
button3=(Button) findViewById(R.id.btn3);
button4=(Button) findViewById(R.id.btn4);
button5=(Button) findViewById(R.id.btn5);
button6=(Button) findViewById(R.id.btn6);
button7=(Button) findViewById(R.id.btn7);
button8=(Button) findViewById(R.id.btn8);
textView=(TextView) findViewById(R.id.txtsua);
getName();
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),Setup.class);
intent.putExtra("text1", button1.getText().toString());
intent.putExtra("text2",button2.getText().toString());
intent.putExtra("text3",button3.getText().toString());
intent.putExtra("text4", button4.getText().toString());
intent.putExtra("text5",button5.getText().toString());
intent.putExtra("text6",button6.getText().toString());
intent.putExtra("text7", button7.getText().toString());
intent.putExtra("text8", button8.getText().toString());
startActivity(intent);
}
});
// getnameButton();
}
public void getName() {
button1.setVisibility(View.GONE);
SharedPreferences preferences = getSharedPreferences("sample", 0);
String Namestr = (preferences.getString("Name", ""));
int position = (preferences.getInt("position", Integer.parseInt("")));
for (int i = 0; i < 8; i++) {
Button[] a = {button1, button2, button3, button4, button5, button6, button7, button8};
if (Namestr.length() > 0&&position==i) {
a[i].setVisibility(View.VISIBLE);
a[i].setText(preferences.getString("Name", ""));
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}}