Matcher won't match the Pattern in Android - java

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.

Related

Is there anyway I can get mobile number of both SIM cards in android Java?

I want to add the functionality of login similar to UPI apps. The user will select the SIM card from his phone and I will send an SMS from that SIM and will verify his phone number using that SMS. But I have to compare the number in the back-end or in API. So, I want to acquire the phone numbers of both SIM cards or the phone number of the SIM card user selects (Get the phone number from SMS or while sending SMS).
I am putting a generic class that I made for SIM selections and SMS. I have tried getting the mobile number from SubscriptionInfo, but it gives the operator name and all details right except the mobile number which returns an empty string. I have found in different blogs or my R&D that it is up to the operator whether to put the number there or not. So, if I am getting the mobile number, it is not 100% guaranteed that I will get the mobile number every time.
Here's my generic class: SimUtil.java
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class SimUtil {
List<SimCard> simCards = new ArrayList<>();
Context context;
public SimUtil(Context context) {
this.context = context;
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
setupPermissions();
return;
}
List<SubscriptionInfo> subscriptionInfos = SubscriptionManager.from(context.getApplicationContext()).getActiveSubscriptionInfoList();
for (int i = 0; i < subscriptionInfos.size(); i++) {
SubscriptionInfo currentCard = subscriptionInfos.get(i);
SimCard simCard = new SimCard(i,currentCard);
simCards.add(simCard);
}
}
public int getSimCardCount() {
return this.simCards.size();
}
public List<SimCard> getSimCardList() {
if(simCards.size() > 0)
return simCards;
else
return null;
}
public SimCard getFirstSimCard() {
return simCards.get(0);
}
public boolean hasDualSim() {
return simCards.size() > 1;
}
public SimCard getSecondSimCard() {
if(hasDualSim())
return simCards.get(1);
else
return null;
}
public static void sendSMSFromSim1(String message) {
SmsManager.getSmsManagerForSubscriptionId(0)
.sendTextMessage(AppConstant.LOGIN_MOBILE_NUMBER, null, message, null, null);
}
public static void sendSMSFromSim2(String message) {
SmsManager.getSmsManagerForSubscriptionId(1)
.sendTextMessage(AppConstant.LOGIN_MOBILE_NUMBER, null, message, null, null);
}
private void setupPermissions() {
int permission = ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS);
if(permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.SEND_SMS}, 1);
}
int permission2 = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
if(permission2 != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
}
}
public static class SimCard {
int index;
String operatorName;
String mobileNumber;
String countryISO;
public SimCard(int index, String operatorName, String countryISO, String mobileNumber) {
this.index = index;
this.operatorName = operatorName;
this.countryISO = countryISO;
this.mobileNumber = mobileNumber;
}
public SimCard(int index,SubscriptionInfo subscriptionInfo) {
this.index = index;
this.operatorName = subscriptionInfo.getCarrierName().toString();
this.countryISO = subscriptionInfo.getCountryIso();
this.mobileNumber = subscriptionInfo.getNumber();
}
public int getIndex() {
return index;
}
public String getOperatorName() {
return operatorName;
}
public String getCountryISO() {
return countryISO;
}
public String getMobileNumber() {
return mobileNumber;
}
}
}

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:

android studio error after run application

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)

How to pass data collected in arraylist from json asset file in one activity having recyclerview to another activity again having recycler view?

I have an activity named Cardview Activity which has a recycler view associated with it and i am fetching data from a JSON asset file in that. But now when i click on an item of Cardview Activity, I want to send data related to that item only to another activity i.e. People_List_Activity which is again having a recyclerView.
CardViewActivity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Telephone Directory");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
String Office_Phone = jobIn.getString("Office_Phone");
String Residence_Phone = jobIn.getString("Residence_Phone");
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
// JSONObject jobI = fax.getString(k);
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("DirectoryData.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
RecyclerViewAdapterMain
package com.example.android.directory;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Android on 3/17/2017.
*/
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
}
});
}
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, int position) {
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
People_List_Activity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class PeopleListActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people_list);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Staff List");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
}
}
RecyclerViewAdapter_People.java
package com.example.android.directory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Android on 3/20/2017.
*/
public class RecyclerViewAdapter_People extends RecyclerView.Adapter<RecyclerViewAdapter_People.PeopleObjectHolder> {
private static String TAG = "peopleRecyclrVwAdptr";
public static class PeopleObjectHolder extends RecyclerView.ViewHolder{
TextView peopleName,peopleDesignation;
public PeopleObjectHolder(View itemView) {
super(itemView);
peopleName=(TextView)itemView.findViewById(R.id.people_name);
peopleDesignation=(TextView)itemView.findViewById(R.id.people_designation);
Log.d(TAG, "PeopleObjectHolder: ");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public PeopleObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_people_list_row,parent,false);
PeopleObjectHolder peopleObjectHolder=new PeopleObjectHolder(view);
return peopleObjectHolder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter_People.PeopleObjectHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
CategoryModel.java:
package com.example.android.directory;
import java.util.ArrayList;
/**
* Created by Android on 3/17/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList>categoryList;
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public static class CategoryList{
private int Category_id;
private String Category_name;
private ArrayList<String>Emails;
private ArrayList<String>Epabx;
private ArrayList<String>Category_Fax;
private ArrayList<Persons> persons;
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
public static class Persons{
private int Person_ID;
private String Name;
private String Designation;
private String Office_Phone;
private String Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
public Persons(int person_ID, String name, String designation, String office_Phone,
String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
}
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(String office_Phone) {
Office_Phone = office_Phone;
}
public String getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(String residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
}
}
how can i send the Person_Id, Name and Designation to the People_List_Activity ? Please help as i am stuck in the code.
You can send using Intent , by passing your data in Bundle and then pass Bundle into Intent Extras.When you go form one Activity to another .
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key1",value1);
bundle.putString("key2",value2);
bundle.putString("key3",value3);
intent.putExtras(bundle)
startActvity(intent);
And You can retrieve Data in next Activity OnCreate():
Bundle bundle = getIntent().getExtras();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
String value3 = bundle.getString("key3");

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