Error Parsing JSON data on executing PHP script - java

this is my php script
<?php
try{
$con = new PDO('mysql:host=localhost;dbname=pfe'/*info db*/,'root'/*login*/, ''/*mdp*/);
}
catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$msg = $_GET['msg'];
$mail = $_GET['mail'];
$result = $con->prepare("INSERT INTO message ( `msg`, `mail`)
VALUES ('{$msg}', '{$mail}')");
$result->execute();
if($result == true) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
my script i think is good cause i tried it with my browser it works but with android does not insert the data
and this is java class,
EditText msg,mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText) findViewById(R.id.editText);
mail = (EditText) findViewById(R.id.editText2);
}
public void signup(View v) {
String message = msg.getText().toString();
String email = mail.getText().toString();
Toast.makeText(this, "wait...", Toast.LENGTH_SHORT).show();
new Insertinto(this).execute(message, email);
}
public class Insertinto extends AsyncTask<String, Void, String> {
private Context context;
public Insertinto(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String msg = arg0[0];
String mail = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?msg=" + URLEncoder.encode(msg, "UTF-8");
data += "&mail=" + URLEncoder.encode(mail, "UTF-8");
link = "http://192.168.43.93/dysfonction.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
this is json
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
}
when i execute it show me "Error parsing JSON data" i didn't find where is the pbm.

debug and check the result received in the postExecute(); and from next time paste the logcat as well..

Try to change this to
if($result == true) {
echo '{"query_result":"SUCCESS"}';
}else{
echo '{"query_result":"FAILURE"}';
}
this
if($result == true) {
$data = array(
'query_result' => 'SUCCESS'
);
}else{
$data = array(
'query_result' => 'FAILURE'
);
}
echo json_encode($data);
It seems to be your java code is so clear. So sent response from php code like above may be works.

in the place of
result = bufferedReader.readLine();
use
result = bufferedReader.readLine().toString();

Related

Get data from a table in sql to a textview in android studio from a specific row

I have a table in ms sql this table contains FName and FInfo i want to get th FInfo according to the FName like if the FName in the app is equal to john it gets the FInfo of john in the same row.
i have tried everything including query's and Result set but it didn't work out for me.
here is my code:
public class InsideFamily extends AppCompatActivity {
private TextView inf;
private boolean success = false; // boolean
private ConnectionClass connectionClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_family);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
inf = (TextView) findViewById(R.id.thefamilyinf);
connectionClass = new ConnectionClass();
SyncData orderData = new SyncData();
orderData.execute("");
}
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(InsideFamily.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
String gettingfam = getIntent().getStringExtra("defamily");
String query = "SELECT * FROM family where FName='" + gettingfam + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
inf.setText((rs.getString("FInfo")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String
msg)
{
progress.dismiss();
Toast.makeText(InsideFamily.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
} catch (Exception ex) {
}
}
}
}
}
the errors i get is that it brings a toast for me saying that "No Data Found!"
which means that that the result set equals null how can i fix it??
I found the answer
the wrong was in the query
because its nvarchar i have to wright
"SELECT * FROM family WHERE FName = (N'" +dta+ "')"
rather than
"SELECT * FROM family where FName='" + gettingfam + "'"

App crashes without catching any exception [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Can't create handler inside thread that has not called Looper.prepare() Android
(2 answers)
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 3 years ago.
So i'm into a tutorial at Udemy "The Complete Android N Developer Course" and trying to make lecture 86 about a weather app.
I use the API from here https://openweathermap.org/current#cityid and use JSON to get the data needed.
The app is working properly when i input a correct city name, but when the input is wrong or empty the app crashes without catching any exceptions.
I don't know why it is crashing and where to look. So i give you all the code i wrote. I tried to implement if statements here and there to try and find it but without any luck.
I would like to know where the problem is and how to fix it so the app doesn't crash anymore.
Thanks in advance.
public class MainActivity extends AppCompatActivity {
EditText editText;
String city = "";
TextView textView;
public void getWeather (View view) {
try {
city = URLEncoder.encode(editText.getText().toString(), "UTF-8");
if (editText.getText().toString() == "") {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
textView.setText("Please enter a city.");
} else {
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=c6ef169a79d84674ef7e1414301eb5c4");
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
} catch (UnsupportedEncodingException e1) {
Toast.makeText(MainActivity.this, "UnsupportedEncodingException", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (getWeather)", Toast.LENGTH_SHORT).show();
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = null;
in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPart = jsonArray.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
textView.setText(message);
} else {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
Toast.makeText(MainActivity.this, "JSONException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (onPostExecute)", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
}
}
It is because you're trying to changes UI with background thread inside the doInBackground(Params...) method of AsyncTask with this line:
try {
...
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
You should not call Toast inside the doInBackground(Params...). Do that inside the onPostExecute(Result).
You can avoid that by either ignoring the error or returning specific text in doInBackground. Something like this:
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
...
try {
...
return result;
} catch (MalformedURLException e1) {
result= "MalformedURLException";
} catch (IOException e2) {
result= "IOException";
} catch (Exception e) {
// do nothing and returning empty
result= "Exception";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// check if there is an error
String errorMessage = "";
switch(result) {
case "MalformedURLException":
errorMessage = "MalformedURLException";
break;
case ""IOException":
errorMessage = "IOException";
break;
case "Exception":
errorMessage = "Exception";
break;
}
// there is an error, show a message.
if(!errorMessage.isEmpty()) {
Toast.makeText(MainActivity.this, "Could not find weather: " + errorMessage, Toast.LENGTH_SHORT).show();
return; // stop the process.
}
// do something when no error found.
}
}

How do I get current user's input data to show in listview?

I have an app where I use the info provided by the user to get a list of data
Using the code below, I'm getting two different results:
When where username = '$username' is presented on the PHP side, I receive just the Toast message. However, ListView remains empty.
When I remove where username = '$username' from PHP side, Toast message is displayed and the ListView also shows some content
Could you please help me to undestand why the ListView remains empty on that specific case?
Thanks in advance
Java
public void current_user() {
String url = "http://websie/my.php";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dayes = new SimpleDateFormat("dd-MM-yyyy");
final String created_date = dayes.format(calendar.getTime());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//System.out.println(response);
// Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
Toast.makeText(show_post_all_sales_2x100.this, response.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(show_post_all_sales_2x100.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", User.getUsername());
params.put("created_date", created_date);
return params;
}
};
RequestQueue requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpParseClass httpParseClass = new HttpParseClass(HttpURL);
try {
httpParseClass.ExecutePostRequest();
if (httpParseClass.getResponseCode() == 200) {
FinalJSonResult = httpParseClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subjects subjects;
SubjectList = new ArrayList<Subjects>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String tempName = jsonObject.getString("username").toString();
String tempFullForm = jsonObject.getString("created_date").toString();
subjects = new Subjects(tempName, tempFullForm);
SubjectList.add(subjects);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpParseClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$username = $_POST['username'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM post_2x where username = '$username'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Result when where username = '$username' is present
Result when I remove where username = '$username'

Registering with a new account failed

Below is a registration form where user can register a new account, however when I try to sign up it connect to the server, but for some reason it failed to register!
with message from php file (Hmmm Look Like User Already Exist...) however I'm sure that the user doesn't exist in the database table!
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
TextView sign_in_text;
EditText Name,Email,Pass,ConPass;
Button reg_button;
AlertDialog.Builder mBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sign_in_text = (TextView) findViewById(R.id.sign_in);
sign_in_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
Name = (EditText) findViewById(R.id.user_name);
Email = (EditText) findViewById(R.id.email_register);
Pass = (EditText) findViewById(R.id.password_register);
ConPass = (EditText) findViewById(R.id.password_conf);
reg_button = (Button) findViewById(R.id.reg_button);
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Name.getText().toString().equals("")|| Email.getText().toString().equals("")|| Pass.getText().toString().equals("")){
mBuilder = new AlertDialog.Builder(RegisterActivity.this);
mBuilder.setTitle("Oops something went wrong!");
mBuilder.setMessage("Please fill all the fields");
mBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
else if (!(Pass.getText().toString().equals(ConPass.getText().toString()))){
mBuilder = new AlertDialog.Builder(RegisterActivity.this);
mBuilder.setTitle("Oops something went wrong!");
mBuilder.setMessage("Your passwords are not matching");
mBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Pass.setText("");
ConPass.setText("");
}
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
else {
BackgroundTask backgroundTask = new BackgroundTask(RegisterActivity.this);
backgroundTask.execute("register",Name.getText().toString(),Email.getText().toString(),Pass.getText().toString());
}
}
});
}
}
And this is the background task where I connect the to server
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, String, String> {
String register_url ="http://justawesome.net/ozone_registration/register.php";
String login_url ="http://justawesome.net/ozone_registration/login.php";
Context ctx;
ProgressDialog mProgressDialog;
Activity activity;
AlertDialog.Builder mBuilder;
public BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute() {
mBuilder = new AlertDialog.Builder(activity);
mProgressDialog = new ProgressDialog(ctx);
mProgressDialog.setTitle("Please wait");
mProgressDialog.setMessage("Connecting to server....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register")){
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name", "UTF-8")+"-"+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email", "UTF-8")+"-"+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"-"+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (method.equals("login")){
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String email,password;
email = params[1];
password = params[2];
String data = URLEncoder.encode("email", "UTF-8")+"-"+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"-"+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
mProgressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
//JSONObject jsonObject = new JSONObject(json);
//String response = jsonObject.getString("server_response");
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
//JSONArray jsonArray = new JSONArray(response);
JSONObject Jo = jsonArray.getJSONObject(0);
String code = Jo.getString("code");
Log.d("code0", code);
String message = Jo.getString("message");
Log.d("message", message);
if(code.equals("reg_true")){
showDialog("Registration Success", message,code);
Log.d("code1", code);
}
else if(code.equals("reg_false")){
showDialog("Registration Failed", message,code);
Log.d("code2", code);
}
else if (code.equals("login_true")){
Intent intent = new Intent(activity, AccountActivity.class );
intent.putExtra("message", message);
activity.startActivity(intent);
}
else if (code.equals("login_false")){
showDialog("Login Error...",message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is the php file.
P.S.: I tested the backend and it works fine.
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
require "init.php";
$query = "SELECT * FROM userdb WHERE email like '$email';";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result)>0){
$response = array();
$code = "reg_false";
$message = "Hmmm Look Like User Already Exist...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else{
$query = "INSERT INTO userdb(name,email,password)values('$name','$email','$password');";
$result = mysqli_query($con,$query);
if(!$result){
$response = array();
$code = "reg_false";
$message = "Some server error occourred. Try again... ";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}else{
$response = array();
$code = "reg_true";
$message = "Yuoohooo Registration Success... Thank you";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
}
mysqli_close($con);
?>
Appreciate your help

Row cannot be updated

Can someone please help me ???
I have successfully store the image path and text into MySQL, and image in the folder.
This is the php code I use to upload image path and text.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['listItems'] ) ){
$listItems = json_decode( $_POST['listItems'], true );
$mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
$sql="INSERT INTO `staff_benefit`
( `type`, `amount`, `description`, `image`, `ts_id` )
VALUES ( ?, ?, ?, ?, ? )";
if($stmt=$mysqli->prepare($sql )){
$url="http://192.168.1.7:80/Android/CRUD/PhotoUpload/";
foreach( $listItems as $item ){
$id = uniqid();
$image_name = $id.".png";
$save_path = 'PhotoUpload/'.$image_name;
$image_url = $url.$image_name;
$bytes=file_put_contents($save_path, base64_decode($item['image']));
if( !$bytes ){
echo 'Error saving image';
}else{
$stmt->bind_param('sssss',
$item['type'],
$item['amount'],
$item['description'],
$image_url,
$item['ts_id'] );
if( !$res=$stmt->execute()){
echo 'Query failed with code: '.$stmt->errno;
}
}
}
}
$mysqli->close();
}
}
?>
But when I tried to update the row in android, the row did not changed but it display updated successfully in php.
This is my update php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
$type = $_POST['type'];
$amount = $_POST['amount'];
$description = $_POST['description'];
//importing database connection script
require_once('dbConnect.php');
if(isset($_POST['image']))
{
$id = uniqid();
$url="http://192.168.107.115:80/Android/CRUD/PhotoUpload/";
$image_name = $id.".png";
$save_path = 'PhotoUpload/'.$image_name;
$image_url = $url.$image_name;
$bytes =file_put_contents($save_path, base64_decode($_POST['image']));
$sql = "UPDATE staff_benefit SET type = '$type', amount = '$amount', description='$description', image='$image_url'
WHERE id = '$id'";
}
else{
$sql = "UPDATE staff_benefit SET type = '$type', amount = '$amount', description='$description' WHERE id = '$id'";
}
//Updating database table
if(mysqli_query($con,$sql)){
echo ' Updated Successfully';
}else{
echo mysqli_error($con);
exit;
}
//closing connection
mysqli_close($con);
}
?>
Update code
public void update( final String claimType, final String Amount, final String Description, final Uri imageUri)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("photo", imageUri.toString());
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
if(imageUri != null){
Log.d("log", "photo " + imageUri);
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri));
}else{
Log.d("log", "photo is null " );
}
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
public void updateWithoutImage( final String claimType, final String Amount, final String Description)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("iD",ID);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
Log.e("Type",claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
I have two functions, one is update and another is updateWithoutImage. They using the same php. But the php works for updateWithoutImage but not for update function.
ok,I know why the update() does not functioning.
In my php code, I have two $id. Change the $id inside the if(isset($_POST['image'])) to $id1, and now it can be updated.

Categories

Resources