Access data sent from stringRequest - java

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();

Related

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";
}
?>

Error while posting variable from android client to php server

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);
?>

Android volley login registration with password confirmation

I'm currently found a problem in my android registration process, the validation seems not working fine. What i mean is that, when there is a blank field, and click register, it straight registered on my database with blank field. I'm not sure what causes it, i hope someone can help me. Below is my android java + php code
Register.java
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etPassword2 = (EditText) findViewById(R.id.etPassword2);
final Button bNext = (Button) findViewById(R.id.bNext);
final Button bBLogin = (Button) findViewById(R.id.bBLogin);
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = etUsername.getText().toString().trim();
final String Acc_Pass = etPassword.getText().toString().trim();
final String Acc_Pass2 = etPassword2.getText().toString().trim();
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
if (TextUtils.isEmpty(Username) || Username.length() < 6){
if (TextUtils.isEmpty(Username))
{
etUsername.setError("You are required to enter a username");
}
else if (Username.length() < 6)
{
etUsername.setError("Your username is too short, minimum character is 6. Please re-enter");
}
return;
} if (TextUtils.isEmpty(Acc_Pass) || Acc_Pass.length() < 6){
if (TextUtils.isEmpty(Acc_Pass))
{
etPassword.setError("Your password is empty. Please try again");
}
else if (Acc_Pass.length() < 6)
{
etPassword.setError("Your password is too short, minimum character is 6. Please re-enter");
}
return;
} if (TextUtils.isEmpty(Acc_Pass2) || !Acc_Pass2.equals(Acc_Pass)){
if (TextUtils.isEmpty(Acc_Pass2))
{
etPassword2.setError("Your password is empty. Please try again");
}
else if (!Acc_Pass2.equals(Acc_Pass))
{
etPassword2.setError("Password mismatch. Please try again");
}
return;
} else if (!success){
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed Username Unavailable")
.setNegativeButton("Retry", null)
.create()
.show();
return;
} else {
Intent intent = new Intent(RegisterActivity.this, RegisterActivity2.class);
RegisterActivity.this.startActivity(intent);
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(Username, Acc_Pass, Acc_Pass2, responeListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
bBLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
});
}
}
RegisterRequest.java
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.1.2/AppRegister.php";
private Map<String, String> params;
public RegisterRequest(String Username, String Acc_Pass, String Acc_Pass2, Response.Listener<String> listener){
super (Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("Username", Username);
params.put("Acc_Pass", Acc_Pass);
params.put("Acc_Pass2", Acc_Pass2);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
AppRegister.php
<?php
$connect = mysqli_connect("localhost", "root", "", "registering");
$Username = $_POST["Username"];
$Acc_Pass = $_POST["Acc_Pass"];
$Acc_Pass2 = $_POST["Acc_Pass2"];
function registerUser() {
global $connect, $Username, $Acc_Pass, $Acc_Pass2;
$statement = mysqli_prepare($connect, "INSERT INTO account_details (Username, Acc_Pass, Acc_Pass2) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $Username, $Acc_Pass, $Acc_Pass2);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
}
function usernameAvailable() {
global $connect, $Username;
$statement = mysqli_prepare($connect, "SELECT * FROM account_details WHERE Username = ?");
mysqli_stmt_bind_param($statement, "s", $Username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
}else {
return false;
}
}
$response = array();
$response["success"] = false;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
}
echo json_encode($response);
mysqli_close($con);
?>
Updated Register.java
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etPassword2 = (EditText) findViewById(R.id.etPassword2);
final Button bNext = (Button) findViewById(R.id.bNext);
final Button bBLogin = (Button) findViewById(R.id.bBLogin);
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = etUsername.getText().toString().trim();
final String Acc_Pass = etPassword.getText().toString().trim();
final String Acc_Pass2 = etPassword2.getText().toString().trim();
if (etUsername.getText().toString().matches("") || etPassword.getText().toString().matches("") || etPassword2.getText().toString().matches("")) {
if (TextUtils.isEmpty(Username) || Username.length() < 6) {
if (TextUtils.isEmpty(Username))
{
etUsername.setError("You are required to enter a username");
}
else if (Username.length() < 6)
{
etUsername.setError("Your username is too short, minimum character is 6. Please re-enter");
}
} if (TextUtils.isEmpty(Acc_Pass) || Acc_Pass.length() < 6) {
if (TextUtils.isEmpty(Acc_Pass))
{
etPassword.setError("Your password is empty. Please try again");
}
else if (Acc_Pass.length() < 6)
{
etPassword.setError("Your password is too short, minimum character is 6. Please re-enter");
}
} if (TextUtils.isEmpty(Acc_Pass2) || !Acc_Pass2.equals(Acc_Pass)) {
if (TextUtils.isEmpty(Acc_Pass2))
{
etPassword2.setError("Your password is empty. Please try again");
}
else if (!Acc_Pass2.equals(Acc_Pass))
{
etPassword2.setError("Password mismatch. Please try again");
}
}
} else {
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
Intent intent = new Intent(RegisterActivity.this, RegisterActivity2.class);
RegisterActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(Username, Acc_Pass, Acc_Pass2, responeListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
}
});
bBLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
});
}
}
Simply check edittext is empty or not by using following code;
if( etUsername.getText().toString().matches("") || etPassword.getText().toString().matches("") || etPassword2.getText().toString().matches("") )
{
Toast.makeText(getApplicationContext(),"Please enter all fields....",Toast.LENGTH_SHORT).show();
}
else if( ! etPassword.getText().toString().matches(etPassword2.getText().toString()))
{
Toast.makeText(getApplicationContext(),"Please enter same both password fields....",Toast.LENGTH_SHORT).show();
}
else
{
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
Intent intent = new Intent(RegisterActivity.this, RegisterActivity2.class);
RegisterActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(Username, Acc_Pass, Acc_Pass2, responeListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
}
Try to follow this snippet
On Button Click Event
if(et_Username.isEmpty() || etUsername.length() == 0 || etUsername.equals("") || etUsername == null){
Toast.makeText(SignUpActivity.this, "Field is empty",Toast.LENGTH_SHORT).show();}
else
{
SignUp();
}
Create SignUp method
public void SignUp() {
final String Username = etUsername.getText().toString().trim();
final String Acc_pass = etPassword.getText().toString().trim();
final String Acc_pass2 = etPassword2.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
JSONObject jObj = null;
try {
jObj = new JSONObject(response);
String success = jObj.getString("success");
String errorMessage = jObj.getString("message");
} else {
Toast.makeText(SignUpActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignUpActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Username", Username);
params.put("password", Acc_pass);
params.put("password2", Acc_pass2);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

How to update item in RecycleView?

I am creating Application in which I have give functionality like Facebook timeline where people can update their story and any user can like or comment on the story. Everything is working fine but what I am facing issue is that when any user update story then data of updated story get saved on server but not added in recycle view at same time. When User go back and again comes on timeline screen then list will get update. How can I solve this problem ?
Custom Adapter
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
holder.txtComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
Intent intent = new Intent(context, StoryDetailActivity.class);
intent.putExtra("storyId",ide);
context.startActivity(intent);
}
});
holder.txtCommentLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
Intent intent = new Intent(context, StoryDetailActivity.class);
intent.putExtra("storyId",ide);
context.startActivity(intent);
}
});
holder.imageLike.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
TimelineActivity t = new TimelineActivity();
final TimeLineItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
likeStory(ide,t.token);
return false;
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
private void likeStory(final String story_id, final String token) {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.likeStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_id", story_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
TimeLineActivity
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
adapter.notifyDataSetChanged();
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You need to implement some sort of polling mechanism on server end to do this. There's a workaround for it but it's not considered good practice. You can use a Timer to call your getTimeline function periodically to update the recycler view. Something like this in your onCreate:
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, page);
}
});
}
}, 0, your_time_in_milliseconds);
You can even do this asynchronously by using AsyncTask in Android.

Cannot enter data into phpmyadmin from Java class

when I run this code there's no new data in my database. I've already checked my connection and tried it using postman app its working the data entered the database. But when i tried to send data from my xml file to phpmyadmin. there's no new data tht I send in it.
when I checked my userRegister.php there's nothing wrong with it.
but still when I try submit the form there's no data in my database.
and the toast msg appear without any msg just a blank black toast msg.
private EditText editTextUsername, editTextEmail, editTextPassword;
private Button buttonRegister;
private ProgressDialog progressDialog;
private TextView textViewLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textViewLogin = (TextView) findViewById(R.id.textViewLogin);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
progressDialog = new ProgressDialog(this);
buttonRegister.setOnClickListener(this);
}
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
progressDialog.setMessage("Registering user...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View view) {
if (view == buttonRegister)
registerUser();
}
registerUser.php
require_once'../includes/DbOperations.php';
$response = array();
if ($_SERVER['REQUEST_METHOD']=='POST'){
//check user give all the info required
if(
isset($_POST['username'])and
isset($_POST['email']) and
isset($_POST['password']))
{
//operate the data further
//create db operation object
$db = new DbOperations();
//call method
if($db-> createUser(
$_POST['username'],
$_POST['password'],
$_POST['email']
)){
$response['error'] = false;
$response['message'] = "User registered successfully";
}else{
$response['error'] = true;
$response['message'] = "Some error occured please try again";
}
}else{
$response['error']= true;
$response['message']= "Required fields are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
//display error in json format
echo json_encode($response);

Categories

Resources