Can't store data to the database - java

I'm working on an application that stores user inputs into the database table via PHP API but i get an error message from the PHP code to the LogCat. Any advice would be greatly appreciated.
D/Create Response(284): {"message":"Required field(s) is missing","success":0}
PHP API
<?php
// array for JSON response
$response = array();
// check for the fields
if (isset($_POST['title']) && isset($_POST['request_date']) && isset($_POST['reqEndDate']) && isset($_POST['reason']) && isset($_POST['requestor']) && isset($_POST['status']) && isset($_POST['submitDate']) && isset($_POST['explanation']) && isset($_POST['hours']) && isset($_POST['id'])) {
$title = $_POST["request_title"];
$date = $_POST["request_date"];
$eDate = $_POST["reqEndDate"];
$reason = $_POST["reason"];
$requestor = $_POST["requestor"];
$status = $_POST["status"];
$dateSubmitted = $_POST["submitDate"];
$explanation = $_POST["explanation"];
$numhours = $_POST["hours"];
$id = $_POST['id'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO requests(request_title, request_date, reqEndDate, reason, requestor, status, submitDate, explanation, hours, empid)
VALUES('$title', '$date', '$eDate', '$reason', '$requestor', '$status', '$dateSubmitted', '$explanation', '$numhours', '$id')");
?>
JAVA CLASS
// url to the PHP API to create new request
private static String url_create_request = "http://mywebsite.com/create_request.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_request);
// Edit Text
inputTitle = (EditText) findViewById(R.id.inputTitle);
inputSdate = (EditText) findViewById(R.id.inputSdate);
inputEdate = (EditText) findViewById(R.id.inputEdate);
inputHours = (EditText) findViewById(R.id.inputHours);
inputReason = (EditText) findViewById(R.id.inputReason);
inputExp = (EditText) findViewById(R.id.inputExp);
// Create button
Button btnCreateRequest = (Button) findViewById(R.id.btnCreateRequest);
// button click event
btnCreateRequest.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewRequest().execute();
}
});
}
class CreateNewRequest extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewRequestActivity.this);
pDialog.setMessage("Creating Request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating Request Required Fields
* */
protected String doInBackground(String... args) {
String title = inputTitle.getText().toString();
String date = inputSdate.getText().toString();
String eDate = inputEdate.getText().toString();
String hours = inputHours.getText().toString();
String reason = inputReason.getText().toString();
String explanation = inputExp.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("request_title", title));
params.add(new BasicNameValuePair("request_date", date));
params.add(new BasicNameValuePair("reqEndDate", eDate));
params.add(new BasicNameValuePair("hours", hours));
params.add(new BasicNameValuePair("reason", reason));
params.add(new BasicNameValuePair("explanation", explanation));
// getting JSON Object
// Note that create request url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_request,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created request
Intent i = new Intent(getApplicationContext(), AllRequestsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create request
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}

Just counting your DB columns: there appears to be 12 of them. You're only inserting into 11, and after process of elimination, it looks like you're leaving out "active," which, unless it has a default value or can be null, would throw a "Required field(s) is missing" error that you're getting when trying to insert into the DB.

Related

Android Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject

I am trying to display information depending on the item pressed in a ListView. When click the item in List view,it will display the subject information.
But i faced a problem that is when click the item in List view,it cannot display the subject information based on the item that i clicked and display error in logcat.
Logcat Json response show that success get the subject information Single Product Details but still failed display subject information.Thanks
05-14 17:54:36.671: D/All Products:(1227): {"success":1,"products":[{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/1","class_ID":"1"},{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/2","class_ID":"2"},{"session":"2-2014\/2015","subject_code":"BITS 3323","section":"1\/2","class_ID":"8"},{"session":"2-2014\/2015","subject_code":"BITS2323 Wide Area Network","section":"1\/1","class_ID":"9"}]}
05-14 17:54:37.731: E/JSON Parser(1227): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
05-14 17:54:37.731: D/Single Product Details(1227): {"success":1,"products":[{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/1","class_ID":"1"},{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/2","class_ID":"2"},{"session":"2-2014\/2015","subject_code":"BITS 3323","section":"1\/2","class_ID":"8"},{"session":"2-2014\/2015","subject_code":"BITS2323 Wide Area Network","section":"1\/1","class_ID":"9"}]}
05-14 17:54:37.731: D/JSON Parser(1227): {"success":1,"products":[{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/1","class_ID":"1"},{"session":"2-2014\/2015","subject_code":"BITS 3323 Local Area Network","section":"1\/2","class_ID":"2"},{"session":"2-2014\/2015","subject_code":"BITS 3323","section":"1\/2","class_ID":"8"},{"session":"2-2014\/2015","subject_code":"BITS2323 Wide Area Network","section":"1\/1","class_ID":"9"}]}
05-14 17:54:37.731: W/System.err(1227): org.json.JSONException: No value for product
I trying use some suggestion such as change echo->print in php, using require_once 'DB_Connect.php that provided in previous post to solve Error parsing data org.json.JSONExceptio but still does not work
Listview java to passes EditProductActivity2
public class AllAttendanceActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.14/android/get_class.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "class_ID";
private static final String TAG_NAME = "subject_code";
private static final String TAG_SECTION = "section";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_attendance);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String class_ID = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity2.class);
// sending pid to next activity
in.putExtra(TAG_PID, class_ID);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllAttendanceActivity.this);
pDialog.setMessage("Loading Subject.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String class_ID = c.getString(TAG_PID);
String subject_code = c.getString(TAG_NAME);
String section = c.getString(TAG_SECTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID,class_ID);
map.put(TAG_NAME, subject_code);
map.put(TAG_SECTION, section);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllAttendanceActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME,TAG_SECTION},
new int[] { R.id.pid, R.id.name,R.id.section});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
public class EditProductActivity2
public class EditProductActivity2 extends Activity {
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String class_ID;
String subject_code;
String session;
String section;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_class_detials = "http://192.168.1.14/android/get_class_details.php";
// url to update product
private static final String url_update_product = "http://10.0.2.2/android_connect/update_product.php";
// url to delete product
private static final String url_delete_product = "http://10.0.2.2/android_connect/delete_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "class_ID";
private static final String TAG_NAME = "subject_code";
private static final String TAG_PRICE = "session";
private static final String TAG_DESCRIPTION = "section";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
class_ID = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
// Delete button click event
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new DeleteProduct().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity2.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", class_ID));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_class_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
Log.d("JSON Parser",json.toString() );
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity2.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
subject_code = txtName.getText().toString();
session = txtPrice.getText().toString();
section = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, class_ID));
params.add(new BasicNameValuePair(TAG_NAME, subject_code ));
params.add(new BasicNameValuePair(TAG_PRICE, session ));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, section ));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_product,
"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity2.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", class_ID));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
}
PHP CODE
$response = array();
require_once __DIR__ . '/db_connect.php';
//require_once 'db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM class WHERE class_ID=$pid ");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["class_ID"] = $row["class_ID"];
$product["subject_code"] = $row["subject_code"];
$product["session"] = $row["session"];
$product["section"] = $row["section"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Search remote database Android app

I want to create an Android app to be a search engine that can
search my remote database from server like MAMP,
list the search results and
select one of the results to view details.
I have already set up the database.
Search.java - the launch page that shows only a search bar, allows user to search:
public class Search extends Activity implements OnClickListener{
private EditText searchterm;
private Button mSubmit;
private SharedPreferences preferences;
private String preFileName="searchrequest"; //this is the Preference file Name
private String prefKey="searchterm"; //Key to store the User Name
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
private static final String SEARCH_URL = "http://xxx.xxx.x.xxx:8888/searchdb/search.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchterm = (EditText)findViewById(R.id.searchterm);
mSubmit = (Button)findViewById(R.id.searchnow);
mSubmit.setOnClickListener(this);
preferences=getSharedPreferences(preFileName, MODE_PRIVATE);
if(!preferences.getString(prefKey, "not_set").equals("not_set")){
prefKey.setText(preferences.getString(preFileName, "not_set"));
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.searchnow:
new SearchQuery().execute();
break;
default:
break;
}
}
public class SearchQuery extends AsyncTask<String,String,String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Checking for records...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String searchquery = searchterm.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("searchquery", searchquery));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
SEARCH_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successful Search!", json.toString());
//need help on how to save search data
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("searchquery", searchquery);
editor.apply();
Intent i = new Intent(Search.this, Result.class);
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Invalid query. Please try again.", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Search.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Search.php:
<?php
# $db = new mysqli('localhost','username','password','db');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database.
Please try again later.';
exit;
}
if (!empty($_POST)) {
$query_params = array(
$term = $_POST['searchquery']
);
$words = explode(" ", trim($term));
$termArray = array();
foreach($words as $word){
if(!empty($word)){
$termArray[] = "+$word";
}
}
$searchinput = implode(" ", $termArray);
$query = "SELECT *
FROM repairsvc
WHERE MATCH(title,address,cat,brand,company)
AGAINST ('".$searchinput."' IN BOOLEAN MODE)
ORDER BY title ASC";
try {
$result = $db->query($query);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$num_results = $result->num_rows;
if ($num_results == 0)
{
$search_ok = false;
}
else
{$search_ok = true;}
if ($search_ok) {
$response["success"] = 1;
$response["message"] = "Search Successful!";
$response["records"] = array();
$records = array();
while ($row = $result->fetch_assoc()) {
$records[] = array('title'=>$row["title"], 'address'=>$row["address"],
'company'=>$row["company"], 'id'=>$row["id"], 'brand'=>$row["brand"]); // push into the array
}
var_dump($records);
// foreach ($records as $row) {
// echo "Outlet: ", $row['title'], "; Address: ", $row['address'];
// }
//update our repsonse JSON data
array_push($response["records"], $records);
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Invalid Search! Please try again.";
die(json_encode($response));
}
} else {
?>
<h1>Search</h1>
<form name="form1" action="search.php" method="post">
Enter Search:<br />
<input type="text" name="searchquery" id="searchquery" placeholder="Search a repair service"/>
<br /><br />
<input type="submit" value="Search Now" name="completedsearch" />
</form>
<?php
}
?>
Problems:
How to save the search results from Search.java and let another activity Result.java to list results?
Save this from the php in first activity:
while ($row = $result->fetch_assoc()) {
$records[] = array('title'=>$row["title"], 'address'=>$row["address"],
'company'=>$row["company"], 'id'=>$row["id"], 'brand'=>$row["brand"]); // push into the array
}
//update our repsonse JSON data
array_push($response["records"], $records);
echo json_encode($response);
and put as listview in second activity (Result.java)??
Result.java --> select one of the results in list view, how to get details by searching database by posting id of the item?
I solved my question by putting this within Search.java to test whether can search:
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String searchquery = searchterm.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("searchquery", searchquery));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
SEARCH_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successful Search!", json.toString());
//save search data
mCommentList = new ArrayList<HashMap<String, String>>();
mComments = json.getJSONArray(TAG_POSTS);
// JSONArray mComments = new JSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONArray innerArray = mComments.optJSONArray(i);
for (int j = 0; j < innerArray.length(); j++) {
JSONObject c = innerArray.getJSONObject(j);
//gets the content of each tag
String title = c.getString(TAG_TITLE);
String address = c.getString(TAG_ADDRESS);
String brand = c.getString(TAG_BRAND);
String company = c.getString(TAG_COMPANY);
String id = c.getString(TAG_ID);
//so our JSON data is up to date same with our array list
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ADDRESS, address);
map.put(TAG_BRAND, brand);
map.put(TAG_COMPANY, company);
map.put(TAG_ID, id);
mCommentList.add(map);
}
}
Intent r = new Intent(Search.this, Results.class);
//either
//r.putExtra("arraylist", mCommentList);
// startActivityForResult(r, 5000);
//or
r.putExtra("searchquery", searchquery);
startActivity(r);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Invalid Search!", json.toString());
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Then in Results.java:
public void updateJSONdata() {
Bundle b = getIntent().getExtras();
String searchquery = b.getString("searchquery");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("searchquery", searchquery));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
SEARCH_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
try {
mResultList = new ArrayList<HashMap<String, String>>();
mResults = json.getJSONArray(TAG_POSTS);
// JSONArray mComments = new JSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mResults.length(); i++) {
JSONArray innerArray = mResults.optJSONArray(i);
for (int j = 0; j < innerArray.length(); j++) {
JSONObject c = innerArray.getJSONObject(j);
//gets the content of each tag
String title = c.getString(TAG_TITLE);
String address = c.getString(TAG_ADDRESS);
String brand = c.getString(TAG_BRAND);
String company = c.getString(TAG_COMPANY);
String id = c.getString(TAG_ID);
//so our JSON data is up to date same with our array list
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ADDRESS, address);
map.put(TAG_BRAND, brand);
map.put(TAG_COMPANY, company);
map.put(TAG_ID, id);
mResultList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
//if you choose the other method
// final ArrayList<HashMap<String, String>> mResultList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
// System.out.println("...serialized data.."+mResultList);
Bundle b = getIntent().getExtras();
final String searchquery = b.getString("searchquery");
ListAdapter adapter = new SimpleAdapter(this, mResultList,
R.layout.single_result, new String[]{TAG_TITLE, TAG_ADDRESS, TAG_BRAND,
TAG_COMPANY, TAG_ID}, new int[]{R.id.outlet, R.id.address, R.id.brand,
R.id.company});
setListAdapter(adapter);
listView.setSelector(R.drawable.listselector);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item value
Map<String, String> map = (Map<String, String>) mResultList.get(position);
String record_id = map.get(TAG_ID);
Intent r = new Intent(Results.this, Record.class);
r.putExtra("key", record_id);
r.putExtra("searchquery", searchquery);
startActivity(r);
}
}
);
}

Android -php-mysql- JSON connection issue

I imported the androidhive project(http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/) and I added another table to the database. The details of the second table are displayed in the second listview. After clicking on listview item the edit page is displayed. But I didn't get the second table details in the corresponding edittexts.
Here are my java classes:
JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
java.io.UnsupportedEncodingException;
import java.util.List;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
2.JuicesActivity
public class JuicesActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> juicesList;
// url to get all products list
private static String url_all_juices = "http://10.0.2.2/android_connect/get_all_juices.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_JUICES = "juices";
private static final String TAG_JID = "j_id";
private static final String TAG_JUICENAME = "juice_name";
// products JSONArray
JSONArray juices = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_juices);
// Hashmap for ListView
juicesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllJuices().execute();
// Get listview
ListView jv = getListView();
// on seleting single product
// launching Edit Product Screen
jv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String j_id = ((TextView) view.findViewById(R.id.jid)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),EditJuice.class);
// sending jid to next activity
in.putExtra(TAG_JID, j_id);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Editjuice Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllJuices extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(JuicesActivity.this);
pDialog.setMessage("Loading juices.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_juices, "GET", params);
// Check your log cat for JSON response
Log.d("All Juices: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
juices = json.getJSONArray(TAG_JUICES);
// looping through All Products
for (int i = 0; i < juices.length(); i++) {
JSONObject c = juices.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_JID);
String name = c.getString(TAG_JUICENAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_JID, id);
map.put(TAG_JUICENAME, name);
// adding HashList to ArrayList
juicesList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
JuicesActivity.this, juicesList,
R.layout.list_juice, new String[] { TAG_JID,
TAG_JUICENAME},
new int[] { R.id.jid, R.id.jname });
// updating list view
setListAdapter(adapter);
}
});
}
}
}
3.EditJuice
public class EditJuice extends Activity {
EditText jName,jpric,jseller;
Button btnSavj,btnDeltJ;
String juid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_juice_details= "http://10.0.2.2/android_connect/get_juice_details.php";
// url to update product
private static final String url_update_juice = "http://10.0.2.2/android_connect/update_juice.php";
// url to delete product
private static final String url_delete_juice = "http://10.0.2.2/android_connect/delete_juice.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_JUICES = "juices";
private static final String TAG_JID = "j_id";
private static final String TAG_JUICENAME = "juice_name";
private static final String TAG_JPRICE = "price";
private static final String TAG_SELLER = "seller";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editjuice);
// save button
btnSavj = (Button) findViewById(R.id.btnSaveJ);
btnDeltJ = (Button) findViewById(R.id.btnDelJ);
// getting juice details from intent
Intent i = getIntent();
// getting juice id jid from intent
juid = i.getStringExtra(TAG_JID);
// Getting complete juice details in background thread
new Getjuice().execute();
// save button click event
btnSavj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// starting background task to update product
new Savejuice().execute();
}
});
// Delete button click event
btnDeltJ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// deleting product in background thread
new Deletejuice().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class Getjuice extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditJuice.this);
pDialog.setMessage("Loading juice details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting juice details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("j_id", juid));
// getting juice details by making HTTP request
// Note that juice details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_juice_details, "GET", params);
// check your log for json response
Log.d("Single juice Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received juice details
JSONArray juiceObj = json.getJSONArray(TAG_JUICES); // JSON Array
// get first juice object from JSON Array
JSONObject juice = juiceObj.getJSONObject(0);
// juice with this jid found
// Edit Text
jName = (EditText) findViewById(R.id.EditNamej);
jpric = (EditText) findViewById(R.id.EditPricej);
jseller = (EditText) findViewById(R.id.Editseller);
// display product data in EditText
jName.setText(juice.getString(TAG_JUICENAME));
jpric.setText(juice.getString(TAG_JPRICE));
jseller.setText(juice.getString(TAG_SELLER));
}else{
// juice with jid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save juice Details
* */
class Savejuice extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditJuice.this);
pDialog.setMessage("Saving juice ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving juice
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String juice_name = jName.getText().toString();
String price = jpric.getText().toString();
String seller = jseller.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_JID, juid));
params.add(new BasicNameValuePair(TAG_JUICENAME, juice_name));
params.add(new BasicNameValuePair(TAG_JPRICE, price));
params.add(new BasicNameValuePair(TAG_SELLER, seller));
// sending modified data through http request
// Notice that update juice url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_juice,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update juice
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once juice updated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class Deletejuice extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditJuice.this);
pDialog.setMessage("Deleting juice...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("j_id", juid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(url_delete_juice, "POST", params);
// check your log for json response
Log.d("Delete juice", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
}
AddJuiceActivity
public class AddJuiceActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputjName,inputPric,inputseller;
// url to create new product
private static String url_create_juice = "http://10.0.2.2/android_connect/create_juice.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_juice);
// Edit Text
inputjName=(EditText)findViewById(R.id.EditNam);
inputPric = (EditText) findViewById(R.id.EditPric);
inputseller = (EditText) findViewById(R.id.Editsell);
// Create button
Button btnj = (Button) findViewById(R.id.btnjuice);
// button click event
btnj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewJ().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewJ extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddJuiceActivity.this);
pDialog.setMessage("Creating juice..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String juicename = inputjName.getText().toString();
String price = inputPric.getText().toString();
String seller = inputseller.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("juice_name", juicename));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("seller", seller));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_juice,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), JuicesActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
LogCat:
07-04 01:10:37.091: D/Single juice Details(891): {"success":1,"juice": [{"seller":"das","juice_name":"lemon","j_id":"9","price":"30.00"}]}
07-04 01:10:37.091: W/System.err(891): org.json.JSONException: No value for juices
07-04 01:10:37.101: W/System.err(891): at org.json.JSONObject.get(JSONObject.java:355)
07-04 01:10:37.101: W/System.err(891): at org.json.JSONObject.getJSONArray(JSONObject.java:549)
07-04 01:10:37.101: W/System.err(891): at com.example.androidhive.EditJuice$Getjuice$1.run(EditJuice.java:136)
07-04 01:10:37.101: W/System.err(891): at android.os.Handler.handleCallback(Handler.java:733)
07-04 01:10:37.141: W/System.err(891): at android.os.Handler.dispatchMessage(Handler.java:95)
07-04 01:10:37.181: W/System.err(891): at android.os.Looper.loop(Looper.java:136)
07-04 01:10:37.181: W/System.err(891): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-04 01:10:37.181: W/System.err(891): at java.lang.reflect.Method.invokeNative(Native Method)
07-04 01:10:37.181: W/System.err(891): at java.lang.reflect.Method.invoke(Method.java:515)
07-04 01:10:37.191: W/System.err(891): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-04 01:10:37.251: W/System.err(891): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-04 01:10:37.251: W/System.err(891): at dalvik.system.NativeStart.main(Native Method)
Here is the php files.
get_all_juices.php
/*
* Following code will list all the juices
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all juices from juices table
$result = mysql_query("SELECT * FROM juices") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// juices node
$response["juices"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$juice = array();
$juice["j_id"] = $row["j_id"];
$juice["juice_name"] = $row["juice_name"];
$juice["price"] = $row["price"];
$juice["seller"] = $row["seller"];
// push single juice into final response array
array_push($response["juices"], $juice);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No juices found";
// echo no users JSON
echo json_encode($response);
}
?>
update_juice
<?php
/*
* Following code will update a juice information
* A juice is identified by juice id (j_id)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['j_id']) && isset($_POST['juice_name']) && isset($_POST['price'])
&& isset($_POST['seller']))
{
$j_id = $_POST['j_id'];
$juice_name = $_POST['juice_name'];
$price = $_POST['price'];
$seller = $_POST['seller'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched j_id
$result = mysql_query("UPDATE juices SET juice_name = '$juice_name',
price = '$price', seller = '$seller' WHERE j_id = $j_id");
// check if row inserted or not
if ($result)
{
// successfully updated
$response["success"] = 1;
$response["message"] = "juice successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
get_juice_details
<?php
/*
* Following code will get single juice details
* A juice is identified by juice id (j_id)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["j_id"]))
{
$j_id = $_GET['j_id'];
// get a juice from juices table
$result = mysql_query("SELECT *FROM juices WHERE j_id = $j_id");
if (!empty($result))
{
// check for empty result
if (mysql_num_rows($result) > 0)
{
$result = mysql_fetch_array($result);
$juice = array();
$juice["j_id"] = $result["j_id"];
$juice["juice_name"] = $result["juice_name"];
$juice["price"] = $result["price"];
$juice["seller"] = $result["seller"];
// success
$response["success"] = 1;
// user node
$response["juice"] = array();
array_push($response["juice"], $juice);
// echoing JSON response
echo json_encode($response);
} else {
// no juice found
$response["success"] = 0;
$response["message"] = "No juice found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no juice found
$response["success"] = 0;
$response["message"] = "No juice found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Take out the runOnUiTread call from Getjuice doInBackground. Put the setText statements for the EditTexts in onPostExecute. Thats a start...

Data from a MySQL database is not displaying in Android Textview

I can't display data from a MySQL database. I want to retrieve some data from my database and display it to the textview, but it's not working.
Java code:
public class Penjualan1 extends Activity {
// All xml labels
String pid;
TextView mejaTv;
TextView customerTv;
TextView keteranganTv;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile JSON url
private static final String url_order_detials = "-my url-/get_penjualan_details.php";
// ALL JSON node names
private static final String TAG_PRODUCT = "product";
private static final String TAG_SUCCESS = "success";
private static final String TAG_GET = "get";
private static final String TAG_MEJA = "meja";
private static final String TAG_CUST = "customer";
private static final String TAG_KET = "keterangan";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_penjualan1);
mejaTv = (TextView) findViewById(R.id.meja);
customerTv = (TextView) findViewById(R.id.customer);
keteranganTv = (TextView) findViewById(R.id.keterangan);
// Loading Profile in Background Thread
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Penjualan1.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
// TODO Auto-generated method stub
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_order_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_GET); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
mejaTv = (TextView) findViewById(R.id.meja);
customerTv = (TextView) findViewById(R.id.customer);
keteranganTv = (TextView) findViewById(R.id.keterangan);
// display product data in EditText
mejaTv.setText(product.getString(TAG_MEJA));
customerTv.setText(product.getString(TAG_CUST));
keteranganTv.setText(product.getString(TAG_KET));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
PHP Code:
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM penjualan WHERE pid = $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["meja"] = $result["meja"];
$product["customer"] = $result["customer"];
$product["keterangan"] = $result["keterangan"];
// success
$response["success"] = 1;
// user node
$response["get"] = array();
array_push($response["get"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I've seen sample code from other posts, but I don't quite understand how to apply it. Can you please give me sample code?
PHP CODE
//you need add single quote near $pid
$result = mysql_query("SELECT *FROM penjualan WHERE pid = '$pid'");
For your java code :
public class Penjualan1 extends Activity {
// All xml labels
String pid;
TextView mejaTv;
TextView customerTv;
TextView keteranganTv;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile JSON url
private static final String url_order_detials = "-my url-/get_penjualan_details.php";
// ALL JSON node names
private static final String TAG_PRODUCT = "product";
private static final String TAG_SUCCESS = "success";
private static final String TAG_GET = "get";
private static final String TAG_MEJA = "meja";
private static final String TAG_CUST = "customer";
private static final String TAG_KET = "keterangan";
String sMeja, sCustomer, sKeterangan; //Declare a variable to handle your data.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_penjualan1);
mejaTv = (TextView) findViewById(R.id.meja);
customerTv = (TextView) findViewById(R.id.customer);
keteranganTv = (TextView) findViewById(R.id.keterangan);
// Loading Profile in Background Thread
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Penjualan1.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// Check for success tag
// TODO Auto-generated method stub
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_order_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_GET); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
// display product data in EditText
sMeja = product.getString(TAG_MEJA);
sCustomer = product.getString(TAG_CUST);
sKeterangan = product.getString(TAG_KET);
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
mejaTv.setText(sMeja);
customerTv.setText(sCustomer);
keteranganTv.setText(sKeterangan);
}
});
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
Done.. :D

Database cannot be connected

I m trying to create an application using eclipse. in the user-register page , after I entered all the required data, and click the submit button, the message " Unfortunately, your eclipse has been stopped". what does this message means and how to solve it?
public class UserRegister extends Activity {
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
RadioButton button1;
RadioButton button2;
Button button3;
int success = 0;
// url to create new product
private static String url_register_user = "http://192.168.1.100/MEMS/add_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_register);
// Edit Text
inputName = (EditText) findViewById(R.id.nameTextBox);
inputUsername = (EditText) findViewById(R.id.usernameTextBox);
inputEmail = (EditText) findViewById(R.id.emailTextBox);
inputPassword = (EditText) findViewById(R.id.pwTextBox);
// Create button
//RadioButton button1 = (RadioButton) findViewById(R.id.studButton);
// RadioButton button2 = (RadioButton) findViewById(R.id.shopownerButton);
Button button3 = (Button) findViewById(R.id.regSubmitButton);
// button click event
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputName.getText().toString();
String username = inputUsername.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if(name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals(""))
{
AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.nullAlert)
.setTitle(R.string.alertTitle);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.show();
}
else
{
new RegisterNewUser().execute();
}
}
});
}
class RegisterNewUser extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String username = inputUsername.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_register_user,
"GET", params);
// check log cat for response
Log.d("Send Notification", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), StudentLogin.class);
startActivity(i);
finish();
}
else
{
// failed to register
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
}
My php file:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password'])) {
$name = $_GET['name'];
$username = $_GET['username'];
$email = $_GET['email'];
$password = $_GET['password'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "You are successfully registered to MEMS.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Change the comparision method to equals() instead of contentEquals() in your code
as The String#equals() not only compares the String's contents, but also checks if the other object is also an instance of a String. The String#contentEquals() methods only compares the contents (the character sequence) and does not check if the other object is also an instance of String. It can be anything as long as it is an implementation of CharSequence or an instance of StringBuffer.
So change your code as like this
if(name.equals("")||username.equals("")||email.equals("")||password.equals(""))
{
....
}

Categories

Resources