btn.performClick()无法自动触发按钮

时间:2016-03-11 05:46:43

标签: java android

我想在OTP到达后立即触发按钮并在edittext区域字段中设置。 OTP成功设置但是提交按钮本身没有被触发。我哪里错了?这是我的代码。

OTP.java

package com.nrb.app.nrb.otp;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.nrb.app.nrb.HomeScreen;
import com.nrb.app.nrb.QRresponse.MyDBHelper;
import com.nrb.app.nrb.QRresponse.ServiceCalls;
import com.nrb.app.nrb.QRscanapi.RM;
import com.nrb.app.nrb.R;
import com.nrb.app.nrb.intera.AsyncResponseActivity;
import com.nrb.app.nrb.intera.ConnectionDetectorActivity;
 import com.nrb.app.nrb.login.RegisterValidation;
import com.nrb.app.nrb.login.SignInActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

   import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;


public class OTP extends FragmentActivity implements View.OnClickListener {

private Hashtable<String, String> verifiedResponseKeyValue = new Hashtable<String, String>();
private Hashtable<String, String> verifiedNestedResponseKeyValue = new Hashtable<String, String>();
private String userMobValue;
private String otpVerUrl;
private String userNameValue;
private String userEmailValue;
private String userCountryValue;
private String userId;
private MyDBHelper myDBHelper;
private String userCountryCode;
private boolean timeOut;
static EditText OtpNumber;
private ConnectionDetectorActivity cd;
private String user_exist;
private Button OTP;
Context cntx;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    cntx=this;
    OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
    cd = new ConnectionDetectorActivity(OTP.this);
    Bundle bundle = getIntent().getExtras();
    userId=bundle.getString("id");
    userEmailValue = bundle.getString("userEmailValue");
    userMobValue = bundle.getString("userMobValue");
    userNameValue = bundle.getString("userNameValue");
    userCountryValue = bundle.getString("userCountryValue");
    userCountryCode = bundle.getString("userCountryCode");
    user_exist = bundle.getString("user_exist");
    registerViews();
}

public void registerViews() {
    OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
    // TextWatcher would let us check validation error on the fly
    OtpNumber.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            RegisterValidation.isName(OtpNumber, false);
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    });

  /*  OtpNumber.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                OTP.performClick();
                return true;
            }
            return false;
        }
    });*/
}

private boolean checkValidation() {
    boolean ret = true;
    if (!RegisterValidation.isName(OtpNumber, true))
    ret = false;
    return ret;
}

@SuppressLint("InflateParams")
private void popUpDialog(String result1, final boolean newuser) {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
    // Get the layout inflater
    LayoutInflater inflater = OTP.this.getLayoutInflater();

    View content = inflater.inflate(R.layout.otp_verification_dialog, null);

    TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
    tv.setText(result1);

    builder.setView(content);
    builder.setCancelable(false);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
    content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    // TODO Auto-generated method stub
                    alertDialog.dismiss();
                    if (newuser) {
                        Bundle bundle = new Bundle();
                        bundle.putString("defaultFrag", "newUserFrag");
                        Intent i = new Intent(OTP.this, HomeScreen.class);
                        i.putExtras(bundle);
                        startActivity(i);
                        setResult(10);
                        finish();

                    }
                    else{
                        Toast.makeText(cntx, "Please enter Valid OTP", Toast.LENGTH_LONG).show();
                        OtpNumber.setText("");
                    }
                }
            });
}

@SuppressLint("InflateParams")
private void popUpDialogSuccess(Spannable result1) {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
    // Get the layout inflater
    LayoutInflater inflater = OTP.this.getLayoutInflater();

    View content = inflater.inflate(R.layout.otp_verification_dialog, null);

    TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
    tv.setText(result1);

    builder.setView(content);
    builder.setCancelable(false);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
    content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    alertDialog.dismiss();
                    insertUserPfref();
                }

            });
}

public void verifyOTPKEY(View v) {
    if (checkValidation()){

        EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
        RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
        RM.OTP_MOB_VALUE = userMobValue;

        if (user_exist.compareTo("true") == 0)
            RM.OTP_USER_EXIST_VALUE = "true";
        else
            RM.OTP_USER_EXIST_VALUE = "false";

        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
            jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
            jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
            jsonObject.put(RM.USER_Id_KEY,userId);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("==", "========= FAIL TO CREATE JSON ==========");
        }

        ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
                jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {

            @Override
            public void myAsyncResponse(String result) {
                // TODO Auto-generated method stub
                Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
                Log.d("====>>>>", result);
                parseOTPRsponseJason(result);
                Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
            }
        });
        if (cd.isConnectingToInternet()) {
            Login.execute(1);

        } else {
            showNetworFailDialog(RM.NO_INTERNET_MSG);
        }
    }
    else{
        Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
    }
}

   @Override
public void onClick(View v) {

}

class MyOTPAsyncTask extends AsyncTask<Void, Void, String> {

    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

        super.onPreExecute();
        dialog = new ProgressDialog(OTP.this);
        dialog.setMessage("Authenticating...");
        dialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(otpVerUrl);

        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();
        } catch (Exception e) {
            timeOut = true;
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        dialog.dismiss();
        // popUpDialog(result);
        if (!timeOut)
            parseOTPRsponseJason(result);
        else
            showNetworFailDialog(RM.REQ_TIMEOUT_MSG);
        Log.d("----->", "      Response     " + result);
    }

}

private void parseOTPRsponseJason(String result) {
    // TODO Auto-generated method stub
    JSONObject json;
    JSONObject nestedJson;
    try {
        json = new JSONObject(result);
        Iterator<String> iter = json.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = json.get(key);

            if (user_exist.compareTo("true") == 0) {
                if (key.compareTo("responseHash") == 0) {
                    nestedJson = new JSONObject(json.get(key).toString());
                    Iterator<String> nestedIter = nestedJson.keys();
                    while (nestedIter.hasNext()) {
                        String nestedKey = nestedIter.next();
                        Object nestedValue = nestedJson.get(nestedKey);
                        verifiedNestedResponseKeyValue.put(nestedKey,
                                nestedValue.toString());
                    }
                }
            }
            verifiedResponseKeyValue.put(key, value.toString());

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        Set<String> hKeys2 = verifiedResponseKeyValue.keySet();
        for (String string : hKeys2) {
            Log.d("====>",
                    string + " ==>" + verifiedResponseKeyValue.get(string));
        }

        String x = verifiedResponseKeyValue.get("success");

        if (x.compareTo("true") == 0) {

            if (user_exist.compareTo("true") == 0) {
                userNameValue = verifiedNestedResponseKeyValue.get("name");
                Spannable wordtoSpan = new SpannableString("HI "
                        + userNameValue + " , Welcome back to Onspot");
                wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 3,
                        3 + userNameValue.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                popUpDialogSuccess(wordtoSpan);
            } else {
                Spannable wordtoSpan = new SpannableString(
                        "Congratulations! " + userNameValue
                        + " , you are successfully registered.");
                wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 17,
                        17 + userNameValue.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                popUpDialogSuccess(wordtoSpan);
            }
        } else
            popUpDialog(
                    verifiedResponseKeyValue.get("responseMessage"), false);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.d("====>", "Exception");
        popUpDialog(RM.CrashError, false);
    }

}

private void insertUserPfref() {
    // TODO Auto-generated method stub

    myDBHelper = new MyDBHelper(OTP.this);
    myDBHelper.getWritableDatabase();

    if (user_exist.compareTo("true") == 0) {

        try {
            myDBHelper.insertRegisteredUser(
                    verifiedNestedResponseKeyValue.get("email"), //
                    verifiedNestedResponseKeyValue.get("mobile_number"),//
                    verifiedNestedResponseKeyValue.get("name"), //
                    verifiedNestedResponseKeyValue.get("country"),
                    //
                    verifiedNestedResponseKeyValue.get("country_code"));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("====>", "Exception");
            popUpDialog(RM.CrashError, false);
        }

        Log.d("------>", "Existing USER");
        Log.d("------>", "Existing USER" + user_exist);

    } else {
        myDBHelper.insertRegisteredUser(userEmailValue,//
                userMobValue,//
                userNameValue, //
                userCountryValue,//
                userCountryCode);
        Log.d("------>", "New User");
        Log.d("------>", "New User" + user_exist);
    }

    Log.d("------>", user_exist);
    startActivity(new Intent(OTP.this, HomeScreen.class));
    setResult(10);
    finish();
}



@SuppressLint("InflateParams")
private void showNetworFailDialog(String msg) {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
    // Get the layout inflater
    LayoutInflater inflater = OTP.this.getLayoutInflater();
    View content = inflater.inflate(R.layout.network_failure_dialog, null);
    builder.setView(content);
    builder.setCancelable(false);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
    TextView tvMsg = (TextView) content.findViewById(R.id.networkFailMsg);
    tvMsg.setText(msg);
    content.findViewById(R.id.btnNetworkFailureOK).setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    alertDialog.dismiss();
                    setResult(10);
                    finish();
                }
            });
}

@Override
public void onBackPressed() {
    Intent i = new Intent(OTP.this, SignInActivity.class);
    startActivity(i);
    setResult(10);
    finish();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    return true;
}

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

public void recivedSms(String message)
{
    try
    {
        int pos=message.indexOf(':');
        String msg = message.substring(pos + 2);
        OtpNumber.setText(msg);
        OTP = (Button) findViewById(R.id.btnOTPVerify);
        OTP.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Do something in response to button click
            }
        });
        OTP.performClick();
        OTP.setPressed(true);
  /*      if(OtpNumber!=null) {
            if (checkValidation()) {

                EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
                RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
                RM.OTP_MOB_VALUE = userMobValue;

                if (user_exist.compareTo("true") == 0)
                    RM.OTP_USER_EXIST_VALUE = "true";
                else
                    RM.OTP_USER_EXIST_VALUE = "false";

                JSONObject jsonObject = new JSONObject();
                try {

                    jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
                    jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
                    jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
                    jsonObject.put(RM.USER_Id_KEY, userId);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("==", "========= FAIL TO CREATE JSON ==========");
                }

                ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
                        jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {

                    @Override
                    public void myAsyncResponse(String result) {
                        // TODO Auto-generated method stub
                        Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
                        Log.d("====>>>>", result);
                        parseOTPRsponseJason(result);


                        Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
                    }
                });
                if (cd.isConnectingToInternet()) {
                    Login.execute(1);

                } else {
                    showNetworFailDialog(RM.NO_INTERNET_MSG);
                }
            } else {
                Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
            }
        }*/
    }
    catch (Exception e)
    {

    }
}
}

IncomingMsg.java

package com.nrb.app.nrb.otp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * Created by Neha on 07-03-2016.
 */
public class IncomingMsg extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent)
    {
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null)
            {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++)
                {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber ;
                    String message = currentMessage.getDisplayMessageBody();
                    try
                    {
                        if (senderNum.equals("DZ-Onspot"))
                        {
                            OTP Sms = new OTP();
                            Sms.recivedSms(message );
                        }
                    }
                    catch(Exception e){}
                }
            }
        } catch (Exception e)
        {

        }
    }

}

activity_otp.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ripple="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="25dp"
android:gravity="center"
android:orientation="vertical"
android:background="#fff"
android:padding="10dp" >

     <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/onspot" />

   <EditText
    android:id="@+id/etOTPVerifaction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:inputType="textCapCharacters"

    android:ems="10"
    android:hint="Enter Verification Key"
    android:maxLength="10"
    android:singleLine="true">

</EditText>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:gravity="center_horizontal"
    android:orientation="horizontal"
    android:padding="5dp"
    android:onClick="verifyOTPKEY">

    <com.andexert.library.RippleView
        android:id="@+id/ripple1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:rv_rippleDuration="200"
        app:rv_type="rectangle" >

        <Button
            android:id="@+id/btnOTPVerify"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_shadow"
            android:text="SUBMIT"
             android:onClick="verifyOTPKEY"
            android:textColor="@color/white" />
    </com.andexert.library.RippleView>
    </LinearLayout>

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
     android:onClick="verifyOTP"
    android:text="Enter Verification key For Login"
    android:textAppearance="?android:attr/textAppearanceSmall" />

2 个答案:

答案 0 :(得分:0)

您将其设置为什么都不做。你应该注释掉这些

 OTP.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
         // Do something in response to button click
     }
 });

答案 1 :(得分:0)

您是否曾尝试将performClick置于此Runnable内,

OTP.post(new Runnable(){
            @Override
            public void run() {
                 OTP.performClick();
            }
      });

使用视图树观察器,用于注册可以在视图树中通知全局更改的侦听器,这在api比16

更高级别有效
ViewTreeObserver vt = OTP.getViewTreeObserver();
vt.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        vt.removeOnGlobalLayoutListener(this);
        OTP.performClick();
    }
});