Set Value of EdiTextPreference in android - android

in Android i want to set EditTextprefernce value i tried
EditTextPreference etp = (EditTextPreference)getPreferenceScreen().findPreference("mykey");
etp.setText("123");
tell me how can i set EditTextpreference value in program dont suffest me in xml/preference.xml to write android:default="123" want to do programmatically

Try this
EditTextPreference myEditTextPreference = (EditTextPreference) findPreference("myPrefKey");
myEditTextPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
try {
String input = newValue.toString();
if (containsOnlyNumbers(input)) {
int result = Integer.parseInt(input);
if (result < 0) {
result = 0;
}
// Parsing was successful. Use the result..
// TODO
} else {
Log.e(TAG, "Invalid value input '" + input
+ "', using old one");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
});
private boolean containsOnlyNumbers(String s) {
if(s.length()<1) {
return false;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}

Related

Profile with editable edittext

What I aim with my program is to make a profile page with details that are blank for the first time use then these details can be editable and retained after clicking an update button. However, I tried many different ways like sharedprefs and firebase. It's just doesn't work to me.
The firebase way is after the update button has been clicked, it's just going to the main activity then it doesn't update or change anything.
here is the firebase code
showAllUserData();
//DB
reference = FirebaseDatabase.getInstance("https://backend-d820a-default-rtdb.firebaseio.com/").getReference("user");
private void showAllUserData(){
Intent intent = getIntent();
_NAME = intent.getStringExtra("name");
_NUMBER = intent.getStringExtra("num");
_ADDRESS = intent.getStringExtra("add");
_AGE = intent.getStringExtra("age");
_BDAY = intent.getStringExtra("bday");
_BTYPE = intent.getStringExtra("btype");
_COMORB = intent.getStringExtra("comorb");
editName.setText(_NAME);
editNum.setText(_NUMBER);
editAdd.setText(_ADDRESS);
editAge.setText(_AGE);
editBday.setText(_BDAY);
editBType.setText(_BTYPE);
editComorb.setText(_COMORB);
}
public void update(View view){
if (isNameChanged() || isNumberChanged() || isAddChanged() || isAgeChanged() ||
isBdayChanged() || isBTypeChanged() || isComorbChanged()) {
Toast.makeText(this, "Data has been updated", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Data his same and cannot be updated", Toast.LENGTH_LONG).show();
}
}
private boolean isComorbChanged() {
if(_COMORB.equals(editComorb.getText().toString())){
reference.child(_COMORB).child("COMORB").setValue(editComorb.getText().toString());
return true;
}else{
return false;
}
}
private boolean isBTypeChanged() {
if(_BTYPE.equals(editBType.getText().toString())){
reference.child(_BTYPE).child("btype").setValue(editBType.getText().toString());
return true;
}else{
return false;
}
}
private boolean isBdayChanged() {
if(_BDAY.equals(editBday.getText().toString())){
reference.child(_BDAY).child("bday").setValue(editBday.getText().toString());
return true;
}else{
return false;
}
}
private boolean isAgeChanged() {
if(_AGE.equals(editAge.getText().toString())){
reference.child(_AGE).child("age").setValue(editAge.getText().toString());
return true;
}else{
return false;
}
}
private boolean isAddChanged() {
if(_NUMBER.equals(editNum.getText().toString())){
reference.child(_NUMBER).child("address").setValue(editNum.getText().toString());
return true;
}else{
return false;
}
}
private boolean isNumberChanged() {
if(_NUMBER.equals(editNum.getText().toString())){
reference.child(_NUMBER).child("numBER").setValue(editNum.getText().toString());
return true;
}else{
return false;
}
}
private boolean isNameChanged() {
if(_NAME.equals(editName.getText().toString())){
reference.child(_NAME).child("name").setValue(editName.getText().toString());
return true;
}else{
return false;
}
Is there a simpler way to implement this?

How to wait first for the retrofit response before returning the boolean

always returning the wrong value, before the request has been finish. The validation will already return the value without waiting for the response. I'am using retrofit for request then i put it on listener.
Thankyou for the help, suggestion is much accepted!.
this is my code, i have validation for the screen when it's true it will goes to another screen.
#Override
public boolean isValid() {
if (NetworkUtils.isConnected(getActivity())) {
final AtomicBoolean pass = new AtomicBoolean(false);
Thread simpleThread = new Thread() {
public void run() {
new ReprintOnlineHelper(rType, receiptNoEditText.getText().toString(), issuedDate, etTotalAmtPaid.getText().toString(), new ReprintOnlineHelper.ReceiptNoSearchListener() {
#Override
public boolean onServiceResponse(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.get(0).getTPAYRECEIPTNO());
if (receiptNumbers.isEmpty()) {
returnValue = "eReceipt Number not found!";
val = true;
} else {
String pdates = null, ddates;
try {
if (!receiptNumbers.get(0).getTPAYISSUEDDATE().isEmpty()) {
Date periodFormat = df.parse(receiptNumbers.get(0).getTPAYISSUEDDATE());
pdates = sdf.format(periodFormat);
}
} catch (ParseException e) {
e.printStackTrace();
Log.e("ddd", "" + e.getMessage());
}
String tinNo = receiptNumbers.get(0).getTPTIN();
if (tinNo.contains("-")) {
tinNo = receiptNumbers.get(0).getTPTIN().replace("-", "");
}
Log.e("JAC", "" + receiptNumbers.get(0).getTPAYRECEIPTNO() + "---" + AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)) + "---" + MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) + "--" + AlfonzoUtils.formatDate(issuedDate) + "--" + receiptNoEditText.getText().toString() + "--" + tinNo + "--"+revenueCollection.getTpTin().replace("-", ""));
if (receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString()) &&
AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))
&& MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) == MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) && tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
pass.set(true);
returnValue = "success";
val = true;
showMessagePrompt(rType,returnValue);
return true;
} else if (!tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
returnValue = "eReceipt Number was not issued to this TIN " + revenueCollection.getTpTin();
val = false;
} else if (!AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))) {
returnValue = "Issued date is not valid";
val = false;
} else if (MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) != MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString())) {
returnValue = "Total amount paid is not valid";
val = false;
} else if (!receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString())) {
returnValue = "ReceiptNo is not valid";
val = false;
}
}
return false;
}
#Override
public void onErrorResponse(int err) {
}
}).reprintReceiptNo();
}
};
if (!receiptNoEditText.getText().toString().isEmpty() && issuedDate != 0 /*&& MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) > 0*/) {
try {
simpleThread.start();
simpleThread.join();
pass.get();
Log.e("pass", "" + pass + "-" + pass.get() + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
return pass.get();
}
}
return false;
}
this is my request in retrofit:
public void reprintReceiptNo() {
JSONObject jO = new JSONObject();
JSONObject result = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jO.put("xReceipt", receiptTypeNo);
jO.put("xType", receipttype);
jsonArray.put(jO);
result.put("dataArray", jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("dataArray", "----- " + result.toString());
ServiceInterface si = BaseRestClient.getClient();
Observable<List<ReceiptNumber>> call = si.getreprintReceiptNumber(result.toString());
call.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ReceiptNumber>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.toString());
onReceiptNoSearchListener.onServiceResponse(receiptNumbers);
}
});
}
Its not possible for the isValid() method to wait for the service reponse if you have code outside the Thread you've created.
The method will execute the Thread, but while that Thread is executing, the rest of the code will be read, meaning the return pass.get(); or the return false; statments will be read, causing the the method to return before the server response.
The solution its to change the way this was done. You should check if you can call the server and then created your logic in the methods onServiceResponse() and onErrorResponse() based on how you want to proceed.

File.exists returning false

I am trying to access a file twice in my program.
First I am reading from the file, which runs fine.
The second time, I am trying to delete the same file from which I read.
Strangely the second time no records are present in the file. In fact when I try to run the command file.exists it returns false. Why is this happening?
Following is my code:
public class ControlLights extends AppCompatActivity {
private RoomListAdapter adapter;
private List<ROOM> mRoomList;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup,menu);
}
public void filedel(int pos) {
Toast.makeText(getApplicationContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();
File filemain = new File("roomdata.txt");
try {
File temp = File.createTempFile("file",".txt",filemain.getParentFile());
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(temp), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
int p=0;
for(String line; (line=reader.readLine())!=null;) {
if(p == pos) {
line = line.replace(line,"");
writer.println(line);
}
writer.println(line);
}
reader.close();
writer.close();
filemain.delete();
temp.renameTo(filemain);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.Edit:
return true;
case R.id.Delete:
filedel(info.position);
mRoomList.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
public void loadrooms() {
int block = 1024;
try {
boolean exists = (new File("roomdata.txt").exists());
Toast.makeText(getApplicationContext(), String.valueOf(exists), Toast.LENGTH_LONG).show();
FileInputStream fis = openFileInput("roomdata.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] data = new char[block];
String roomdata = "";
int size;
try {
while ((size = isr.read(data)) > 0) {
String read_data = String.copyValueOf(data, 0, size);
roomdata += read_data;
data = new char[block];
}
} catch (IOException e) {
e.printStackTrace();
}
String[] room_display = roomdata.split("\n");
String[] tempstring;
ListView lsv = (ListView) findViewById(R.id.Room_list);
mRoomList = new ArrayList<>();
for (int b = 0; b < room_display.length; b++) {
tempstring = room_display[b].split(":");
mRoomList.add(new ROOM(tempstring[0], tempstring[1], tempstring[2], tempstring[3], tempstring[4], tempstring[5], tempstring[6], tempstring[7], tempstring[8], tempstring[9]));
}
adapter = new RoomListAdapter(getApplicationContext(), mRoomList);
lsv.setAdapter(adapter);
registerForContextMenu(lsv);
int count = mRoomList.size();
final ArrayList<Integer> disabledpos = new ArrayList<Integer>();
for (int q = 0; q < count; q++) {
ROOM temp_room1 = mRoomList.get(q);
String IP = temp_room1.getRoom_IP_Address();
String online = null;
ConnectionTest CT = new ConnectionTest();
try {
online = CT.execute(IP, "a", "b").get();
Boolean b1 = Boolean.valueOf(online);
if (!b1) {
disabledpos.add(q);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
try {
isr.reset();
isr.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (new File("roomdata.txt").delete()) {
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "not deleted", Toast.LENGTH_LONG).show();
// Not deleted
}
lsv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int temp_position = position;
Intent p = new Intent(ControlLights.this, Electrical_equipment_list.class);
if (!(disabledpos.contains(position))) {
ROOM temp_room = mRoomList.get(temp_position);
p.putExtra("EE1", temp_room.getEE1());
p.putExtra("EE2", temp_room.getEE2());
p.putExtra("EE3", temp_room.getEE3());
p.putExtra("EE4", temp_room.getEE4());
p.putExtra("EE5", temp_room.getEE5());
p.putExtra("EE6", temp_room.getEE6());
p.putExtra("EE7", temp_room.getEE7());
p.putExtra("EE8", temp_room.getEE8());
p.putExtra("IPaddress", temp_room.getRoom_IP_Address());
startActivity(p);
}
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_lights);
loadrooms();
}
public class ConnectionTest extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
Boolean online;
String tempstring = null;
try {
InetAddress roomaddress = InetAddress.getByName(params[0]);
online = roomaddress.isReachable(100);
tempstring = String.valueOf(online);
} catch (IOException e) {
e.printStackTrace();
}
return tempstring;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
Keep your File as a class' member, since it is an essential component of what the class does
Move your inner logic and file reference initialization to onStart()
public class ControlLights extends AppCompatActivity {
private RoomListAdapter adapter;
private List mRoomList;
private File filemain;
...
public void filedel(int pos) {
Toast.makeText(getApplicationContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();
try {
File temp = File.createTempFile("file",".txt", filemain.getParentFile());
...
}
}
public void loadrooms() {
int block = 1024;
try {
boolean exists = filemain.exists();
...
if (filemain.delete()) {
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "not deleted", Toast.LENGTH_LONG).show();
// Not deleted
}
} ...
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_lights);
}
#Override
protected void onStart() {
super.onStart();
filemain = new File("roomdata.txt");
loadrooms();
}
}
Foot note
I apologize for the horrible code format, but apparently they changed the parsing algorithm to a point where you have to manually type all the code again here instead of just being able to copy-paste it. Anyone being to edit it accordingly is welcome.

Email Validation on EditText in android

I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").
I don't want that it login with "\".`
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.main);
WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);
this.pref = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
register = (Button) findViewById(R.id.btnregister);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RegisterIntent();
}
});
login = (Button) findViewById(R.id.btlogin);
password = (EditText) findViewById(R.id.txtPwd);
username = (EditText) findViewById(R.id.txtemail);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
pref = getSharedPreferences(Constants.PREFS_NAME,
MODE_PRIVATE);
String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
"");
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLogin = pref.getBoolean("saveLogin", false);
if (saveLogin == true) {
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLoginCheckBox.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Constants.clearInfo();
getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(Constants.PREF_USERNAME,
username.getText().toString())
.putString(Constants.PREF_PASSWORD,
password.getText().toString())
.putString(Constants.PREF_CHECKED, "TRUE")
.commit();
if (username.getText().toString().trim().equals("")) {
username.setError(Html
.fromHtml("Please Enter Username"));
username.requestFocus();
} else if (password.getText().toString().trim()
.equals("")) {
password.setError(Html
.fromHtml("Please Enter Password"));
password.requestFocus();
} else {
if (Constants
.checkInternetConnection(WiztangoActivity.this)) {
Constants.userpass = password.getText()
.toString();
new AuthenticData().execute();
} else {
WiztangoBaseApplication.ShowThisDialog("Error",
"Please check internet connection.");
}
if (saveLoginCheckBox.isChecked()) {
prefEditor.putBoolean("saveLogin", true);
prefEditor.putString(Constants.PREF_USERNAME,
username.getText().toString());
prefEditor.putString(Constants.PREF_PASSWORD,
password.getText().toString());
saveLoginCheckBox.setChecked(true);
prefEditor.commit();
} else {
SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove(Constants.PREF_USERNAME);
editor.remove(Constants.PREF_PASSWORD);
editor.commit();
}
}
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
Inbuilt Patterns Provides Email Validation like:
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
emailEditText.setError("Invalid Email");
emailEditText.requestFocus();
}
Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882
It says:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You can use this code for check is Valid Email or not:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Best Approach
Validate email and isEmpty in one method.
public final static boolean isValidEmail(CharSequence target)
{
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Try out the below method to validate the Email address.
private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
if (!m_matcher.matches() && editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Try this code:--
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}

Boolean function not returning proper value

I am using following function which uses boolean value.
int recFound=0;
public Boolean CheckUser(String uName,String password)
{
try
{
statement=conn.createStatement();
resultSet=statement.executeQuery("select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'");
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}
I am calling this function through:
boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString());
if(isValidUser)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
When i pass this function proper values its not making recFound=1;
And in last condition although recFound==0 it enters in else condition and returns true.
But while assigning this value to caller functions return value it assigns false.
Means it makes , boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString()); to be false.
isValidUser should get true in such case.
Please help me.
Hi Shrimant Bajirao Peshawe - I,
change the statement "if(resultSet.getRow()>0)" to "if(resultSet. next ())" then try it.
Reference : Refer
you are calling a boolean function in your CheckUser method so its returns true or false value..
Jo just returns true value in that function.
you can also check it with:
if(isValidUser==true)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
and print a value isValidUser in log that which value it is getting
Try Follwing code...
int recFound = 0;
public boolean CheckUser(String uName, String password) {
try {
statement = conn.createStatement();
resultSet = statement.executeQuery("select count(*) from UserMaster where username LIKE '" + uName + "' and password LIKE '" + password + "'");
if (resultSet.getRow() > 0) {
recFound = 1;
} else {
recFound = 0;
}
if (recFound > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
and
if(con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString())) {
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
Change:
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
to:
if(resultSet.getRow()>0)
{
return true;
}
else
{
return false;
}
Remove conditions checking recFound in catch()
This should solve your problem.
Replace code
if(resultSet.getRow()>0){
recFound=1;
} else {
recFound=0;
}
to
if(resultSet.next()){
return true;
} else {
return false;
}
Try to initialize the
isValidUser to false at the begining
also log the value of resultSet.getRow() and recFound before returning it caller.
you can also try to use cusrsor like below
int recFound=0;
private SQLiteDatabase mDb;
public Boolean CheckUser(String uName,String password)
{
try
{
String sql="select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'";
Log.i(TAG,"Executing Query : "+sql);
mCur = mDb.rawQuery(sql, null);
Log.i(TAG,"Query Executed Successfully");
if(mCur!=null)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}

Categories

Resources