Android integer conversion from EditText failed - java

I'm trying to set a value in a Handler from a Dialog edittext but i get an error. The code is this:
private Button btnstart;
private Button btnstop;
TimePicker myTimePicker;
final static int RQS_1 = 1;
TimePickerDialog timePickerDialog;
Context context;
private int n = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnstart = (Button)findViewById(R.id.btnstart);
btnstart.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
LayoutInflater l = LayoutInflater.from(MainActivity.this);
View dview = l.inflate(R.layout.dialog, null);
AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);
ad.setView(dview);
final EditText edit = (EditText) dview.findViewById(R.id.edit);
String e = edit.getText().toString();
n = Integer.parseInt(e);
ad.setCancelable(false)
.setTitle("Imposta i Secondi")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
Toast.makeText(getApplicationContext(), "Start",Toast.LENGTH_LONG).show();
}
}, n);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alertD = ad.create();
alertD.show();
}
});
the n value, usually could be 3000,4000,5000 or any other value in ms as integer value. So i converted the edit value of edittext in integer but i get an error in the logcat:
Invalid int "" at line n = Integer.parseInt(e); what's wrong here?

You need to move these two lines of code from where they are now to inside the onClick handler of the DialogInterface.OnClickListener.
String e = edit.getText().toString();
n = Integer.parseInt(e);
revised code
private Button btnstart;
private Button btnstop;
TimePicker myTimePicker;
final static int RQS_1 = 1;
TimePickerDialog timePickerDialog;
Context context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnstart = (Button)findViewById(R.id.btnstart);
btnstart.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
LayoutInflater l = LayoutInflater.from(MainActivity.this);
View dview = l.inflate(R.layout.dialog, null);
AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);
ad.setView(dview);
final EditText edit = (EditText) dview.findViewById(R.id.edit);
ad.setCancelable(false)
.setTitle("Imposta i Secondi")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
String e = edit.getText().toString();
int n = Integer.parseInt(e);
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
Toast.makeText(getApplicationContext(), "Start",Toast.LENGTH_LONG).show();
}
}, n);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alertD = ad.create();
alertD.show();
}
});

At what point does your EditText get populated? This is in a create event so it appears that you are trying to extract an integer from an empty string?

int value;
try{
value = Integer.parseInt(stringValue);
}(Execption e){
value = 0; // If edittext contains letters, space, etc
}

First , you should use try catch for formatting numbers.
String e = edit.getText().toString().trim();
if(e!=null && !e.isEmpty())
{
int n ;
try {
n = Integer.valueOf(e);
} catch (NumberFormatException e) {
e.printStackTrace();
n = 0;
}
}
Hope it helps.

Related

Display value to another activity [duplicate]

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

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.

Checkbox-Not selected the Current positon

I am using checkbox in an listview,while click the checkbox it has to select the content in the row.But is not taking taking the current position.But is not select the current positon first and second time is not selecting anything.Is not selecting the current position,Its selecting randomly.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item2);
lv =(ListView)findViewById(R.id.list);
mDbHelper = new GinfyDbAdapter(this);
share = (Button)findViewById(R.id.btnget);
btnadd1 = (Button)findViewById(R.id.btnadd);
lv = getListView();
share.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<mCheckStates.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append("Title:");
result.append(bb.get(i));
result.append("\n");
result.append("Content:");
result.append(aa.get(i));
result.append("\n");
}
}
// }
showAlertView(result.toString().trim());
}
});
btnadd1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createProject();
}
});
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData() {
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
int count = projectsCursor.getCount();
Log.i(".................",""+count);
if (projectsCursor.moveToFirst()) {
do {
int col1 = projectsCursor.getColumnIndex("title");
String title = projectsCursor.getString(col1 );
bb.add(title);
int col2 = projectsCursor.getColumnIndex("content");
String content = projectsCursor.getString(col2 );
aa.add(content);
} while (projectsCursor.moveToNext());
}
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE,GinfyDbAdapter.CATEGORY_COLUMN_CONTENT,GinfyDbAdapter.CATEGORY_COLUMN_DATE};
int[] to = new int[]{R.id.text22,R.id.text11,R.id.date};
dataAdapter = new CustomAdapter (YourPrayerActivity .this, R.layout.row2, projectsCursor, from, to);
setListAdapter(dataAdapter);
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return mDbHelper.fetchProjectByName(constraint.toString());
}
});
tts = new TextToSpeech(this, this);
final ListView lv = getListView();
txtText = (TextView) findViewById(R.id.text11);
lv.setTextFilterEnabled(true);
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//btnaudioprayer.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void createProject() {
Intent i = new Intent(this, AddyourprayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void speakOut() {
// String text = txtText.getText().toString();
// String text = "Android speech";
tts.speak(typed, TextToSpeech.QUEUE_FLUSH, null);
}
class CustomAdapter extends SimpleCursorAdapter implements CompoundButton.OnCheckedChangeListener {
private LayoutInflater mInflater;
private ListView lv;
#SuppressWarnings("deprecation")
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
{
super(context, layout, c, from, to);
mInflater= LayoutInflater.from(context);
mCheckStates = new SparseBooleanArray(c.getCount());
}
#Override
public void bindView(View view, Context context, final Cursor cursor){
if (view != null) {
int row_id = cursor.getColumnIndex("_id"); //Your row id (might need to replace)
TextView tv = (TextView) view.findViewById(R.id.text22);
final TextView tv1 = (TextView) view.findViewById(R.id.text11);
TextView tv2 = (TextView) view.findViewById(R.id.date);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
int col1 = cursor.getColumnIndex("title");
final String title = cursor.getString(col1 );
int col2 = cursor.getColumnIndex("content");
final String content = cursor.getString(col2 );
int col3 = cursor.getColumnIndex("date");
final String date = cursor.getString(col3);
cb.setTag(cursor.getPosition());
cb.setChecked(mCheckStates.get(cursor.getPosition()+1, false));
cb.setOnCheckedChangeListener(this);
tv.setText( title);
tv1.setText( content);
tv2.setText(date);
ImageButton button = (ImageButton) view.findViewById(R.id.sms1);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
StringBuffer sb2 = new StringBuffer();
sb2.append("Title:");
sb2.append(Html.fromHtml(title));
sb2.append(",Content:");
sb2.append(Html.fromHtml(content));
sb2.append("\n");
String strContactList1 = (sb2.toString().trim());
sendsmsdata(strContactList1);
}
});
ImageButton button1 = (ImageButton) view.findViewById(R.id.mail1);
button1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
StringBuffer sb3 = new StringBuffer();
sb3.append("Title:");
sb3.append(Html.fromHtml(title));
sb3.append(",Content:");
sb3.append(Html.fromHtml(content));
sb3.append("\n");
String strContactList2 = (sb3.toString().trim());
sendmaildata(strContactList2);
}
});
ImageButton button2 = (ImageButton) view.findViewById(R.id.btnaudioprayer1);
button2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//ADD STUFF HERE you know which row is clicked. and which button
typed = content;
speakOut();
}
});
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.row2, parent, false);
bindView(v,context,cursor);
return v;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
while click the checkbox,and then after have to click share button it will shows sms or email,if we click sms,in that content what are the things we checked that content has to be there in msg content.
I checked in debug,if i select the first or second row its taking or otherwise if i selected thirdrow first its not taking the content.
Have a count variable as a class member
int count;
Then in fillData
count = projectsCursor.getCount();
SO when you click on a button
StringBuilder result = new StringBuilder();
if(count>0) // check if count is greater than o
// count can be 0 if you don't select any check box
{
for(int i=0;i<count;i++)
{Log.i("checked content Inside on click of share ",""+aa.get(i));
if(mCheckStates.get(i)==true)
{
result.append("Title:");
result.append(bb.get(i));
result.append("\n");
result.append("Content:");
result.append(aa.get(i));
result.append("\n");
}
}
}
You are using a SparseBoolean array which is true for row that you check. Then you retrieve the data based on the checked items.
Here's the sample from which i picked upon
https://groups.google.com/forum/#!topic/android-developers/No0LrgJ6q2M
What you were doing is you were not going through the whole list of items to check if the checkbox was checked.
for(int i=0;i<mCheckStates.size();i++) // this was the problem
if only two items are checked you will get the first two.
To avoid the problems with CheckBoxes in a ListView you can take a Boolean array initialized false in the beginning and then making true the corresponding position in the array where checkbox is checked in the ListView.Please refer to this demo here:
Android checkbox multiselected issue
Why not you use arrayAdapter?
Have a look at this link. Hope it helps you out.
< http://androidcocktail.blogspot.in/2012/04/adding-checkboxes-to-custom-listview-in.html>
As the behavior or getview() method that it recreate view everytime whenever you scroll, so have to maintain position using setTag & getTag, even store selected checked into array with proper position.
Try below example, you can replace toggle button with check box.
Getview Method Wierd in Listview

Output string variable value from EditText into a message box

I am trying to input a number into a EditText, then output it in a message/AlertDialog after click a button. So far I have coded up what I think should work to output it, but for some reason, it doesn't. At the moment, the only output I recieve from the message box, is the text that I specified: "saved". There is no value from the variable being displayed.
Hopefully someone will be able to see what I am doing wrong and find a solution.
Thanks
Code below:
Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText inputTxt1 = (EditText) findViewById(R.id.yourPhoneNum);
String phoneNum1 = inputTxt1.getText().toString();
savenum1(phoneNum1);
}
});
public void savenum1(String phoneNum1) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Saved" + phoneNum1);
//dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
dlgAlert.create().show();
}
Create a private field EditText inputTxt1;
Before Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
get the EditText id: inputTxt1 = (EditText) findViewById(R.id.yourPhoneNum);
At saveBtn1.setOnClickListener
get the phoneNum1: String phoneNum1 = inputTxt1.getText().toString();
Call savenum1 with phoneNum1: savenum1(phoneNum1);
Remove from savenum1:
EditText inputTxt1 = (EditText) findViewById(R.id.yourPhoneNum);
String phoneNum1 = (String) inputTxt1.getText().toString();
Code after correction:
public class SettingsScreen extends Activity {
private EditText inputTxt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_settings);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
EditText inputTxt1 = (EditText) findViewById(R.id.yourPhoneNum);
Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNum1 = inputTxt1.getText().toString();
savenum1(phoneNum1);
}
});
}
public void savenum1(String phoneNum1) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Saved" + phoneNum1);
//dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
dlgAlert.create().show();
}

Android - Can't get value from EditText inside Custom Dialog

I have been unsuccessful in getting the input from my EditText object inside my custom dialog.
public class SetCityDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View view = factory.inflate(R.layout.city_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.city_dialog, null))
// Add action buttons
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//This is the input I can't get text from
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
//query is of the String type
query = inputTemp.getText().toString();
newQuery();
getJSON newData = new getJSON();
newData.execute("Test");
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
SetCityDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
I don't get any exceptions, but the variable query is set to an empty string.
Any help would be fantastic.
I was trying to do the same thing and i get the same error. I don't no why. I already use AlertDialog.Builder in the past and get no trouble. But in your case change this code:
public void onClick(DialogInterface dialog,
int id) {
//This is the input I can't get text from
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
//query is of the String type
query = inputTemp.getText().toString();
newQuery();
getJSON newData = new getJSON();
newData.execute("Test");
}
By this one:
public void onClick(DialogInterface dialog,
int id) {
Dialog f = (Dialog) dialog;
//This is the input I can't get text from
EditText inputTemp = (EditText) f.findViewById(R.id.search_input_text);
query = inputTemp.getText().toString();
...
}
This solution works for me and it seems to be the same for you.
Found on stackoverflow
Use this instead :
View myLayout = nflater.inflate(R.layout.city_dialog, null);
EditText myEditText = (EditText) myLayout.findViewById(R.id.myEditText);
String valueOfEditText = myEditText.getText().toString();
No need to do that much coding. just change
builder.setView(inflater.inflate(R.layout.city_dialog, null))
to
builder.setView(view)
and access text of EditText using **view.findView.....
EditText inputTemp = (EditText) view.findViewById(R.id.search_input_text);
String xyz = inputTemp.getText().toString();
This is worked for me:
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Dialog inDialog = (Dialog) dialog;
EditText emailAddress = (EditText) inDialog.findViewById(R.id.emailAddress);
email = emailAddress.getText().toString();
if(email.length() == 0) {
objPublicDelegate.showToast("Please fill Email Address.");
}else{
objLoadingDialog.show("Please wait...");
// Call a network thread Async task
mNetworkMaster.runForgetAsync(email);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

Categories