Issue Sending data to mysql in android studio - java

I am currently building an app for my university project and I am well and truly stuck. I am currently trying to send data from my apps sign up page to my Mysql database, I have gotten as far as being able to connect due to error logs showing that a connection was successful but no data is being sent to the database?
I have tried multiple ways of sending the data through php but it doesn't seem to make any difference. I was hoping maybe someone could point out my mistake and help me get past this hurdle I have been stuck on for so long.
Signup.java
package com.example.projectv1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SignUp extends AppCompatActivity {
ImageView nxtPage;
EditText Fname;
EditText Lname;
EditText Email;
EditText Password;
EditText RePassword;
private String sendURL = "https://tg322.brighton.domains/AppPHP/get_data.php";
private RequestQueue requestQueue;
private static final String TAG = SignUp.class.getSimpleName();
int success;
private String TAG_SUCCESS = "Success";
private String TAG_MESSAGE = "Message";
private String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
nxtPage = (ImageView) findViewById(R.id.NextPage);
Fname = (EditText) findViewById(R.id.editTextFName);
Lname = (EditText) findViewById(R.id.editTextLName);
Email = (EditText) findViewById(R.id.editTextEmail);
Password = (EditText) findViewById(R.id.editTextPassword);
RePassword = (EditText) findViewById(R.id.editTextRePassword);
requestQueue = Volley.newRequestQueue(getApplicationContext());
nxtPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startActivity = new Intent(SignUp.this, HomePage.class);
startActivity(startActivity);
sendData();
}
});
}
//public void GetData(){
// TempFname = Fname.getText().toString();
// TempLname = Lname.getText().toString();
// TempEmail = Email.getText().toString();
// TempPassword = Password.getText().toString();
// }
private void sendData(){
StringRequest request = new StringRequest(Request.Method.POST, sendURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jobj = new JSONObject(response);
success = jobj.getInt(TAG_SUCCESS);
if(success == 1){
Toast.makeText(SignUp.this, jobj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SignUp.this, jobj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(SignUp.this, "Error Occured " + e, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(SignUp.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("F_Name" , Fname.getText().toString());
params.put("L_Name" , Lname.getText().toString());
params.put("Email" , Email.getText().toString());
params.put("Password" , Password.getText().toString());
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
requestQueue.add(request);
}
}
DatabaseConfig.php
<?php
$HostName = "localhost";
$HostUser = "tg322_admin";
$HostPass = "1234";
$DatabaseName = "tg322_AndroidAppDatabase";
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if(!$con){
echo "Error occured in connection";
}
?>
get_data.php
<?php
include "DatabaseConfig.php";
class user{}
$fname = ($_POST['F_Name']);
$lname = ($_POST['L_Name']);
$email = ($_POST['Email']);
$pass = ($_POST['Password']);
$query = "INSERT INTO 'Login_Details' ('id' , 'F_Name' , 'L_Name' , 'Email' , 'Password') values (NULL, '".$fname."' , '".$lname."' , '".$email."' , '".$pass."')";
mysqli_query($con,$query);
if($query){
$response=new user();
$response->success=1;
$response->message="Successfully uploaded";
die(json_encode($response));
}else{
$response=new user();
$response->success=0;
$response->message="Failed to upload";
die(json_encode($response));
}
mysqli_close($con);
?>
This is the result when running my app:
Error Occured org.json.JSONException: No value for Success
Edit
After adding error_reporting(E_ALL); to both php scripts, I am confident that the error does not lie with the php code as no error is being reported. {"success":1,"message":"Successfully uploaded"} This is the response from my php code so I am connecting to the database successfully but I am unsure what the issue is with my android studio code.

Related

How can I get JSONarray values from Database through the php and convey the JSONarray to the listview?

How can I get JSONarray values from Database through the php and convey the JSONarray to the listview?
Hello, I am making an Android application and I faced some problems that I cannot know what is the cause.
So here is what I want to do. I wanna get the JSONarray through the php file from the database and show the elements of it into the listview of android. The array that I wanna get looks like this.                                                                                
[{"success":true,"roomNum":2,"departTime":"2019-07-15 13:30:00","messageText":"학교 정문에서 20분까지 만나요.","peopleNum":2,"placeNum":2},{similar contents}, {similar contents}, {similar contents}]
It is the array consisted of another array which has keys and values. To get the array from the database I wrote this php file and It works. (I upload this php file at the DB that I'm using)
<?php
$con = mysqli_connect("localhost", "******", "********", "********");
$statement = mysqli_prepare($con, "SELECT roomNum, departTime, messageText, peopleNum, placeNum
FROM OUTGOING WHERE departTF = FALSE AND peopleNum<4");
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $roomNum, $departTime, $messageText, $peopleNum, $placeNum);
$response = array();
$result = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["roomNum"] = $roomNum;
$response["departTime"] = $departTime;
$response["messageText"] = $messageText;
$response["peopleNum"] = $peopleNum;
$response["placeNum"] = $placeNum;
$result[] = $response;
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
However, when I try to get the array into the below class of Android, I cannot see the elements(which are arrays) in the list view. Below codes are the code I wrote. I guess it is the matter of usage of Volley. Can you guys help me?
package com.example.sharetaxi;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class GagyungActivity extends AppCompatActivity {
static final String[] LIST_MENU = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gagyung);
final Intent intent = getIntent();
final String userID = intent.getStringExtra("userID");
final ArrayList<String> list = new ArrayList<String>();
ListView listview = (ListView) findViewById(R.id.taxilist);
TextView title = (TextView) findViewById(R.id.title);
Response.Listener<JSONArray> responseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONArray item = response.getJSONArray(i);
list.add(item.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
};
};
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, list);
listview.setAdapter(adapter);
GagyungRequest gagyungRequest = new GagyungRequest(responseListener);
RequestQueue queue = Volley.newRequestQueue(GagyungActivity.this);
queue.add(gagyungRequest);
};
}
Here is additional code for the communication with the DB.
package com.example.sharetaxi;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import java.util.HashMap;
import java.util.Map;
public class GagyungRequest extends JsonArrayRequest{
final static private String URL = "http://000000000/Listview.php";
public GagyungRequest(Response.Listener<JSONArray> listener){
super(Method.POST, URL, null, listener, null);
}
}

How to fix org.json.JSONException: on Volley?

I am developing Login on android via connection with php (web).
Code
package com.example.salmakhalil.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
private EditText email,password;
private Button btn_login;
private TextView link_regist;
private ProgressBar loading;
private static String URL_LOGIN="http://192.168.8.101/android_register_login/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loading=findViewById(R.id.loading);
email=findViewById(R.id.email);
password=findViewById(R.id.password);
btn_login=findViewById(R.id.btn_login);
link_regist=findViewById(R.id.link_regist);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail=email.getText().toString().trim();
String mPass=password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty()){
Login(mEmail,mPass);
}
else {
email.setError("Please insert email");
password.setError("Please insert Password");
}
}
});
link_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
});
}
private void Login(String email, String password){
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
//I think here facing a problem
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray=jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i=0; i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email=object.getString( "email").trim();
Toast.makeText(LoginActivity.this,
"Success Login. \nYour Name : "
+name+"\nYour Email : "
+email, Toast.LENGTH_SHORT)
.show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this, "Error!!! " +e.toString(),
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!! " +error.toString(),
Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
When I click on the login Button, its showing thee error
org.json.JSONException: No value for success.
I'm all the day trying to fix it. I have read other posts on Stack, no one helped me. I hope you can help me. Thanks.
Apparently the jsonObject your receive in onResponse() does not have a value for entry "success"
You should use the method jsonObject.optString("success"); instead of jsonObject.getString("success");
optString("success") returns the empty string ("") if the key "success" doesn't exist. getString("success") on the other hand throws a JSONException.
Can you share the response that is supposed to get. I think the response doesn't contain any field name "success". Query on postman to get response otherwise talk to your back end developer.

JSON Issue - how to fix that?

This is my code for getting the data from JSON, it will contain only one row,
but it will give output for only "pro_name" for left of the values it will give just dots(......).
package com.example.sh_enterprises;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Detailes extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
public static String URL_PRODUCTS, pass1,pass2 ;
public static String ptopic,psubcode;
private static ProgressDialog progressDialog;
//a list to store all the products
List<pro_data> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailes);
Intent i = getIntent();
pass1 = i.getStringExtra("pro_id");
//Toast.makeText(this,"HI THIS IS "+pass,Toast.LENGTH_SHORT).show();
//URL_PRODUCTS = "https://premnathindia.000webhostapp.com/Api.php?p1="+pass;
URL_PRODUCTS = "http://192.168.225.25/prem/Api.php?p1="+pass1+"&p2=det";
Toast.makeText(this, URL_PRODUCTS, Toast.LENGTH_SHORT).show();
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
prefConfig product = new prefConfig(this);
String str = product.read_ret_id();
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < 1; i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
product.getString("pro_id");
String st;
TextView a = findViewById(R.id.pro_name);
TextView b = findViewById(R.id.weight);
TextView c = findViewById(R.id.base_amount);
TextView d = findViewById(R.id.mass_amonut);
TextView e = findViewById(R.id.brand);
TextView f = findViewById(R.id.catogery);
String st1 = product.getString("pro_name");
a.setText(st1);
st = product.getString("weight");
b.setText(st);
st = product.getString("total_amount");
d.setText(st);
//st = product.getString("pro_img_url");
st = product.getString("base_amount");
c.setText(st);
//st = product.getString("disc");
st = product.getString("brands");
e.setText(st);
st = product.getString("categories");
f.setText(st);
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void downme_ooi(View view) {
String pro_id = ((TextView) view).getText().toString();
Intent i = new Intent(this,Detailes.class);
i.putExtra("pro_id",pro_id);
startActivity(i);
}
public void go_back(View view) {
super.onBackPressed();
}
}
Sorry I made the Mistake that in TextView I put the text as password .

java.io.ioexception unexpected end of stream on com.android.okhttp.address #f32949bd

Hello , I am making a android application using Mysql database , where i am trying to make registration of the user !! can anyone help me plz
i am getting this error when i click on Register button : java.io.ioexception unexpected end of stream on com.android.okhttp.address #f32949bd
This is my code :
package androidloginandregistration.inducesmile.com.enpascheres;
/**
* Created by User on 10/12/2017.
*/
public class Constants {
public static final String ROOT_URL ="http://192.168.1.3/android/v1/registerUser.php";
public static final String URL_REGISTER = ROOT_URL+"registerUser.php";
}
and this is the main activity:
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextUsername,editTextEmail,editTextPassword;
private Button buttonRegister;
private ProgressDialog progressDialog;
#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);
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) {
try {
JSONObject jsonObject= new JSONObject(response);
Toast.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();
}
}

I am having problems inserting data in my database tables , and passing information from android studio to database

Below is my register class for user registration that, in the class when the user clicks register it gets the information from the field and passes it to register request (register request code posted below ), i do not get anything added to the tables after executing my code in android studio.
package com.example.user.emaillogin;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etemail =(EditText) findViewById(R.id.etemail);
final EditText etpassword =(EditText) findViewById(R.id.etpassword);
final EditText etname =(EditText) findViewById(R.id.etname);
final Button buttonregister =(Button) findViewById(R.id.buttonregister);
buttonregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etname.getText().toString();
final String email = etemail.getText().toString();
final String password = etpassword.getText().toString();
Response.Listener<String> ResponseListener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
Intent intent = new Intent(Register.this,MainActivity.class);
Register.this.startActivity(intent);
} else{
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setMessage("Register failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Registerrequest registerRequest = new Registerrequest(name, email, password, ResponseListener);
RequestQueue queue = Volley.newRequestQueue(Register.this);
queue.add(registerRequest);
}
});
}
}
this Register Request class allows me to make a request to my register.php(code posted below) file on the server and get response as a string and i have uploaded the php file to my server
package com.example.user.emaillogin;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by User on 07/02/2017.
*/
public class Registerrequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://picandlaugh.co.uk/register.php";
private Map<String, String> params;
public Registerrequest(String name, String email, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name",name);
params.put("email",email);
params.put("password",password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
below is my register.php code andi did include the actual host, username, password etc in the actual code but removed it for security purposes,
<?php
$con = mysqli_connect("HOST", "USERNAME", "PASSWORD", "DB");
$name = $_POST["name"];
$email = $_POST["mail"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, " INSERT INTO WINKEL (name, mail, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>

Categories

Resources