When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
Here are my codes:
Java code:
private Dialog alertDialog() { final AlertDialog.Builder
alertDialog = new AlertDialog.Builder(NotificationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirmation...");
// Setting Dialog Message
alertDialog.setMessage("Do you want to accept this job?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_dialog_alert);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Accept", Toast.LENGTH_SHORT).show();
// Return Result from alertdialog to database
result = "accepted";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Reject", Toast.LENGTH_SHORT).show();
dialog.cancel();
// Return Result from alertdialog to database
result = "rejected";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
return alertDialog.show(); }
/** * Background Async Task to update database * */ class
UpdateActivity extends AsyncTask {
/** * Before starting background thread Show Progress Dialog * */
#Override protected void onPreExecute() { super.onPreExecute();
pDialog = new ProgressDialog(NotificationActivity.this);
pDialog.setMessage("Sending ...");
pDialog.setIndeterminate(false); pDialog.setCancelable(true);
pDialog.show(); }
/** * Saving product * */ protected String
doInBackground(String... args) {
System.out.println("Sending...");
// getting updated data from dialog String confirmation =
result.toString();
System.out.println("Result to string..." + confirmation );
// Building Parameters List<NameValuePair> params = new
ArrayList(); params.add(new BasicNameValuePair(TAG_ID,
uid)); params.add(new BasicNameValuePair(TAG_RESULT, confirmation));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(UPDATE_URL,
"POST", params);
System.out.println("Json parsing...");
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
System.out.println("Checking...");
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), JobsAcceptedActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(), "Update successfully...", Toast.LENGTH_SHORT).show();
System.out.println("Successfully updated...");
// closing this screen
finish();
} else {
// failed to create product
//Toast.makeText(getApplicationContext(), "Update unsucessfully...", Toast.LENGTH_SHORT).show();
System.out.println("Update unsuccessfully...");
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Done!");
return null; }
/**
* After completing background task Dismiss the progress dialog
* **/ protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss(); }
} }
PHP code:
$response = array(); // check for required fields if
(isset($_POST['UID']) && isset($_POST['accept'])) {
$UID = $_POST['UID'];
$accept = $_POST['accept'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
// check if column inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Notification successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
} } else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
Q: When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
A: It sounds like you probably want a more restrictive "where" clause on your update :)
This is your one ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
My Suggession ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = '$UID'"); or
$queryString= "UPDATE notification SET accept = ".$accept." WHERE UID =".$UID;
$result = mysql_query($queryString);
Related
There is a problem with my java code, when I emptied my username and password and click login, I can still get into the main menu, if there are less with my code? where do I need to fix it? please help
LoginActivity.Java
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), info.androidhive.slidingmenu.MainActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Please write your PHP code. I think that you missed a condition !!!
Also, you can add a condition in your LoginActivity like that:
if((inputEmail.getText().toString()).isEmpty() ||
(inputPassword.getText().toString()).isEmpty())
{
Toast.makeText(LoginActivity.this,"Please fill out Username and Password !!!",
5000).show();
}
else
{
//check for login response
}
Background Information:
I am developing a small application. The way it works right now is the moment the app is launched, the user is prompted with the main activity. Then from there, the user clicks on the login button which prompts the login activity. Now in my login activity, I have set an Intent that gets the user's username and then stores it in the Shared Preferences. If the login is successful then the user goes to the mainloggedinpage where the user sees: [Welcome back {username}]
The problem is the following:
If the user is accessing the mainloggedinpage via loginactivity then you can easily see his username which is exactly what I want. But the thing is that on the main page, I have other buttons which goes to other activities. The moment the user click on any of those activities and then returns to the mainloggedin page, then all you see is: [Welcome Back {}]. His username is not displayed anymore.
My question:
Can anyone suggest a quick fix that will allow me to display the username so even when the user goes to another activity from the mainloggedinpage and then comes back to the mainloggedinpage, the user will still see: [Welcome Back {username}]?
My Code for Login Activity [This is where I am getting the username]:
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, mainpage.class);
i.putExtra("Welcome back, username", username);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My Code for mainloggedinActivity [This is where the username is displayed]:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
msuggestions = (Button) findViewById(R.id.btn_suggestions);
msuggestions.setOnClickListener(this);
mprayertimes = (Button)findViewById(R.id.btn_activityone);
mprayertimes.setOnClickListener(this);
mqibladirection =(Button)findViewById(R.id.btn_activitytwo);
mqibladirection.setOnClickListener(this);
mnewsboard = (Button) findViewById(R.id.newsboard);
mnewsboard.setOnClickListener(this);
mhadiths = (Button) findViewById(R.id.btn_activitythree);
mhadiths.setOnClickListener(this);
mchat = (Button) findViewById(R.id.btn_discussion);
mchat.setOnClickListener(this);
mallahnames = (Button) findViewById(R.id.btn_activityfour);
mallahnames.setOnClickListener(this);
// Get Username Start
TextView txt_loggedName = (TextView) findViewById(R.id.txt_loggedName);
Intent intent = getIntent();
String username = intent.getStringExtra("Welcome back, username");
txt_loggedName.setText(username);
// Get Username End
buttonLogout = (Button) findViewById(R.id.logout);
buttonLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove("username");
editor.remove("password");
editor.commit();
Message myMessage=new Message();
myMessage.obj="NOTSUCCESS";
handler.sendMessage(myMessage);
finish();
}
});
Can anyone help me out so then when a user goes to the mainpage and click on one of the button and then comes back to the mainpage, it still displays his username? :)
Don't rely on an Intent extra for storing the username, since that will only be populated directly after the user logs in.
Replace this:
Intent intent = getIntent();
String username = intent.getStringExtra("Welcome back, username");
txt_loggedName.setText(username);
With:
String username = PreferenceManager.getDefaultSharedPreferences(this).getString("username", "guest");
txt_loggedName.setText("Welcome back, " + username);
Instead of getting the username from the intent, You should get it from the SharedPreferences since you already saved it there.
so I'm using the androidhive tutorial to make a server for my app and connect to it. I have it so the server will send back different messages depending on what was sent in but I'm getting an error with it and I can't figure out why. Here is the class that the error occurs in:
class CreateNewSpot extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewSpotActivity.this);
pDialog.setMessage("Creating Spot..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String longitude = inputLong;
String latitude = inputLat;
String pavement = spinner_pavement.getSelectedItem().toString();
String traffic = spinner_traffic.getSelectedItem().toString();
String environment = spinner_enviro.getSelectedItem().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("longitude", longitude));
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("pavement", pavement));
params.add(new BasicNameValuePair("traffic", traffic));
params.add(new BasicNameValuePair("environment", environment));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
switch(success){
case 0:
//name is empty!
break;
case 1:
// successfully created product
Intent i = new Intent(getApplicationContext(),
AllSpotsActivity.class);
startActivity(i);
// closing this screen
finish();
break;
case 2:
//name has been taken
Toast.makeText(getApplicationContext(), "Name for spot has already been taken.", Toast.LENGTH_LONG).show();
break;
case 3:
//server error
Toast.makeText(getApplicationContext(), "A server error has occurred.", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "An unknown error has occurred.", Toast.LENGTH_LONG).show();
//just an unknown error
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Now I'm purposely sending in data to get success==2 but it tells me my app unexpected error has occurred. Why is this? Is it because of the pDialog is still open? I tried putting pDialog.dismiss(); above but I still get the error. Sorry if this is a simple question and thank you in advance.
Tyler
EDIT:
Logcat:
class CreateNewSpot extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewSpotActivity.this);
pDialog.setMessage("Creating Spot..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String longitude = inputLong;
String latitude = inputLat;
String pavement = spinner_pavement.getSelectedItem().toString();
String traffic = spinner_traffic.getSelectedItem().toString();
String environment = spinner_enviro.getSelectedItem().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("longitude", longitude));
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("pavement", pavement));
params.add(new BasicNameValuePair("traffic", traffic));
params.add(new BasicNameValuePair("environment", environment));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
switch(success){
case 0:
//name is empty!
break;
case 1:
// successfully created product
Intent i = new Intent(getApplicationContext(),
AllSpotsActivity.class);
startActivity(i);
// closing this screen
finish();
break;
case 2:
//name has been taken
error_msg = 0;
break;
case 3:
//server error
error_msg = 1;
break;
default:
error_msg = 2;
//just an unknown error
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
switch(error_msg){
case 0:
Toast.makeText(getApplicationContext(), "Name for spot has already been taken.", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "A server error has occurred.", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "An unknown error has occurred.", Toast.LENGTH_LONG).show();
break;
default:
break;
}
pDialog.dismiss();
}
}
You are getting unexpected error because you are showing Toast from doInBackground(), which you can't do. You never handle your UI from background in AsyncTask. Just remove your try-catch block from doInBackground() to onPostExecute() and it will work.
I am trying to do the session handling process in android.
Here I have successfully logged into through android and now i waant to handle the session of the logged in user.
this is my login_suer.java(android part)
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class login_user extends Activity{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText login_email;
EditText login_password;
Button signin;
TextView error_msg;
private static String url_create_signin= "http://10.0.2.2/android_iwant/login_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_form);
// Edit Text
login_email = (EditText) findViewById(R.id.login_email);
login_password = (EditText) findViewById(R.id.login_password);
signin = (Button) findViewById(R.id.signin);
error_msg = (TextView) findViewById(R.id.error_msg);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CheckLogin().execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login_user.this);
pDialog.setMessage("Signing in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email",login_email.getText().toString()));
params.add(new BasicNameValuePair("password", login_password.getText().toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_signin,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created users
Intent i = new Intent(getApplicationContext(), post_item.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to sign in
error_msg.setText("Incorrect username/password");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
now i need the idea to start session handling in this java file.
and the code of the server side is below: ie login_user.php
<?php
session_start();
// array for JSON response
$response = array();
if(isset($_POST['email']) && isset($_POST['password'])){
$email = $_POST['email'];
$password = $_POST['password'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
$user = $db->getUesrByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
?>
the function used in this above php file is i.e getUesrByEmailAndPassword($email, $password)
is below :
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
//return $result;
session_start();
$_SESSION['clientId'] = $result[0];
$_SESSION['logged_in'] = TRUE;
}
} else {
// user not found
return false;
}
}
Please help me to make my code working.
Any help will be appreciated.
Any link containing such problem solution can be helpful for me. thank you!
As far as I can see, your getUserByEmailAndPassword() never returns actual user data after successfull password check. //return $result; is commented out. $user is therefore null, and client receives "Incorrect email or password!" message.
Another thing. For PHP sessions to work, client has to receive and remember its session_id and send it with every request as GET or COOKIE parameter. Looking at your code, I don't see android receiving its session_id. See: http://www.php.net/manual/en/session.idpassing.php
By the way, using unescaped $email in your SQL query directly from POST is a bad idea. See: How can I prevent SQL injection in PHP?
with this Login form, an admin with (ID: 001) should get a 'AdminActivity' whereas every other userID should get a 'UserActivity', and this is the code. It's not returning the adminID for some reason. Thank you
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
UserFunctions userFunction = new UserFunctions();
String id = inputId.getText().toString();
String pswd = inputPassword.getText().toString();
JSONObject json = userFunction.loginUser(id, pswd);
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
if(id == "001"){
// Launch Admin Activity
Intent tab1 = new Intent(getApplicationContext(), AdminActivity.class);
// Close all views before launching requestActivity
tab1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tab1);
}
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_ID),
json_user.getString(KEY_NAME),
json_user.getString(KEY_EMAIL),
json_user.getString(KEY_CREATED_AT));
// Launch User Activity
Intent tab = new Intent(getApplicationContext(), UserActivity.class);
// Close all views before launching requestActivity
tab.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tab);
}else{
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
if("001".equals(id)){
// Launch Admin Activity
Intent tab1 = new Intent(getApplicationContext(), AdminActivity.class);
// Close all views before launching requestActivity
tab1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tab1);
return;
}
You can't compare Strings in Java using ==
Try something like this:
if(id.equals("001"))