in my app i have two editbox in which the user types the email and password. The values are send to an URL and if the return values is success i am moving to a new activity, else if the return value is Email And Password Not Match! i want to show an alert box that emailand pwd mismatches.
For this, after getting the xml file from the network using sax parser i am doing parsing the and if the return value is "Email And Password Not Match!", i am storing this in a constant names as ERROR_VALUE.
i have already stored the value in a String constant as follows
public static String ERROR_CONST = "Email And Password Not Match!";
now i am comparing those values and showing an alert box,
if (ERROR_CONST.contentEquals(ERROR_VALUE))
{
alertbox();
}
after this i am using the else part to move to a new activity, my app gets crashed at this part only
else if(ERROR_VALUE == null)
{
Intent myIntent = new Intent(getBaseContext(), Add.class);
startActivityForResult(myIntent, 0);
finish();
}
}
how to use else condition successfully in my app, please help me friends
Well when comparing 2 strings its always a good idea to use
s1.compareToIgnoreCase(s2);
reading your post I would suggest you use enum or constants
public static final ERROR_CODE_INVALIDE_LOGGIN = 1;
to compare rather that strings.
Comparing strings is tedious (have to be careful that your comparing the characters and not references etc.). As comparing 2 int is easy and takes less time
I checked quickly in the javaDoc
contentEquals compares your String to a StringBuffer
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#contentEquals(java.lang.StringBuffer)
as
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#compareTo(java.lang.String)
Compares the actual string letters
other edit (sorry about that)
if your code is
if (ERROR_CONST.contentEquals(ERROR_VALUE))
{
alertbox();
}
else if(ERROR_VALUE == null)
{
Intent myIntent = new Intent(getBaseContext(), Add.class);
startActivityForResult(myIntent, 0);
finish();
}
then you have a problem when ERROR_VALUE is == null.
you pass null in contentequals and I'm guessing Java tries to convert null to StringBuffer and crashes.
what you want to do it
if(ERROR_VALUE == null)
{
Intent myIntent = new Intent(getBaseContext(), Add.class);
startActivityForResult(myIntent, 0);
finish();
}else if (ERROR_CONST. equalsIgnoreCase(ERROR_VALUE))
{
alertbox();
}
this way you avoid any null pointer exceptions and your compare will work just fine
Related
I am trying to make a sign in page for an android app. My team leader has decided to make this with a webservice.
Whenever a uses logs in, a request is sent, with 3 possible responses:
0: Wrong Password
20: Wrong username
otherwise: a UUID
I am trying to validate the results given back by the webservice like this:
String resultString = result.toString();
if (resultString.equals("20")) {
Toast.makeText(getBaseContext(), "Het ingevulde emailadres klopt niet!", Toast.LENGTH_LONG).show();
return;
} else if (resultString.equals("0")) {
Toast.makeText(getBaseContext(), "Het ingevulde wachtwoord klopt niet!", Toast.LENGTH_LONG).show();
return;
} else {
Toast.makeText(getBaseContext(), "Debug, klopt", Toast.LENGTH_LONG).show();
return;
}
Seems like basic code to me. However, this code always shows the bottom statement, so it lets the first 2 pass as false.
For debugging purposes, am also returning the resultString to my console. (removed that line in the sample). There I can very obviously see that the result given back is in fact 20.
How can it be that such simple code does not do what I want it to do?
Thanks.
The code seems to be ok... Maybe a white space in the result?
Try trimming the resultString.
which es 20, result or resultString?
As an advice, it is usually better do "".equals(object) because otherwise, if the object is null it will throw NullpointerExceptcion
Regards
Response is not exactly the string you are comparing which are "0" and "20". but the response is
0: Wrong Password
20: Wrong username
otherwise: a UUID
if you want to compare the string then it should be
Options : 1
String resultString = result.toString();
if (resultString.equals("20: Wrong username")) {
// code
} else if (resultString.equals("0: Wrong Password")) {
// code
} else {
// code
}
Option : 2
Instead of eqauls you should use contains
String resultString = result.toString();
if (resultString.contains("20")) {
// code
} else if (resultString.contains("0")) {
// code
} else {
// code
}
I agree with all of the above - the code does look good.
Try using String.compareTo and look at the int returned value to check for hidden differences.
Also, try printing String.toCharArray + String.length to identify extra characters.
If you are taking the complete string returned from web service without extracting the code (0 or 20) then you need to replace 'equals' with 'contains'.
I want to make a diet helper app for android devices, using android studio and
I need ideas on what to use to implement the login/register system, I followed a tutorial on youtube but it was outdated and I ended up wasting my time, then I've read on google, that android studio has a library called volley that I can use with PHP and MySql to make the login system.
Do you have other ideas, or is that the best one to go with?
I'm open to suggestions so shoot!
Update:
I've created a post about how to do this using a PHP backend for your Android application. https://keithweaver.ca/posts/4/android-php-custom-login
Additionally to the link above, this is how you can setup a server.
https://github.com/kweaver00/tutorials/blob/master/setup-server.md
https://keithweaver.ca/posts/9/setup-ubuntu-server-quickly
Original Post:
This is one solution and isn't guaranteed to be the best.
You can really use anything to communicate with a server. Async Tasks or Retrofit are both popular.
Assuming you have set up a server with a LAMP stack. Make sure you have an SSL so you don't pass user information that isn't encrypted.
Create a user table in mysql
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
pass varchar 250 default->null
signupdate date default-> null
Create a log in sessions table of some sort
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
token varchar 250 default->null
addedDate date default->null
Create a log in php script (I know this probably isnt the best way to right php code)
$connection = mysqli_connect("localhost", "phpmysqluser", "password", "dbname") or die("Error 404: unable to connect");
$username = $_POST['user'];
$pass = $_POST['pass'];
//add code to remove slashes and etc.
$result = mysqli_query($connection, "SELECT * FROM userTable WHERE user='$username' AND pass='$pass'") or die("Error: this line has error");
class response{
public $loggedin =0;
public $message = "";
}
$response = new response();
if(mysqli_num_rows($result) == 1){
$logInToken = generateLogInToken();
//have a function that creates a unique token and stores it for X days or minutes
$response->loggedin = 1;
$response->message = $logInToken;
}else{
$response->message = "wrong info";
}
echo json_decode($response);
This should output a json file like this depending on your user and pass variables.
{
"loggedin" : 1,
"message" : "asdnlansdkansd"
}
Right another script that passes in the log in token and user name to check if it's valid.
$connection .... //same as above
//well it really should be a include_once cause if you change credentials
$token = $_POST['token'];
$user = $_POST['user'];
$registeredDate = "";
$today = date('Y-m-d');
$result = mysqli_query($connection, "SELECT * FROM tokenTable WHERE user='$user' AND token='$token'") or die("Error...");
class response{
public $status = 0;
}
$response = new response();
if(mysqli_num_rows($result) == 1){
//check token has been register today and if not sign them out
while($row = mysqli_fetch_array($result)){
$registeredDate = $row['addedDate'];
}
if($registeredDate == $today){
//token is valid
$response->status = 3;
}else{
//expired
$response->status = 2;
}
}else{
//user and token are not valid
$response->status = 1;
}
echo json_decode($response);
Giving a json object like:
{
"status" : 3
}
In your Android app on open, run the code to check if the account is valid if there is anything stored locally. Or just go to log in screen.
On splash screen in the onCreate (you dont need a splash screen, its actually not recommended but its the easiest way to explain the process):
if(userNameAndTokenStoredInSharedPref()){
String token = getTokenFromSharedPref();
String userName = getUserNameFromSharedPref();
checkAgainstServer(token, userName);
}else{
Intent openLogInWindow = new Intent(this, LogInActivity.class);
startActivity(openLogInWindow);
}
still in the slash activity but out of the oncreate:
protected void checkAgainstServer(String token, String user){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(token, user, new Callback<UserStatusCallBack>() {
#Override
public void success(UserStatusCallBack userStatusCallback, retrofit.client.Response response) {
if(userStatusCallback.getStatus() == 1){
//Invalid token
}else if(userStatusCallback.getStatus() == 2){
//Expired token
}else if(userStatusCallback.getStatus() == 3){
//Success
Intent openMainWindow = new Intent(this, MainActivity.class);
startActivity(openMainWindow);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The log in activity would be something like:
logBtn.setOnClickListener(new View.onClick...
String userName = userNameEditText.getText().toString().toLowerCase().trim();
String password = passwordEditText.getText().toString().trim();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)){
callServerLogInScript(userName, password);
}
userNameEditText.setText("");
logBtn.setVisibility(View.GONE);
}
lower down the file:
protected void callServerLogInScript(String user, String pass){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(user, pass, new Callback<LogInCallBack>() {
#Override
public void success(LogInCallBack logInCallback, retrofit.client.Response response) {
if(logInCallback.getLoggedIn() == 1){
//succssful
storeUserNameInSharedPref(user);
storeTokenInSharedPref(logInCallback.getMessage());
Intent openMainActivity = new Intent(this, MainActivity.class);
startActivity(openMainActivity);
}else{
//incorrect log in
logBtn.setVisibility(View.VISIBLE);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The reason for not storing the user name and password directly is if the device is rooted they can manipulate the data locally but not on your server.
It depends which you want to use. If you have your own server to host, then use php,mysql. If not, you can also use other third party which provides you to add if you know php,mysql to create.
Another option is if you don't want to use php mysql to store datas, then you can proceed with parse.com
So if you want to use parse.com, just register it. It's free to use.
Hope it will match your requirement, say for eg: if you want to create registration(everything saving in datas will be handled),you need to give exact object name that matches what you given in parse.com
Even you can also create in code itself without object name. I will show you a piece of example how to create and insert for registration..
ParseUser user = new ParseUser();
user.setEmail((txtEmail));//create an edittext and get the values in strings and store..
user.setPassword(txtPassword);//same for password
user.setUsername(txtUsername);//username
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
//completed..it has been registered
Toast.makeText(getApplicationContext(),
"Successfully Signed up, please log in.",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up Error", Toast.LENGTH_LONG)
.show();
}
}
});
Simple one if you don't want to use php,mysql. Well documentation and easy to integrate and use it. Happy coding.
FYI: Android studio is IDE for development. And volley is HTTP library that makes networking for Android.
I am developing an application in cordova but my barcode scanner from Zxing opens and closes Automatically after scanning the product in need to add a scan/exit button and a close button the scanner shouldnt open and close automatically. I also need to check if the scanned product exist in the database (SQL SERVER) and return product infomation i have tried to google but to no avail please help.the following is my code in Eclipse. I need to know how i can modify The UI and add my own control of my ZXING barcode scanner plugin i am developing in Eclipse and have a web api service hosted in IIS which i can access on my android App.Please ASAP or show me how i can modify this barcode UI to ADD my controls.
public void scan() {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
this.cordova.startActivityForResult((CordovaPlugin) this, intentScan, REQUEST_CODE);
}
My OnStartActivity code is here is the code but it seems like it is the same as yours.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, intent.getStringExtra("SCAN_RESULT"));
obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT"));
obj.put(CANCELLED, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else if (resultCode == Activity.RESULT_CANCELED) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, "");
obj.put(FORMAT, "");
obj.put(CANCELLED, true);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else {
//this.error(new PluginResult(PluginResult.Status.ERROR), this.callback);
this.callbackContext.error("Unexpected error");
}
}
}
Good Afternoon I have an app that do what you are looking for... first of all I create an intent so i can use any QR scanner I use an external app in order to get the value of the QR code here.
public void scanNow(View view) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
so in my onStartActivity for result send that info to the server side and I wait for the answer...
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if(requestCode == 0){
if(resultCode == RESULT_OK){
contents = intent.getStringExtra("SCAN_RESULT");// here is the content of the qr scanner
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
String messLoc = "Visita Guardada Con Exito";
Log.i("xZing", "contents: " + contents + " format: " + format);// Handle successful scan
Toast.makeText(this, messLoc, Toast.LENGTH_LONG).show();
new Thread(new Task()).start(); // here I start the thread for the connection
return;
}
else if(resultCode == RESULT_CANCELED);{// Handle cancel
Log.i("xZing", "Cancelled");
}
}
}
Please let me know if this help you
UPDATE:
I just started using Zbar instead Zxing. It's a whole lot easier to work with. Extremely easy to embed (no 3rd party app for the scanner). It has a lot let file to load into the project. Also, it has an included example that you can pretty much copy and paste into your code. The example is perfect for what you are trying to do and would only require a few edits to gain the functions you are looking for. So try using the zbar library.
Zbar - https://github.com/dm77/ZBarScanner
A tutorial - http://community.magicsoftware.com/en/library?book=en/Magicxpa/&page=Android_Barcode_Scanning_(Using_ZBar_SDK)_Sample.htm
The tutorial isn't that good but it helps with setting it up. NOTE: the links they have don't work if you click them..you have to copy and paste the text into your browser.
The database stuff I explained below still is relevant but ignore the parts about zxing.
Best of luck to you!
Original answer
I may be able to help somewhat for you SQL issues. Do you have any database helper set up?
First off I would google around and find a simply database example to set up the database. There are a number of good ones out there that show you how to set up a database in SQLite for android. The one I used to learn some of the basics:http://hmkcode.com/android-simple-sqlite-database-tutorial/ . You can use the example of Book to create a product class with all the values for columns that match your needs. Then you simply create automatic getters and setters with eclipse click "Source -> generate getters and setters". Onces you've done that you can use the tutorial below to set up your qr scanner. As for keeping the window open, I don't think you need to do that. Just create an activity that the scanner closes into. In that acticity you can have the output and have the scan results compared to the database.
I was able to use the tutorial http://%20http://code.tutsplus.com/tutorials/android-sdk-create-a-barcode-reader--mobile-17162 to integrate zxing into my app. Once I did that
An example of parsing the data from the qr code:
First you call the scan:
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scanQRButton){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
The scan results code then looks like this:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
scanContent = scanningResult.getContents();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
Now the finishing method for the scan button:
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scanQRButton){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
formatTxt.setText( "Scan Initiated");
contentTxt.setText(" Scan Results: " + scanContent);
if(scanContent != null){
String userid,medname,tabstaken,dob;
// Here I am breaking apart the scan results and
//saving them into variables.
//Do this then call the database for your product and compare
StringTokenizer st = new StringTokenizer(scanContent, ",");
// token 0
dob = st.nextToken();
//token 1
medname = st.nextToken();
//token 2
tabstaken = st.nextToken();
//token 3
//rxnumber
// So here you setup the db so you can access it
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
//This is used to call the results
HashMap<String,String> user = new HashMap<String, String>();
//Use a method such as getProductResults() for your case
user = db.getUserDetails();
enter code here
//An example of me storing the user
userid = user.get("uid");
//debug.setText("Userid: "+ userid+ " medname: " + medname + " tabs: " +tabstaken);
UserLogEntry userlog = new UserLogEntry(getApplicationContext(),userid,medname,tabstaken);
userlog.addUserLog();
}
}
}
If you need to see my database class let me know. Obviously this isn't the exact code you need, but it shows you how to use the results from the QR and call the DB results to do comparisons. Hopefully its helpful
I have two activities and two ParseObjects respectively. In one activity I'm saving 3 strings and in another activity I'm saving Image to the ImageView. Its getting successfully saved to Parse.com but with different ObjectIds. I want the Image to be saved in other table. and then get the image based on the mobile number. I have searched the documentation referred in the Parse.com but not able to resolve this.
final ParseObject dataObject = new ParseObject("DataObject");
dataObject.put("name", name);
dataObject.put("mobilenumber", mobileNumber);
dataObject.put("occupation", occup);
dataObject.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
// Success!
String objectId = dataObject.getObjectId();
} else {
// Failure!
}
}
});
Toast.makeText(getBaseContext(), "Data successfully saved "+ objectId, Toast.LENGTH_LONG).show();
This is the first activity. In the next activity I'm saving an image. I want the ObjectId but its says NULL everytime. Pls Help.
You can send the mobile number with intent to your next activity like :
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(LoadImg.this, "",
"Saving Image...", true);
try {
image = readInFile(path);
}
catch(Exception e) {
e.printStackTrace();
}
ParseFile file = new ParseFile("picturePath.png", image);
file.saveInBackground();
ParseObject imgupload = new ParseObject("Image");
imgupload.put("ImageFile", file);
imgupload.put("Mobilenumber", mob);
// Create the class and the columns
and in the activity you can fetch the mobile number from the intent like :
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Image");
mobileNumber = mbltxt.getText().toString();
query.whereEqualTo("Mobilenumber", mobileNumber);
ob = query.find();
How about this.
You can send the three strings as a bundle from the first activity to the next(second) activity using intent.putExtras(Bundle) or Intent.putExtra(String, String) and then in the second activity, get the extras and then save the strings and the image together into a ParseObject. This will also reduce the number of API requests to Parse.
In my app I send some intent extras from one activity to another. But some users report back that these data are always zero - even though I can see the values are alright in the sending activity.
Here's the code of the sending activity:
Intent intent = new Intent();
intent.setClass(waypointListView.this, addWaypointActivity.class);
intent.putExtra("latitude", String.format("%9.6f", globLatitude));
intent.putExtra("longitude", String.format("%9.6f", globLongitude));
startActivityForResult(intent, ACTIVITY_ADD_WAYPOINT);
And this is how it's read in the new activity:
Intent myIntent = getIntent();
String latitudeStr = myIntent.getExtras().getString("latitude");
try{
globLatitude = Float.parseFloat(latitudeStr);
} catch(NumberFormatException nfe) {
globLatitude=0f;
}
String longitudeStr = myIntent.getExtras().getString("longitude");
try{
globLongitude = Float.parseFloat(longitudeStr);
} catch(NumberFormatException nfe) {
globLongitude=0f;
}
On both my devices it works fine, but I have 3 cases of customers complaining that it doesn't work (documented in video recordings).
Any suggestions?
I tried to change the code to use getFloatExtra() instead of getString and parse it to a float, and it solved the problem. I see this is a lot more efficient, but I still don't understand why the original solution worked on some devices but not on others.
Case closed!