android studio error after run application - java

When I run the application and log in the user data does not appear in the Dashboard and after modifying the code get this error
error: method loginUser in class SessionHandler cannot be applied to given types;
required: String,String,String
found: String,String
reason: actual and formal argument lists differ in length
how i can fix this error ?
Login Act Class
package com.androidigniter.loginandregistration;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
private static final String KEY_STATUS = "status";
private static final String KEY_MESSAGE = "message";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMPTY = "";
private EditText etUsername;
private EditText etPassword;
private String username;
private String password;
private ProgressDialog pDialog;
private String login_url = "http://192.168.1.102/member/login.php";
private SessionHandler session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionHandler(getApplicationContext());
if(session.isLoggedIn()){
loadDashboard();
}
setContentView(R.layout.activity_login);
etUsername = findViewById(R.id.etLoginUsername);
etPassword = findViewById(R.id.etLoginPassword);
Button register = findViewById(R.id.btnLoginRegister);
Button login = findViewById(R.id.btnLogin);
//Launch Registration screen when Register Button is clicked
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
finish();
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Retrieve the data entered in the edit texts
username = etUsername.getText().toString().toLowerCase().trim();
password = etPassword.getText().toString().trim();
if (validateInputs()) {
login();
}
}
});
}
/**
* Launch Dashboard Activity on Successful Login
*/
private void loadDashboard() {
Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
startActivity(i);
finish();
}
/**
* Display Progress bar while Logging in
*/
private void displayLoader() {
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Logging In.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
private void login() {
displayLoader();
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, login_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got logged in successfully
if (response.getInt(KEY_STATUS) == 0) {
session.loginUser(username,response.getString(KEY_FULL_NAME));
loadDashboard();
}else{
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
/**
* Validates inputs and shows error if any
* #return
*/
private boolean validateInputs() {
if(KEY_EMPTY.equals(username)){
etUsername.setError("Username cannot be empty");
etUsername.requestFocus();
return false;
}
if(KEY_EMPTY.equals(password)){
etPassword.setError("Password cannot be empty");
etPassword.requestFocus();
return false;
}
return true;
}
}
sessionhandler class
package com.androidigniter.loginandregistration;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Date;
/**
* Created by AndroidIgniter on 23 Mar 2019 020.
*/
public class SessionHandler {
private static final String PREF_NAME = "UserSession";
private static final String KEY_USERNAME = "username";
private static final String KEY_EXPIRES = "expires";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_CARD_ID = "cardid";
private static final String KEY_EMPTY = "";
private Context mContext;
private SharedPreferences.Editor mEditor;
private SharedPreferences mPreferences;
public SessionHandler(Context mContext) {
this.mContext = mContext;
mPreferences = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
this.mEditor = mPreferences.edit();
}
/**
* Logs in the user by saving user details and setting session
*
* #param username
* #param fullName
* #param cardid
*/
public void loginUser(String username, String fullName , String cardid) {
mEditor.putString(KEY_USERNAME, username);
mEditor.putString(KEY_FULL_NAME, fullName);
mEditor.putString(KEY_CARD_ID, cardid);
Date date = new Date();
//Set user session for next 7 days
long millis = date.getTime() + (7 * 24 * 60 * 60 * 1000);
mEditor.putLong(KEY_EXPIRES, millis);
mEditor.commit();
}
/**
* Checks whether user is logged in
*
* #return
*/
public boolean isLoggedIn() {
Date currentDate = new Date();
long millis = mPreferences.getLong(KEY_EXPIRES, 0);
/* If shared preferences does not have a value
then user is not logged in
*/
if (millis == 0) {
return false;
}
Date expiryDate = new Date(millis);
/* Check if session is expired by comparing
current date and Session expiry date
*/
return currentDate.before(expiryDate);
}
/**
* Fetches and returns user details
*
* #return user details
*/
public User getUserDetails() {
//Check if user is logged in first
if (!isLoggedIn()) {
return null;
}
User user = new User();
user.setUsername(mPreferences.getString(KEY_USERNAME, KEY_EMPTY));
user.setFullName(mPreferences.getString(KEY_FULL_NAME, KEY_EMPTY));
user.setCardId(mPreferences.getString(KEY_CARD_ID, KEY_EMPTY));
user.setSessionExpiryDate(new Date(mPreferences.getLong(KEY_EXPIRES, 0)));
return user;
}
/**
* Logs out user by clearing the session
*/
public void logoutUser(){
mEditor.clear();
mEditor.commit();
}
}
user class
package com.androidigniter.loginandregistration;
import java.util.Date;
/**
* Created by AndroidIgniter on 23 Mar 2019 020.
*/
public class User {
String username;
String fullName;
String cardid;
Date sessionExpiryDate;
public void setUsername(String username) {
this.username = username;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setCardId(String cardid) {
this.cardid = cardid;
}
public void setSessionExpiryDate(Date sessionExpiryDate) {
this.sessionExpiryDate = sessionExpiryDate;
}
public String getUsername() {
return username;
}
public String getFullName() {
return fullName;
}
public String getCardId() {
return cardid;
}
public Date getSessionExpiryDate() {
return sessionExpiryDate;
}
}

Your definition of loginUser is:
public void loginUser(String username, String fullName , String cardid)
whereas, when you call loginUser :
session.loginUser(username,response.getString(KEY_FULL_NAME));
You call it with 2 String parameters. You need to provide another parameter, cardid or change the function definition to require only 2 parameters, like this:
public void loginUser(String username, String fullName)

Related

The response from the onResponse method from Retrofit Library is always returning null

I'm using retrofit to get some data from the API for user login, but when I write all the code for the retrofit and check it's implementation on the emulator it always returns null response in onResponse method.
package com.madhulata.shriresume;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
EditText emailLogin, passwordLogin;
Button loginBtn;
RequestQueue mQueue;
ProgressBar progressBar;
String email,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailLogin = findViewById(R.id.emailLogin);
passwordLogin = findViewById(R.id.passwordLogin);
loginBtn = findViewById(R.id.loginBtn);
mQueue = VolleySingleton.getnstance(this).getRequestQueue();
progressBar = findViewById(R.id.progressBar);
email = emailLogin.getText().toString().trim();
password = passwordLogin.getText().toString().trim();
// Login button click listener
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginUser();
}
});
}
// Login user by fetching the data from the Api
public void loginUser(){
Call<User> call = RetrofitClient.getInstance().getApi().userLogin(email,password);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
if(user.getId() != 0){
Toast.makeText(MainActivity.this, "Everthing is okay " , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Everthing went wrong " , Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
}
///////////////////////////////////////
User.java
package com.madhulata.shriresume;
public class User {
private int id;
private String email;
private String country;
private String authentication_token;
public User(int id, String email, String country,String authentication_token) {
this.id = id;
this.email = email;
this.country = country;
this.authentication_token = authentication_token;
}
public int getId() {
return id;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
public String getAuthentication_token(){
return authentication_token;
}
}
//////////////////////////////////////////////////////////////////////
RetroClient.java
package com.madhulata.shriresume;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static final String BASE_URL = "https://shriresume.com/api/v1/";
private static RetrofitClient mInstance;
private Retrofit retrofit;
private RetrofitClient(){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
public static synchronized RetrofitClient getInstance(){
if(mInstance == null){
mInstance = new RetrofitClient();
}
return mInstance;
}
public Api getApi(){
return retrofit.create(Api.class);
}
}
//////////////////////////////////////////////////////////////////////
Api.java
package com.madhulata.shriresume;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Api {
#FormUrlEncoded
#POST("login")
Call<User> userLogin(
#Field("email") String email,
#Field("password") String password
);
}
The expected result is the no-error toast when the data from the API is correct and the error toast when the data is not present
Your code is working fine, I am getting proper output.
Try to print the output in logs,
Below is my loginUser() function code:
public void loginUser(String email, String pass){
Call<User> call = RetrofitClient.getInstance().getApi().userLogin(email,pass);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
Log.d("userOutput","user->"+user.toString());
if(user.getId() != 0){
Toast.makeText(TestAct.this, "Everthing is okay " , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TestAct.this, "Everthing went wrong " , Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
User.java
public class User {
private int id;
private String email;
private String country;
private String authentication_token;
public User(int id, String email, String country,String authentication_token) {
this.id = id;
this.email = email;
this.country = country;
this.authentication_token = authentication_token;
}
public int getId() {
return id;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
public String getAuthentication_token(){
return authentication_token;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email + '\'' +
", country='" + country + '\'' +
", authentication_token='" + authentication_token + '\'' +
'}';
}
}
Log details:

signup button linked to sqlite database

public void onSignUpClick(View v){
if(v.getId() == R.id.btnRegister)
{
EditText name = (EditText)findViewById(R.id.TFname);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = name.getText().toString();
String pass1str = name.getText().toString();
String pass2str = name.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg:
Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
tpass.show();
}
else
{
//insert the details in DB:
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setPass(pass1str);
helper.insertContact(c);
}
}
}
I'm trying to make a signup form linked to sqlite database. the registraion button that's linked to onSignUpClick method doesn't work. any help to fix this error?
I have implemented a similar functionality to my app.. You can use this as a reference.You need to add whatever elements needed for your signup activity.
1. Create a database handler for your sqlite application.(DatabaseHandler.java)
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context, Object name,
Object factory, int version) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
String password;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Mydatabase.db";
// Contacts table name
private static final String TABLE_REGISTER= "register";
public static final String KEY_EMAIL_ID="email_id";
public static final String KEY_MOB_NO = "mobile_number";
public static final String KEY_PASSWORD = "password";
public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
+ KEY_EMAIL_ID+ " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
onCreate(db);
}
void addregister(UserRegister registerdata)
// code to add the new register
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
values.put(KEY_PASSWORD, registerdata.getPassword());
// Inserting Row
db.insert(TABLE_REGISTER, null, values);
db.close(); // Closing database connection
}
//code to get the register
String getregister(String username){
SQLiteDatabase db = this.getReadableDatabase();
//String selectquery="SELECT * FROM TABLE_REGISTER";
Cursor cursor=db.query(TABLE_REGISTER,null, "email_id=?",new String[]{username},null, null, null, null);
if(cursor.getCount()<1){
cursor.close();
return "Not Exist";
}
else if(cursor.getCount()>=1 && cursor.moveToFirst()){
password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
cursor.close();
}
return password;
}
public String getDatabaseName() {
return DATABASE_NAME;
}
public static String getTableContacts() {
return TABLE_REGISTER;
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
}
2. Create a modal class UserRegister
public class UserRegister {
//private variables
String email_id;
String mobile_number;
String password;
// Empty constructor
public UserRegister(){}
// constructor
public UserRegister( String email_id,String mobile_number, String password){
this.email_id=email_id;
this.mobile_number=mobile_number;
this.password = password;
}
public String getEmailId() {
return email_id;
}
public void setEmailId(String email_id){
this.email_id = email_id;
}
public String getMobNo() {
// TODO Auto-generated method stub
return mobile_number;
}
public void setMobNo(String mobile_number){
this.mobile_number=mobile_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.Create the RegistrationActivity
public class Registration_Activity extends AppCompatActivity {
EditText reg_email,reg_phone,reg_password;
Button reg_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final DatabaseHandler db = new DatabaseHandler(this, null, null, 2);
reg_email = (EditText)findViewById(R.id.reg_email);
reg_phone = (EditText)findViewById(R.id.reg_phone);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_button = (Button)findViewById(R.id.reg_button);
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = reg_email.getText().toString();
String phone = reg_phone.getText().toString();
String password = reg_password.getText().toString();
if (email.matches(emailPattern)) {
DatabaseHandler db = new DatabaseHandler(Registration_Activity.this, null, null, 2);
UserRegister userRegister = new UserRegister();
userRegister.setEmailId(email);
userRegister.setMobNo(phone);
userRegister.setPassword(password);
db.addregister(userRegister);
Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration_Activity.this, Login_Activity.class);
startActivity(intent);
Registration_Activity.this.finish();
}
else
{
Toast.makeText(getApplicationContext(),"Enter a valid Email Address",Toast.LENGTH_SHORT).show();
}
}
});
}
}
4. Login_Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login_Activity extends AppCompatActivity {
TextView signup;
String email,password;
EditText log_username,log_password;
Button login_button;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signup = (TextView)findViewById(R.id.signup);
String htmlString="<u>Signup</u>";
signup.setText(Html.fromHtml(htmlString));
log_username = (EditText)findViewById(R.id.log_username);
log_password = (EditText)findViewById(R.id.log_password);
login_button = (Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db=new DatabaseHandler(Login_Activity.this, null, null, 2);
email = log_username.getText().toString();
password = log_password.getText().toString();
String StoredPassword =db.getregister(email);
if(password.equals(StoredPassword)){
Toast.makeText(getApplicationContext(),"Login Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login_Activity.this,VideoActivity.class);
startActivity(intent);
Login_Activity.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
log_username.setText("");
log_password.setText("");
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login_Activity.this,Registration_Activity.class);
startActivity(intent);
Login_Activity.this.finish();
}
});
}
}

Matcher won't match the Pattern in Android

I am trying to develop an app that automatically reads a One Time Password from an incoming SMS. I have a class called SMS where I'm storing the currently read messages and a class called SMSRule that contains information about the possible OTP Senders.
The SMSRule also contains a Pattern variable that should be matched with the message to see if it really is the correct sender of the OTP.
Everything is going smooth except for the OTP extraction from the message. My SMS is containing the message, but when I try to match the Pattern against the message, my match.find() returns false.
Following are my files:
OTPAutoRead.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import auro.widget.OTP.SMS.SMS;
import auro.widget.OTP.SMS.SMSRule;
/**
* Created on 26/8/16.
* #author Auro
* #since 1.0
*/
public class OTPAutoRead extends BroadcastReceiver {
private static final String LOG_TAG = OTPAutoRead.class.getCanonicalName();
private static final String mReadPermission = "android.permission.READ_SMS";
private static final String mReceivePermission = "android.permission.RECEIVE_SMS";
private List<SMSRule> smsRules;
private Context context;
private String OTP;
public OTPAutoRead() {throw new InstantiationError("Empty Constructor");}
public OTPAutoRead(#NonNull Context context, final List<SMSRule> smsRules) {
if (smsRules == null || smsRules.size() == 0) {
throw new AuroMissingRulesException("No SMS Rules Found");
}
this.smsRules = smsRules;
this.context = context;
CheckSMSReadPermission();
IntentFilter itf = new IntentFilter();
itf.addAction("android.provider.Telephony.SMS_RECEIVED");
itf.setPriority(999);
context.registerReceiver(this,itf);
}
private void CheckSMSReadPermission() {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
int readPermission = packageManager.checkPermission(mReadPermission,packageName);
int receivePermission = packageManager.checkPermission(mReceivePermission, packageName);
boolean canRead = (readPermission == PackageManager.PERMISSION_GRANTED);
if (!canRead)
Toast.makeText(context,"Please enable SMS read permission for auto OTP read", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
tryReceiveMessage(intent);
} catch (Exception e) {
Log.i(LOG_TAG, "Failed to read SMS", e);
}
}
private void tryReceiveMessage(Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] messages = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String messageFrom = messages[i].getOriginatingAddress().toUpperCase();
String messageBody = messages[i].getMessageBody().toUpperCase();
Log.d(LOG_TAG, "Message is from: " + messageFrom + " and its content is: " + messageBody);
SMS sms = new SMS();
sms.setMessage(messageBody).setAddress(messageFrom);
processOTP(sms);
}
}
}
}
private void processOTP(SMS sms) {
int i;
for (i = 0; i < smsRules.size(); i ++) {
if (sms.getAddress().toUpperCase().contains(smsRules.get(i).getSender().toUpperCase())) {
Pattern pattern = smsRules.get(i).getOTPPattern();
System.out.println(pattern.pattern());
System.out.println(sms.getMessage());
Matcher matcher = pattern.matcher(sms.getMessage().toUpperCase());
if (matcher.find()) {
OTP = matcher.group(1);
Log.i(LOG_TAG,"Extracted OTP is: " + OTP);
Toast.makeText(context,"OTP RECEIVED IS: " + OTP,Toast.LENGTH_SHORT).show();
return;
} else
Log.d(LOG_TAG,"Failed to extract OTP");
}
}
}
public String getOTP() {
return OTP;
}
}
SMS.java
import android.support.annotation.NonNull;
/**
* Created on 26/8/16.
* #author Auro
* #since 1.0
*/
public class SMS {
private String mID;
private String mAddress;
private String mMessage;
private boolean isRead = false;
private String mTime;
public String getID() {
return mID;
}
public SMS setID(#NonNull final String ID) {
mID = ID;
return this;
}
public String getAddress() {
return mAddress;
}
public SMS setAddress(#NonNull final String Address) {
mAddress = Address;
return this;
}
public String getMessage() {
return mMessage;
}
public SMS setMessage(#NonNull final String Message) {
mMessage = Message;
return this;
}
public boolean isRead() {
return isRead;
}
public SMS setReadState(boolean ReadState) {
isRead = ReadState;
return this;
}
public String getTime() {
return mTime;
}
public SMS setTime(#NonNull String Time) {
mTime = Time;
return this;
}
}
SMSRule.java
import java.util.regex.Pattern;
/**
* Created on 26/8/16.
* #author Auro
* #since 1.0
*/
public class SMSRule {
private String mSender;
private String mGroupID;
private Pattern mOTPPattern;
private SMS sms;
public String getSender() {
return mSender;
}
public SMSRule setSender(final String sender) {
mSender = sender;
return this;
}
public String getGroupID() {
return mGroupID;
}
public SMSRule setGroupID(final String groupID) {
mGroupID = groupID;
return this;
}
public Pattern getOTPPattern() {
return mOTPPattern;
}
public SMSRule setOTPPattern(final Pattern otpPattern) {
mOTPPattern = otpPattern;
return this;
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import auro.widget.OTP.OTPAutoRead;
import auro.juspay.widget.OTP.SMS.SMSRule;
public class MainActivity extends AppCompatActivity {
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
SMSRule rule = new SMSRule();
Pattern pattern = Pattern.compile("One Time Password is (\\d{6})".toUpperCase());
rule.setSender("BANK-XYZ");
rule.setOTPPattern(pattern);
List<SMSRule> smsRules = new ArrayList<>();
smsRules.add(rule);
OTPAutoRead otpAutoRead = new OTPAutoRead(this,smsRules);
String OTP = otpAutoRead.getOTP();
if (OTP != null)
{
editText.setText(OTP);
}
}
}
Problem is, when I run this in Debug mode, I get matchFound = false. I also tried changing the regex to
Pattern pattern = Pattern.compile("One Time Password is \d{6}".toUpperCase());
It just wouldn't work
Following is a screenshot: -
When you convert the pattern string to uppercase in Pattern.compile("One Time Password is (\\d{6})".toUpperCase()), \d (matching a digit) turns into \D (matching a non-digit).
Use [0-9] instead of the \d so that the pattern means the same, or just remove toUpperCase() and write the exact pattern, or use a pattern case insensitive flag.

Android Null Pointer Exception for onclick listener

The following code is giving me null pointer exception even though I can't find anything wrong with the code. Tried commenting it out and it seems to be working. But still not able to find out what is wrong with the code? tried my own trouble shooting of commenting out the code and such and right now the code below is giving me nullpointer exception
Log Cat
12-19 05:49:14.833: E/AndroidRuntime(3392): Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference 12-19 05:49:14.833: E/AndroidRuntime(3392):
at
com.techiequickie.bharath.boadraf.newBet_activity.onCreate(newBet_activity.java:80)
Code:
package com.techiequickie.bhr.boadraf;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import databasehandler.DatabaseHandler;
import databasehandler.UserFunctions;
/**
* Created by YP on 17-Nov-14.
*/
public class newBet_activity extends ActionBarActivity
{
EditText inputBetname, inputBetbrief, inputBetdescription;
SeekBar valueSeekbar; //= null;
Button placeBet;
// JSON Response node names
private static String KEY_SUCCESS = "success";
#SuppressWarnings("unused")
private static String KEY_ERROR = "error";
#SuppressWarnings("unused")
private static String KEY_ERROR_MSG = "error_msg";
//private static String KEY_UID = "uid";
private static String KEY_BETNAME = "bet_name";
private static String KEY_BETBRIEF = "bet_brief";
private static String KEY_BETDESCRIPTION = "bet_description";
private static String KEY_BETVALUE = "bet_value";
// private static String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newbet);
// Importing all assets like buttons, text fields
inputBetname = (EditText) findViewById(R.id.betName_et);
inputBetbrief = (EditText) findViewById(R.id.betBriefDescription_et);
inputBetdescription = (EditText) findViewById(R.id.betDescription_et);
placeBet = (Button) findViewById(R.id.btn_newbet);
//valueSeekbar = (SeekBar) findViewById(R.id.betValue_bar);
/*
valueSeekbar.setOnSeekBarChangeListener
(
new SeekBar.OnSeekBarChangeListener()
{
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(newBet_activity.this, "seek bar progress:" + progressChanged, Toast.LENGTH_SHORT).show();
}
}
);*/
placeBet.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String betname = inputBetname.getText().toString();
String betBrief = inputBetbrief.getText().toString();
String betDescription = inputBetdescription.getText().toString();
//StringBuilder betValue = ((toString()) valueSeekbar.getProgress());
//new BetRegisterTask().execute(betname,betBrief,betDescription);
}
}
);
}
/*
class BetRegisterTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.createBet(params[0], params[1], params[2]);
// check for login response
try
{
if (json.getString(KEY_SUCCESS) != null)
{
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1)
{
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.optJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.newBet(json_user.getString(KEY_BETNAME), json_user.getString(KEY_BETBRIEF), json.getString(KEY_BETDESCRIPTION));
return "1";
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
if (s.equals("1"))
{
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), Loginactivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
showToastforSucessfulBetCreation();
}
else
{
// Error in registration
//registerErrorMsg.setText("Error occurred in registration");
showToastforUnsucessfulBetCreation();
}
}
}*/
public void showToastforSucessfulBetCreation() {
Toast toast = Toast.makeText(this, "Registration Sucessfull", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 30);
toast.show();
}
public void showToastforUnsucessfulBetCreation() {
Toast toast = Toast.makeText(this, "Registration UnSucessfull", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 30);
toast.show();
}
}
placeBet is not yet initialized that's why it is giving null pointer exception
check the following line
palceBet=findViewId(R.id.btn_newbet);
It seems that you did not create Button with id btn_newbet in the .xml file.
so to find if you define this button in xml file or not you should take your cursor over btn_newbet in
placeBet = (Button) findViewById(R.id.btn_newbet);
and if onclicking ,it will redirect to correct xml .

Arraylist keeps overwriting the last entry i added

sorry for troubling you, i am new at android, and i need a little help. I am doing a simple ampplication in which you sign up some people to a club. What it keeps happening is that the last person i add to the arraylist overwries the old one. I really donĀ“t know what it could be. If you can help i would be grateful.
AltaSocio.java
package com.example.polideportivo1;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AltaSocio extends Activity {
Socios nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
VariablesGlobales vb = new VariablesGlobales();
private EditText editDocumento;
private EditText editApellido;
private EditText editNombre;
private CheckBox checkBoxM;
private CheckBox checkBoxF;
private EditText editCivil;
private Spinner Nacionalidad;
private EditText Nacimiento;
private EditText Domicilio;
private Spinner Localidad;
private EditText Celular;
private EditText TelFijo;
private EditText Correo;
String miNacionalidad;
String miLocalidad;
ArrayList<Socios> socios = vb.getSocios();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alta_socio2);
editDocumento = (EditText)findViewById(R.id.editDocumento);
editApellido = (EditText)findViewById(R.id.editApellido);
editNombre = (EditText)findViewById(R.id.editNombre);
editCivil = (EditText)findViewById(R.id.editCivil);
Nacimiento = (EditText)findViewById(R.id.editNacimiento);
Domicilio = (EditText)findViewById(R.id.editDomicilio);
Celular = (EditText)findViewById(R.id.editCelular);
TelFijo = (EditText)findViewById(R.id.editFijo);
Correo = (EditText)findViewById(R.id.editCorreo);
checkBoxM = (CheckBox)findViewById(R.id.checkM);
checkBoxF = (CheckBox)findViewById(R.id.checkF);
Nacionalidad = (Spinner)findViewById(R.id.spinnerNacionalidad);
Localidad = (Spinner)findViewById(R.id.spinnerLocalidad);
final Button BtnCrear = (Button)findViewById(R.id.botonCrear);
final Button BtnCerrar = (Button)findViewById(R.id.buttonAtras);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Nacionalidad, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
Nacionalidad.setAdapter(adapter);
Nacionalidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miNacionalidad = Nacionalidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.Localidad, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_item);
Localidad.setAdapter(adapter2);
Localidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miLocalidad = Localidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
}
public void grabar(View v) {
nuevosSocio.setCI(Integer.parseInt(editDocumento.getText().toString()));
nuevosSocio.setApellido(editApellido.getText().toString());
nuevosSocio.setNombre(editNombre.getText().toString());
nuevosSocio.setEstadoCivil(editCivil.getText().toString());
DateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
DateFormat DataSocio;
try {
String Fecha =(Nacimiento.getText().toString());
formateador.parse(Fecha);
nuevosSocio.setFechaNacimiento(Fecha);
}
catch (ParseException e)
{
Toast g = Toast.makeText(this, "Formato Fecha no valido", Toast.LENGTH_LONG);
}
//nuevosSocio.setFechaNacimiento(Fecha);
nuevosSocio.setDomicilio(Domicilio.getText().toString());
nuevosSocio.setTelefonoCelular(Integer.parseInt(Celular.getText().toString()));
nuevosSocio.setTelefonoFijo(Integer.parseInt(TelFijo.getText().toString()));
nuevosSocio.setCorreo(Correo.getText().toString());
if (checkBoxM.isChecked()) {
nuevosSocio.setSexo("Masculino");
} else {
nuevosSocio.setSexo("Femenino");
}
nuevosSocio.setNacionalidad(miNacionalidad);
nuevosSocio.setLocalidad(miLocalidad);
socios.add(nuevosSocio);
nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
Toast t = Toast.makeText(this, "Los datos fueron grabados",
Toast.LENGTH_SHORT);
t.show();
finish();
}
}
Socio.java
package com.example.polideportivo1;
import java.sql.Date;
import android.graphics.Bitmap;
import android.widget.CheckBox;
import android.widget.ImageView;
public class Socios {
private int CI;
private String Nombre;
private String Apellido;
private String Sexo;
private String EstadoCivil;
private String Nacionalidad;
private String FechaNacimiento;
private String Domicilio;
private String Localidad;
private int TelefonoCelular;
private int TelefonoFijo;
private String DireccionCorreo;
public Socios(int CI, String Nombre, String Apellido, String Sexo, String EstadoCivil,
String Nacionalidad, String FechaNacimiento, String Domicilio, String Localidad, int TelefonoCelular, int TelefonoFijo, String DireccionCorreo) {
this.CI = CI;
this.Nombre = Nombre;
this.Apellido = Apellido;
this.Sexo = Sexo;
this.EstadoCivil = EstadoCivil;
this.Nacionalidad = Nacionalidad;
this.FechaNacimiento = FechaNacimiento;
this.Domicilio = Domicilio;
this.Localidad = Localidad;
this.TelefonoCelular = TelefonoCelular;
this.TelefonoFijo = TelefonoFijo;
this.DireccionCorreo = DireccionCorreo;
}
public int obtenerCI() {
return CI;
}
public String obtenerNombre() {
return Nombre;
}
public String obtenerApellido() {
return Apellido;
}
public String obtenerSexo() {
return Sexo;
}
public void setSexo() {
this.Sexo = Sexo;
}
public String obtenerNacionalidad() {
return Nacionalidad;
}
public String obtenerEstadoCivil() {
return EstadoCivil;
}
public String obtenerFechaNacimiento() {
return FechaNacimiento;
}
public String obtenerDomicilio() {
return Domicilio;
}
public String obtenerLocalidad() {
return Localidad;
}
public int obtenerCelular() {
return TelefonoCelular;
}
public int obtenerTelefonoFijo() {
return TelefonoFijo;
}
public String obtenerCorreo() {
return DireccionCorreo;
}
public void setCI(int parseInt) {
this.CI = parseInt;
}
public void setApellido(String string) {
this.Apellido = string;
}
public void setNombre(String string) {
this.Nombre = string;
}
public void setEstadoCivil(String string) {
this.EstadoCivil = string;
}
public void setDomicilio(String string) {
this.Domicilio = string;
}
public void setTelefonoCelular(int parseInt) {
this.TelefonoCelular = parseInt;
}
public void setTelefonoFijo(int parseInt) {
this.TelefonoFijo = parseInt;
}
public void setCorreo(String string) {
this.DireccionCorreo = string;
}
public void setSexo(String string) {
this.Sexo = string;
}
public void setNacionalidad(String miNacionalidad) {
this.Nacionalidad = miNacionalidad;
}
public void setLocalidad(String miLocalidad) {
this.Localidad = miLocalidad;
}
public void setFechaNacimiento(String string) {
this.FechaNacimiento = string;
}
}
Every time you called the grabar to add the user you have to create a new Socio object. Using the same references will only change object's content

Categories