Johncbell Johncbell - 6 months ago 23
MySQL Question

Android Studio: PHP mysql variable isnt being passed in RegisterAPI when adding 2 variables

I am trying to use a Form and PHP to pass a variable into the PHP file to POST into MySQL. I was able to get all of the variables but a calculated one. I just can't get to work. I can make the toast show the calculated number, but not carry it forward.

In MainActivity: I am trying to calculate

emptyMilage
-
loadedMilage
.

I created a private textview or string, I have tried almost everything, and know is just something I can't grasp yet.

I have attached the MainActivity and RegisterAPI class I am using along with the SQL import.

MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//Declaring views
private WebView webView;
private EditText trucksID;
private EditText tripReportNumber;
private EditText enteredDate;
private EditText emptyMilage;
private EditText loadedMilage;

private Button buttonRegister;
private String estTotal;
private TextView estMilage;

//This is our root url
public static final String ROOT_URL = "http://rooturl_for_php/php/";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Initializing Views
trucksID = (EditText) findViewById(R.id.trucksID);
tripReportNumber = (EditText) findViewById(R.id.tripReportNumber);
enteredDate = (EditText) findViewById(R.id.enteredDate);
emptyMilage= (EditText) findViewById(R.id.emptyMilage);
loadedMilage = (EditText) findViewById(R.id.loadedMilage);
estMilage = (TextView) findViewById(R.id.estMilage);

buttonRegister = (Button) findViewById(R.id.buttonRegister);

//Adding listener to button
buttonRegister.setOnClickListener(this);
}




public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
// Just took out Menu options, since that is working well //

private void insertUser(){
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter

//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);

//Defining the method insertuser of our interface
api.insertUser(

//Passing the values by getting it from editTexts
trucksID.getText().toString(),
tripReportNumber.getText().toString(),
enteredDate.getText().toString(),
emptyMilage.getText().toString(),
loadedMilage.getText().toString(),
//can take this out below
estMilage.getText().toString(),

//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;

//An string to store output from the server
String output = "";

try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}

//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}

@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}

//Overriding onclick method
@Override
public void onClick(View v) {
//Calling insertUser on button click
insertUser();
int value1=Integer.parseInt(emptyMilage.getText().toString());
int value2=Integer.parseInt(loadedMilage.getText().toString());

int estMilage=value2-value1;
Toast.makeText(this, "Estimated Milage:"+String.valueOf(estMilage), Toast.LENGTH_SHORT).show();
}
}


Here is the RegisterAPI I created

public interface RegisterAPI {
@FormUrlEncoded
@POST("/insert.php")
public void insertUser(
@Field("trucksID") String trucksID,
@Field("tripReportNumber") String tripReportNumber,
@Field("enteredDate") String enteredDate,
@Field("emptyMilage") String emptyMilage,
@Field("loadedMilage") String loadedMilage,
@Field("estTotal") String estTotal,
Callback<Response> callback);
}


And here is the final, after I use a $conn php file insert.php

<?php
//checking if the script received a post request or not
if($_SERVER['REQUEST_METHOD']=='POST'){

//Getting post data
$trucksID = $_POST['trucksID'];
$tripReportNumber = $_POST['tripReportNumber'];
$enteredDate = $_POST['enteredDate'];
$emptyMilage = $_POST['emptyMilage'];
$loadedMilage = $_POST['loadedMilage'];
$estTotal = $_POST['estTotal'];

//checking if the received values are blank
if($trucksID == '' || $tripReportNumber == '' || $emptyMilage == '' || $loadedMilage == '' ){
//giving a message to fill all values if the values are blank
echo 'Please fill all values';
}else{
//If the values are not blank
//Connecting to our database by calling dbConnect script
require_once('dbConnect.php');

//Creating an SQL Query to insert into database
//Here you may need to change the drivers_report because it is the table I created
//if you have a different table write your table's name

//This query is to check whether the Trip Report is already registered or not
$sql = "SELECT * FROM drivers_report WHERE trucksID='$trucksID'";

//If variable check has some value from mysqli fetch array
//That means username or email already exist
$check = mysqli_fetch_array(mysqli_query($con,$sql));

//Checking check has some values or not
if(isset($check)){
//If check has some value that means username already exist
echo 'Trip Report already exists';
}else{
//If username is not already exist
//Creating insert query
$sql = "INSERT INTO drivers_report (trucksID,tripReportNumber,enteredDate,emptyMilage,loadedMilage,estTotal) VALUES('$trucksID','$tripReportNumber','$enteredDate','$emptyMilage','$loadedMilage','$estTotal')";

//Trying to insert the values to db
if(mysqli_query($con,$sql)){
//If inserted successfully
echo 'Trip Report Submitted!';
}else{
//In case any error occured
echo 'oops! Please try again!';
}
}
//Closing the database connection
mysqli_close($con);
}
}else{
echo 'error';
}


The variable can change but has to populate the estTotal in the php file.
Thank you for any help, I have spent about a week trying to change the code about 50 times to work and I am still stuck.

Also attached the
Activity_Main.xml
for screen

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:text="Enter Truck ID:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/trucksID"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<TextView
android:text="Enter Trip Report Number:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


<EditText
android:id="@+id/tripReportNumber"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<TextView
android:text="Enter Trip Date:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


<EditText
android:id="@+id/enteredDate"
android:inputType="date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="MM/DD/YY" />



<TextView
android:text="Enter Empty Milage:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


<EditText
android:id="@+id/emptyMilage"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<TextView
android:text="Enter Loaded Milage:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


<EditText
android:id="@+id/loadedMilage"
android:inputType="date"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/buttonRegister"
android:text="Submit Trip Report"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/estMilage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
/>
</LinearLayout>


Re-Adding in full MainActivity file:



package com.johncbell.atrixtrucking;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.WebView;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

//Class for our main activity with OnClickListener
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//Declaring views
private WebView webView;
private EditText trucksID;
private EditText tripReportNumber;
private EditText enteredDate;
private EditText emptyMilage;
private EditText loadedMilage;

private Button buttonRegister;
private String estTotal;
private TextView estMilage;

//This is our root url
public static final String ROOT_URL = "http://URLOFPHPFILE/php/";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Initializing Views
trucksID = (EditText) findViewById(R.id.trucksID);
tripReportNumber = (EditText) findViewById(R.id.tripReportNumber);
enteredDate = (EditText) findViewById(R.id.enteredDate);
emptyMilage= (EditText) findViewById(R.id.emptyMilage);
loadedMilage = (EditText) findViewById(R.id.loadedMilage);
estMilage = (TextView) findViewById(R.id.estMilage);

buttonRegister = (Button) findViewById(R.id.buttonRegister);

//Adding listener to button
buttonRegister.setOnClickListener(this);
}




public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.openWebsite:
Intent website = new Intent(this,ourWebsite.class);
this.startActivity(website);
return true;

case R.id.goto2:
Intent activity2 = new Intent(this,MainActivity2.class);
this.startActivity(activity2);
return true;

case R.id.about_us:
Intent about = new Intent(this,aboutUs.class);
this.startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}


private void insertUser(){
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter

//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);

//Defining the method insertuser of our interface

int value1=Integer.parseInt(emptyMilage.getText().toString());
int value2=Integer.parseInt(loadedMilage.getText().toString());
int estMilage=value2-value1;

api.insertUser(

api.insertUser(
//Passing the values by getting it from editTexts
trucksID.getText().toString(),
tripReportNumber.getText().toString(),
enteredDate.getText().toString(),
emptyMilage.getText().toString(),
loadedMilage.getText().toString(),
//can take this out below
Integer.toString(estMilage),


//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;

//An string to store output from the server
String output = "";

try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}

//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}

@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}

//Overriding onclick method
@Override
public void onClick(View v) {
//Calling insertUser on button click
insertUser();

}
}

Answer

Before api.insertUser(, try:

int value1=Integer.parseInt(emptyMilage.getText().toString());
int value2=Integer.parseInt(loadedMilage.getText().toString());
int estMilage=value2-value1;

then api.insertUser( should be:

 api.insertUser(
                //Passing the values by getting it from editTexts
                trucksID.getText().toString(),
                tripReportNumber.getText().toString(),
                enteredDate.getText().toString(),
                emptyMilage.getText().toString(),
                loadedMilage.getText().toString(),
                //can take this out below
                Integer.toString(estMilage),
Comments