Error while posting variable from android client to php server - java

I want to make an activity to change user profil. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
public class ProfilActivity extends AppCompatActivity {
private EditText editTextNama, editTextEmail, editTextPassword, editTextNohp;
private Button Simpan;
private static final String PROFIL_URL = "http://vrai-dev.000webhostapp.com/koneksi_profil.php";
List<Profil> profilList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
Button back = (Button) findViewById(R.id.profil_back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ProfilActivity.this, MenuActivity.class);
startActivity(i);
}
});
profilList = new ArrayList<>();
getEmail();
editTextNama = (EditText) findViewById(R.id.profil_username);
editTextEmail = (EditText) findViewById(R.id.profil_email);
editTextPassword = (EditText) findViewById(R.id.profil_password);
editTextNohp = (EditText) findViewById(R.id.profil_nohp);
Simpan = (Button) findViewById(R.id.profil_simpan);
Simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
updateProfil();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void getEmail(){
final String email = "a";
StringRequest stringRequest = new StringRequest(Request.Method.POST, PROFIL_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loadProfil();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void loadProfil() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, PROFIL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray profil = new JSONArray(response);
JSONObject profilObject = profil.getJSONObject(0);
String foto_user = profilObject.getString("foto_user");
String username = profilObject.getString("username");
String email = profilObject.getString("email");
String password = profilObject.getString("password");
String nohp = profilObject.getString("nohp");
Profil viewProfil = new Profil(foto_user, username, email, password, nohp);
profilList.add(viewProfil);
editTextNama.setText(username);
editTextEmail.setText(email);
editTextPassword.setText(password);
editTextNohp.setText(nohp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfilActivity.this, error.getMessage() + "Error Load Profil", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}

Had the same problem could not figure what was wrong, but this worked for, dont forget to add the dependency in the gradle file
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(com.android.volley.Request.Method.POST, YOUR_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// do work here
} catch (JSONException e) {
e.printStackTrace();
Log.d("Response", "failed: " + response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("title", title);
return params;
}
};
queue.add(postRequest);
** implementation 'com.he5ed.lib:volley:android-cts-5.1_r4'
**

Try to modify your loadProifle() method like below
// define below variable to globally
String mRequestBody=null;
private void loadProfil() {
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("namekey", "paste here name");
jsonBody.put("emailkey", "paste here email");
jsonBody.put("passkey", "paste here password");
jsonBody.put("nokey", "paste here number");
mRequestBody = jsonBody.toString();
}catch(JSONException e){
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, PROFIL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray profil = new JSONArray(response);
JSONObject profilObject = profil.getJSONObject(0);
String foto_user = profilObject.getString("foto_user");
String username = profilObject.getString("username");
String email = profilObject.getString("email");
String password = profilObject.getString("password");
String nohp = profilObject.getString("nohp");
Profil viewProfil = new Profil(foto_user, username, email, password, nohp);
profilList.add(viewProfil);
editTextNama.setText(username);
editTextEmail.setText(email);
editTextPassword.setText(password);
editTextNohp.setText(nohp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfilActivity.this, error.getMessage() + "Error Load Profil", Toast.LENGTH_LONG).show();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
};
Volley.newRequestQueue(this).add(stringRequest);
}

Here is my php code for getting email variable.
Is there something wrong?
<?php
define('DB_HOST','Localhost');
define('DB_USER','id9815170_phpjember');
define('DB_PASS','phpjember');
define('DB_NAME','id9815170_phpjember');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
die('Unable to connect to database ' . mysqli_connect_error());
}
$email = $_POST['email'];
$stmt = $conn->prepare("SELECT foto_user, username, email, password, nohp FROM datauser WHERE email='$email';");
$stmt->execute();
$stmt->bind_result($foto_user, $username, $email, $password, $nohp);
$profil = array();
while($stmt->fetch()){
$temp = array();
$temp['foto_user'] = $foto_user;
$temp['username'] = $username;
$temp['email'] = $email;
$temp['password'] = $password;
$temp['nohp'] = $nohp;
array_push($profil, $temp);
}
echo json_encode($profil);
?>

Related

Access data sent from stringRequest

I am trying to access data sent from stringRequest here:
public class ProductDetailActivity extends AppCompatActivity {
String cart_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_cart.php";
String favorites_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_favorites.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra(EXTRA_URL);
String email = intent.getStringExtra("user");
final int product_id = intent.getIntExtra(EXTRA_ID, 0);
String name = intent.getStringExtra(EXTRA_NAME);
Double price = intent.getDoubleExtra(EXTRA_PRICE, 0);
String description = intent.getStringExtra(EXTRA_DESCRIPTION);
ImageView imageView = findViewById(R.id.image_view);
TextView textViewName = findViewById(R.id.text_view_name);
TextView textViewPrice = findViewById(R.id.text_view_price);
TextView textViewDescription = findViewById(R.id.text_view_description);
Button add_cart = findViewById(R.id.add_cart);
Button add_favorites = findViewById(R.id.add_wishlist);
add_cart.setTag(email);
textViewName.setText(name);
textViewPrice.setText(price + "€");
textViewDescription.setText(description);
add_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = view.getTag().toString();
add_to_cart(email, product_id);
}
});
add_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add_to_favorites();
}
});
}
private void add_to_cart(final String e, final int id) {
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("user", e);
jsonBody.put("product", id);
final String requestBody = jsonBody.toString();
} catch (JSONException ex) {
ex.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, cart_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(ProductDetailActivity.this,"successfully Add Into Cart",Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductDetailActivity.this, "Could not add item into cart", Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("user", e);
params.put("product", String.valueOf(id));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void add_to_favorites() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, favorites_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(ProductDetailActivity.this, "Successfully added into Favorites", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductDetailActivity.this, "Could not add item into favorites", Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And here I try to access the data in my PHP file:
<?php
include_once "database_connect.php";
$email = $_POST["user"];
$product_id = $_POST["product"];
$sql = "SELECT * FROM users WHERE email = '$email';";
$result= mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
$user_id = $row['user_id'];
$count=mysqli_num_rows($result);
if($count>0){ /*if product is already in cart */
echo "Product already in cart";
}
else {
$add_to_cart="INSERT INTO cart (user_id,product_id,quantity) VALUES ('$user_id','$product_id','1')";
if(!mysqli_query($conn,$add_to_cart))
{
echo "Can't add product to cart";
}
else
{
echo "Product successfully added to cart";
}
}
What happens is that the query is successfully run but inserts 0 both on user_id and product_id positions.
What Am I doing wrong?
Thank you in advance!
Beware of SQL injection! Use prepared statements to protect your database.
To check if a product is already in the cart for a particular user you could change your first sql query to something like this (written as a prepared statement):
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT c.quantity FROM cart c
JOIN users u ON u.user_id = c.user_id
WHERE c.product_id = ? AND u.email = ?");
$stmt->bind_param("is", $product_id, $email);
// 'i' means integer and 's' means string
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
// product exists in cart
}
$stmt->close();

SignUp rest service is not working when rest call is made from Android Application

I create project in android studio and use Volley for signup and login
I can login in my android app with email and password that i insert in database with phpMyadmin But signup in android doesn't insert email and password to database!
this is my LoginDialog.java code :
public class LoginDialog extends DialogFragment {
EditText edtEmail, edtPass;
Button btnSignup, btnLogin;
OnSignupClicked onSignupClicked;
View view;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
view = LayoutInflater.from(getContext()).inflate(R.layout.login_dialog, null);
setupViews();
builder.setView(view);
return builder.create();
}
private void setupViews() {
btnSignup = (Button) view.findViewById(R.id.btn_loginDialog_signup);
edtEmail = (EditText) view.findViewById(R.id.edt_loginDialog_email);
edtPass = (EditText) view.findViewById(R.id.edt_loginDialog_pass);
btnLogin = (Button) view.findViewById(R.id.btn_loginDialog_login);
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = edtEmail.getText().toString();
String pass = edtPass.getText().toString();
userSignup(email, pass);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login(edtEmail.getText().toString(), edtPass.getText().toString());
}
});
}
private void login(final String myEmail, final String pass) {
String url = "http://192.168.1.101/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("not found")) {
Toast.makeText(getContext(), "پست الکترونیک یا رمز عبور اشتباه است", Toast.LENGTH_SHORT).show();
} else {
onSignupClicked.onClicked(response);
dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("LOG", "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", myEmail);
params.put("pass", pass);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
public void setOnSignupClicked(OnSignupClicked onSignupClicked) {
this.onSignupClicked = onSignupClicked;
}
private void userSignup(final String email, final String pass) {
String url = "http://192.168.1.101/signup.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG", "onResponse: "+response);
onSignupClicked.onClicked(response);
dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("LOG", "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("pass", pass);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
public interface OnSignupClicked {
void onClicked(String email);
}
}
And this my signup.php code :
<?php
include "connect.php";
$email = $_POST["email"];
$pass = $_POST["pass"];
$query = "INSERT INTO user(email,pass)VALUES (:email,:pass)";
$res=$connect->prepare($query);
$res->bindParam(":email",$email);
$res->bindParam(":pass",$pass);
$res->execute();
if($res){
echo $email;
}else{
echo "error";
}
Please guide me how can i fix signup to connect with database :X
Your server side code had bugs. I fixed it
<?php
$connection = mysqli_connect('localhost','root','password','user') or die('connecition err');
$email = $_POST['email'];
$pass = $_POST['pass'];
$sql = "INSERT INTO `user` (`email`,`pass`) VALUES ('$email','$pass')";
$query = mysqli_query($connection,$sql);
if($query){
echo $email;
}else{
echo "no";
}
?>

getParams() with JsonArrayRequest

I am trying to get the response from the server based on the data I send it, I am able to get a response from the server, but the server doesn't seem to be receiving the values in the getParams().
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Toast.makeText(getContext(), selectedUniversityItem.getmUniversityValue(), Toast.LENGTH_SHORT).show();
params.put("schoolUniversity", selectedUniversityItem.getmUniversityValue());
params.put("key", key);
return params;
}
};
queue.add(jsonRequest);
The method I would suggest in this case is to pass the parameters in the URL of your code and remove the getParams() method.
So, your modified code looks like;
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url+"?schoolUniversity="+selectedUniversityItem.getmUniversityValue()+"&key="+key,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
};
queue.add(jsonRequest);
Hopefully, this will work. Good Luck :)

How to Post raw data using volley

My API working correctly but when i send data using android app its not inserting data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { JSONObject jsonBody = new JSONObject();
try {
`jsonBody.put("ID", "Android Volley Demo");
jsonBody.put("Name", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
That is my API.Its working correctly.
public HttpResponseMessage Post([FromBody]Login log)
{
db.Logins.Add(log);
db.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, log);
message.Headers.Location = new Uri(Request.RequestUri + log.ID.ToString());
return message;
}
This is my Code i am Posting data but not inserting in SQL Server but when i test API by sending raw data its working correctly.
Try this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
Log.i("VOLLEY Response : ", ServerResponse);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("VOLLEY ErrorResponse : ", volleyError.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Name", "BNK");
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(context);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
Check this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("firstkey", "firstvalue");
jsonBody.put("secondkey", "secondobject");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}

How to return serverAnswer?

How do I return serverAnswer behind onResponse?
Because in onResponse, serverAnswer gets data, but behind onResponse it's an empty variable...
For example, if I try to show a Toast with serverAnswer in onResponse, it's alright, serverAnswer has data from JSON string. But if try to show a Toast with serverAnswer behind onResponse - I get an empty Toast.
And addUser returns an empty String too.
public String addUser(final String username, final String email, final String password, final Context context) {
StringRequest request = new StringRequest(
Request.Method.POST,
REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonObject = new JSONObject(response);
final JSONObject status = jsonObject.getJSONObject("Result");
serverAnswer = status.getString("Server answer");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverAnswer = error.getMessage();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_USERNAME, username);
params.put(KEY_EMAIL, email);
params.put(KEY_PASSWORD, password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
return serverAnswer;
}

Categories

Resources