button is called twice with performClick() - android

I have a ImageButton plus. When click i need to do a inflate of a view.
My problem is that when i use performClick the Imagebutton is called twice, and execute two inflates simultaneously.
I don't why this happens.
Here is a little of my code:
private ImageButton addPhone;
addPhone = (ImageButton)view.findViewById(R.id.ac_ibAddClientPhone);
addPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inflationFields = new InflatationFields(getActivity());
inflationFields.inflateNewField("phone", containerPhone, view, adapterPhone);
}
});
and in another part of the code i call the button and try to click with perform click
try{
if(ccPhone.moveToFirst())
do{
if(flag_first==true){
phone = ccPhone.getString(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(ClientEditContact.class.getName(), "PHONE: " +phone);
type = ccPhone.getInt(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
etPhone = (EditText)viewPrincipal.findViewById(R.id.ac_etAddClientPhone);
etPhone.setText(phone + "" +etPhone.getTag().toString());
spPhone.setSelection(convertTypeToIdSpinner(type));
flag_first=false;
}
else if(flag_first == false){
addPhone.performClick();
phone = ccPhone.getString(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
type = ccPhone.getInt(ccPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
etPhone = (EditText)viewContainerPhone.findViewWithTag("etTagPhone" + count);
etPhone.setText(phone + "" + etPhone.getTag().toString());
count = count + 1;
if(count==ccPhone.getCount()){
break;
}
}
}while(ccPhone.moveToNext());
Log.d(ClientEditContact.class.getName(), "LAST PHONE ---> " +phone);
}finally{
if(ccPhone != null && ! ccPhone.isClosed()){
ccPhone.close();
}
}
Anyone have any idea?

Double check the part of code from where you are calling addPhone.performClick();. May be that part is getting called twice.

Kind of late, but the system calls performClick() on its own when the button is clicked so you shouldnt use it in your code.

Related

how to add counter in android studio to quit an application

I am getting an error when I set the counter to subtract and close the application. I get an error "cannot assign value to final variable counter". If the user logins in 3 times with no success quit the application.
final int counter = 3;
//Set the OKButton to accept onClick
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
//display text that was inputed for userText and passText
user = userText.getText().toString();
pass = passText.getText().toString();
//create if loop which checks if user and pass equals the credentials
if (user.equals("pshivam") && pass.equals("Bway.857661")) {
//display toast access welcome
String welcome = "Access Granted.";
//Create a Toast to display the welcome string in the MainActivity.
Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show();
setContentView(R.layout.account_main);
}
//create else if loop which checks if user or pass does not equals the credentials
else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){
//displays previous entry
userText.setText(user);
passText.setText(pass);
//allows user to re-enter credentials.
user = userText.getText().toString();
pass = passText.getText().toString();
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
}
});
}
}
Do something like this :
OKButton.setOnClickListener(new View.OnClickListener() {
int counter = 3;
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
You can also call a function from inside onClick which will decrement the variable, or use a static field declared in your class
This How to increment a Counter inside an OnClick View Event and How do I use onClickListener to count the number of times a button is pressed? might help.
Edit:
What you are doing in else part doesn't make sense. You are setting text for userText and passText that you just got using getText() from these. Then you are storing these same values to user and pass. But you aren't using these variables anywhere and they get new values when onClick is called again. Why not keep it simple :
else {
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}

How to make an async button click update a TextView dynamically with Xamarin Android

In Xamarin Native Android app I am calling methodOne() and getting some details. After this I want to updated the details to text view and then calls the methodTwo(). After executing MethodTwo I have to clear the text details from text view. I tried with
RunOnUiThread(() => tColorDetail.SetText("text", TextView.BufferType.Normal));
The details are displaying after finishing all the methods it is not showing immediately after executing MethodOne().
What is missing here?
.....................................................
public class MainActivity : Activity
{
int count = 1;
ticket Ticket;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button bClick= FindViewById<Button>(Resource.Id.bSub);
try {
bClick.Click += delegate {
Job Job;
Action act = new Action();
EditText Address = (EditText)FindViewById(Resource.Id.Address);
act.Address = Address.Text.ToString();
if (!ValidateIPv4(act.Address))
{
ShowMessage("Invalid IP");
}
else
{//TextView Mode = (TextView)FindViewById(Resource.Id.Mode);
string httpUrl = act.iPAddress ;
Ticket = act.ExecuteTicket(httpUrl, "Ticket");
//RunOnUiThread(() => tColorMode.SetText("text", TextView.BufferType.Normal));
// this.RunOnUiThread(() => setTicket(true));
setStatus(" Ticket : Success", true);
setTicket(true);
//tColorMode.SetText("text",TextView.BufferType.Normal);
//tColorMode.Invalidate();
Job = act.executeJob(httpUrl, Ticket);
setStatus(" Job : Success", true);
act.File(httpUrl, Ticket, Job);
setStatus("File Retrieval : Success", true);
setTicket(false);
setStatus("File Retrieval : Success", false);
}
};
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString());
}
}
public bool ValidateIPv4(string ipString)
{
if (String.IsNullOrWhiteSpace(ipString))
{
return false;
}
string[] splitValues = ipString.Split('.');
if (splitValues.Length != 4)
{
return false;
}
return true;
}
public void setTicket(bool b)
{
//TextView tMode = (TextView)FindViewById(Resource.Id.tMode);
// tMode.SetText("text",TextView.BufferType.Normal);
RunOnUiThread(() => {
TextView tMode = (TextView)FindViewById(Resource.Id.Mode);
tColorMode.SetText("text",TextView.BufferType.Normal);// b==true?Ticket.getProcessing():"";
((TextView)this.FindViewById(Resource.Id.tRes)).Text = b == true ? Ticket.getHeight().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tFormat)).Text = b == true ? Ticket.getFormat().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tOrode)).Text = b == true ? Ticket.getType().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tRot)).Text = b == true ? Ticket.getValue().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tSource)).Text = b == true ? Ticket.getSource().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tSize)).Text = b == true ? Ticket.getAutoDetect().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tExpo)).Text = b == true ? Ticket.getAuto().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tSharp)).Text = b == true ? Ticket.getSharp().ToString() : "";
((TextView)this.FindViewById(Resource.Id.tComp)).Text = b == true ? Ticket.getComp().ToString() : "";
//tColorMode.Invalidate();
}); }
private void ShowMessage(string msg)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog = builder.Create();
dialog.SetMessage(msg);
dialog.SetButton("OK", (s, ev) =>
{
dialog.Cancel();
});
dialog.Show();
}
private void setStatus(string status,bool b)
{
((TextView)this.FindViewById(Resource.Id.tStatus)).Text = b == true ? status : " ";
}
}
Without access to the full code it is tricky to give you an answer but
Ticket = act.ExecuteTicket(httpUrl, "Ticket");
this line has the potential to take a while to complete if it performs network operations and probably runs in a background thread not to freeze the UI.
Presumably when you get to
// this.RunOnUiThread(() => setTicket(true));setStatus(" Ticket : Success", true);
setTicket(true);
the act.ExecuteTicket call might not have finished
also if there are async operations taking place in
Job = act.executeJob(httpUrl, Ticket);
it could take a while to complete
All taken into consideration, you could probably be getting to
setTicket(false);
setStatus("File Retrieval : Success", false);
before the first calls finish
It could be worth checking
ANSWER UPDATE after discussion in comments:
Since your problem is that your asynchronous calls are taking a long time and you are experiencing "race conditions" because of it (your UI thread is proceeding with the updates on the TextViews before it should), you can solve the situation by changing your button click delegate to an async delegate, and forcing an await on the long operations' result before proceeding.
bClick.Click += async delegate {
//...
Job = await act.executeJob(httpUrl, Ticket);
//...
}

comparing two strings in Android ( if-else statemente)

I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
else ///////Display a warning message: Try again
}
when I run this code this only executes the else part. why its not executing the if part? what should I do ?
The reason is that you are fetching the EditText's value while declaring the EditText. Actually you nee to fetch the Text from EditText while clicking on the button, hence you need to move you code to onClick() method like below,
#Override
public void onClick (View view)
{
String u = un.getText().toString();
String p = pw.getText().toString();
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
{
....
}
else ///////Display a warning message: Try again
{
....
}
}
please try this:
public void onClickL (View view){
u = un.getText().toString();
p = pw.getText().toString();
if ( u.equals("Android") && p.equals("1234") ) /////// move to a new activity
{
}
else ///////Display a warning message: Try again
{
}
}
try Following code
need to clear space in username if it is available.
public void onClick (View view){
String username = un.getText().toString().trim();
String password = pw.getText().toString();
if ((username.equals("Android")) && (password.equals("1234"))) {
//do something
} else{
//do something
}
}
Try this..
get the text inside Click function like below
public void onClick (View view){
String u = un.getText().toString().trim();
String p = pw.getText().toString().trim();
if ((u.equals("Android")) && (p.equals("1234"))) {
//do something
}
else{
//do something
}
}

Show DialogBox in loop in android

I am trying to show dialog boxes with contents from the database .The fetched data from the database may contain more than 1 data.So I have to show dialog in for loop.But the dialog shows only for the first row in the database.Here is the code
cursor = sqldb.query(Database_Handler.dbdectab, null,"((" + Database_Handler.gendtime + "<='" + after_1hr + "' and " + Database_Handler.gendtime + ">='" + before_1hr + "') and ("
+ Database_Handler.calused + "='Gregorian' or " + Database_Handler.calused + "='both')) ", null, null, null, null);
notif_count = cursor.getCount();
//dec_name_ctr_builder = new StringBuilder("");
if(notif_count>0)
{
dialog1 = new Dialog(this);
cursor.moveToFirst();
do
{
dec_name =cursor.getString(cursor.getColumnIndex(Database_Handler.decname));
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.custom_dialog_alert);
TextView tv_alert = (TextView)dialog1.findViewById(R.id.txt_alert);
tv_alert.setText( dec_name );
Button yes = (Button) dialog1.findViewById(R.id.btn_yes);
Button no = (Button) dialog1.findViewById(R.id.btn_no);
yes.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(donateurl));
startActivity(intent);
dialog1.dismiss();
cursor.close();
sqldb.close();
finish();
}
});
no.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
dialog1.dismiss();
cursor.close();
sqldb.close();
finish();
}
});
dialog1.show();
}while(cursor.moveToNext());
Android dialog boxes are not modal (which is to say, they don't block the background processes).Hence your work is done asycnhronuosly and according to :
Romain guy
We've designed Android to prevent developers from writing synchronous dialogs so you don't really have much of a choice.
SO you can not block the while loop execution in between using Dialog.
Karan_Rana is right. The simplest solution for your answer would be storing the results somewhere else and displaying a new dialog each time some data is left and user clicks on a previous dialogs button.
I know this is a bit late, but I had a similar problem once. I used recursion to loop a dialog box. My situation was unique as I needed to detect an internet connection during app startup. So, this approach may not work for you. But I was able to implement the solution without for loops and blocking the main UI thread. Because I was on a splash screen, there was no other UI I needed to contend so I would simple call the dialog box again until the user chooses to "Quit".
I had a splash screen that would only continue to the landing activity of the app if a network connection was detected.
Sample code below to demonstrate the concept. Note that there are custom methods, but you should get the idea to call the prompt again from within onClick method.
protected void onCreate(Bundle savedInstanceState) {
if (isNetworkAvailable()) {
launchApp();
} else {
retryPrompt();
}
}
private void retryPrompt() {
if (isNetworkAvailable()) {
launchApp();
} else {
final ConfirmDialog dialog = new ConfirmDialog.CustomAlertBuilder(this,
"Internet Connection",
"Internet Connection not detected. Please check your connection.",
"Retry").
setNegBtnLabel("Quit").
setCustomCallback(new CustomDialogCallback() {
#Override
public void onClickPositiveBtn(DialogInterface dialogInterface, int which) {
// go around again.
retryPrompt(); // <<== Call method recursively
}
#Override
public void onClickNegativeBtn(DialogInterface dialogInterface, int which) {
// abort app.
finish();
}
}).build();
dialog.show();
}
}

Android - How to check if textview is null or not null

I have some textview in my application
and want to check whether the properties of text on my textview has a value or null.
then i want to display a toast if the value on my textview null
but the toast is not running as it should
this is my code :
public class brekeleV2 extends Activity {
static Context context;
brekeleV2Model r = new brekeleV2Model();
private EditText jalan, kota, postal;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
Button go = (Button)findViewById(R.id.go);
go.setOnClickListener(onGo);
Button reset = (Button)findViewById(R.id.reset);
reset.setOnClickListener(onRes);
jalan =(EditText)findViewById(R.id.jalan);
kota =(EditText)findViewById(R.id.kota);
postal =(EditText)findViewById(R.id.post);
jalan.setText(null);
kota.setText(null);
postal.setText(null);
}
and this is the onClick method code:
private View.OnClickListener onGo=new View.OnClickListener() {
public void onClick(View v) {
if (jalan.getText()!= null && kota.getText()!=null){
switch(v.getId()){
case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.brekele", "com.openit.brekele.brekeleV2Nav");
brekeleV2Nav.putLatLong(lat, lon);
startActivity(maps);
break;
}
}else{
Toast msg = Toast.makeText(brekeleV2.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
if(!textview.getText().toString.matches(""))
{
// not null not empty
}else {
//null or empty
}
This is what I would use.
if (mText1.getText().length() > 0 && mText2.getText().length() > 0) {
// Your code.
}
in the end i found my problem solving. here is my code:
if (jalan.getText().toString().length()>0 || kota.getText().toString().length()>0){
//switch(v.getId()){
//case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.razer", "com.openit.razer.mapRazerNav");
mapRazerNav.putLatLong(lat, lon);
startActivity(maps);
//break;
//}
}else{
Toast msg = Toast.makeText(razerNav.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
i used to check the length, because on my xml i add like this :
android:text=" "
see? this is my fault.
anyway thanks for helping me. :)
TextView has a public length() method you can use to check if there are any characters in the TextView.
if (textView.length() > 0) {
// textView is not null
} else {
// textView is null
}
Try textView.getText() != "" instead.
Are you sure that the else condition is invoked? Debug it!
Maybe you need to put the toast into a runOnUiThread statement:
runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
Method getText() in TextView returns EditAble that cant compare with String
you should convert EditAble to String using String.ValueOf() method.
String jalanContent = String.ValueOf(jalan.getText());
if(jalanContent.equals(""){
//do your action here
} else {
//some action here
}
hope it'd be usefull
if (jalan.getText()!= null && kota.getText()!=null)
This is the line of code that doesn't work for you.
Best solution for such scenario is using matches("") method for String
So the solution will be:
if (!jalan.getText().toString.matches("") && !kota.getText().toString().matches("")){
// code for not null textViews
}
else
{
//Code for nul textView
}
I would have modified the correct answer a bit (missing () after toString but we're not allowed edit code so:
if(textview.getText().toString().matches(""))
{
// is null or empty
}else {
//not null or empty
}

Categories

Resources