Lesson 5–Add New Record
Step 1: Create table using SQL
Create table “f_food”
CREATE table f_food (foodID int(4) AUTO_INCREMENT NOT NULL,
foodName varchar(30) NOT NULL,
foodPrice decimal(10,2) NOT NULL,
PRIMARY KEY(foodID)
);
Create table “f_drink”
CREATE table f_drink (drinkID INT(4) AUTO_INCREMENT NOT NULL,
drinkName varchar(20) NOT NULL,
drinkPrice decimal(10,2) NOT NULL,
PRIMARY KEY(drinkID)
);
Step 2: Modify source code php file “api.php”
else if ($_POST['method']=='insert') {if ($_POST['typeID']=='Food') {
$stmt = $db_con->prepare("INSERT INTO f_food VALUES ('',:name,:price)");
$stmt->bindParam(":name", $_POST['name']);
$stmt->bindParam(":price", $_POST['price']);
$stmt->execute();
}
else if ($_POST['typeID']=='Drink') {
$stmt = $db_con->prepare("INSERT INTO f_drink VALUES ('',:name,:price)");
$stmt->bindParam(":name", $_POST['name']);
$stmt->bindParam(":price", $_POST['price']);
$stmt->execute();
}
$arr = array ('query_result'=>'SUCCESS');
echo json_encode($arr);
}
Step 3:
Modify “fragment_add_new.xml” in directory res/layout/
FrameLayout xmlns:android="xmlns:tools="
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="p.my.myfood.AddNew"
<!-- TODO: Update blank fragment layout -->
RelativeLayout
android:layout_width="match_parent"
android:contentDescription="@string/layout_fragment"
android:layout_height="match_parent"
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="@string/second_fragment"
android:textSize="30sp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="200sp"
android:layout_height="50sp"
android:layout_centerInParent="true"
android:layout_below="@+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:entries="@array/food_type"
android:prompt="@string/app_name"/>
<EditText
android:id="@+id/data1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/spinner1"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:ems="10"
android:inputType="textPersonName"
android:textSize="20sp"
android:hint="@string/form1_data1" />
<EditText
android:id="@+id/data2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/data1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:ems="10"
android:inputType="textPersonName"
android:textSize="20sp"
android:hint="@string/form1_data2" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/data2"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:textSize="20sp"
android:text="@string/form1_submit" />
<TextView
android:id="@+id/result1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnSubmit"
android:layout_centerHorizontal="true"
android:layout_marginTop="31dp"
android:textSize="25sp"
android:text="@string/form1_result" />
</RelativeLayout
</FrameLayout
Modify “string.xml” in directory res/value/
string-array name="food_type"<item>-- Select --</item
<item>Food</item
<item>Drink</item
</string-array
string name="form1_data1">Food//Drink Name</string
string name="form1_data2">Price</string
string name="form1_submit">Save</string
string name="form1_result"</string
Modify “AddNew.java”
package p.my.myfood;import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
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.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.content.ContentValues.TAG;
public class AddNew extends Fragment {
private Spinner spinner1;
private EditText etData1, etData2;
private TextView response;
private Button btnSubmit;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_new, container, false);
spinner1 = (Spinner)view.findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
etData1 = (EditText)view.findViewById(R.id.data1);
etData2 = (EditText)view.findViewById(R.id.data2);
response = (TextView)view.findViewById(R.id.result1);
btnSubmit = (Button)view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
String url = ";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String jsonStr = response;
if (jsonStr!=null) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
String query_result = jsonObject.getString("query_result");
if (query_result.equalsIgnoreCase("SUCCESS")) {
Toast.makeText(getContext(),"Data is successfull inserted...." ,Toast.LENGTH_SHORT).show();
}
else if (query_result.equalsIgnoreCase("FAILED")) {
Toast.makeText(getContext(),"Data is unsuccessfull inserted...." ,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(),"Database connection failed...." ,Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
response.setText("That didn't work!");
}
}) {
//adding parameters to the request
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap>();
params.put("method","insert");
params.put("typeID",String.valueOf(spinner1.getSelectedItem()));
params.put("name", etData1.getText().toString());
params.put("price", etData2.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
});
return view;
}
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
// Todo when item is selected by the user
}
}
@Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
Good Luck !!!!