Get data from MySQL to Android application
Posted
by
Mona
on Stack Overflow
See other posts from Stack Overflow
or by Mona
Published on 2012-12-08T04:35:33Z
Indexed on
2012/12/08
5:04 UTC
Read the original article
Hit count: 340
I want to get data from MySQL database using PHP and display it in Android activity. I code it and pass JSON Array but there is a problem i dont know how to connect to server and my all database is on local server. I code it Kindly tell me where i go wrong so I can get exact results. I'll be very thankful to you.
My PHP code is:
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET["cid"])) {
$cid = $_GET['cid'];
// get a product from products table
$result = mysql_query("SELECT *FROM my_task WHERE cid = $cid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$task = array();
$task["cid"] = $result["cid"];
$task["cus_name"] = $result["cus_name"];
$task["contact_number"] = $result["contact_number"];
$task["ticket_no"] = $result["ticket_no"];
$task["task_detail"] = $result["task_detail"];
// success
$response["success"] = 1;
// user node
$response["task"] = array();
array_push($response["my_task"], $task);
// echoing JSON response
echo json_encode($response);
} else {
// no task found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no task found
$response["success"] = 0;
$response["message"] = "No product found";
echo json_encode($response); }
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);}
?>
My Android code is:
public class My_Task extends Activity {
TextView cus_name_txt, contact_no_txt, ticket_no_txt, task_detail_txt;
EditText attend_by_txtbx, cus_name_txtbx, contact_no_txtbx, ticket_no_txtbx, task_detail_txtbx;
Button btnSave;
Button btnDelete;
String cid;
// Progress Dialog
private ProgressDialog tDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> my_taskList;
// single task url
private static final String url_read_mytask = "http://198.168.0.29/mobile/read_My_Task.php";
// url to update product
private static final String url_update_mytask = "http://198.168.0.29/mobile/update_mytask.php";
// url to delete product
private static final String url_delete_mytask = "http://198.168.0.29/mobile/delete_mytask.php";
// JSON Node names
private static String TAG_SUCCESS = "success";
private static String TAG_MYTASK = "my_task";
private static String TAG_CID = "cid";
private static String TAG_NAME = "cus_name";
private static String TAG_CONTACT = "contact_number";
private static String TAG_TICKET = "ticket_no";
private static String TAG_TASKDETAIL = "task_detail";
private static String attend_by_txt;
// task JSONArray
JSONArray my_task = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_task);
cus_name_txt = (TextView) findViewById(R.id.cus_name_txt);
contact_no_txt = (TextView)findViewById(R.id.contact_no_txt);
ticket_no_txt = (TextView)findViewById(R.id.ticket_no_txt);
task_detail_txt = (TextView)findViewById(R.id.task_detail_txt);
attend_by_txtbx = (EditText)findViewById(R.id.attend_by_txt);
attend_by_txtbx.setText(My_Task.attend_by_txt);
Spinner severity = (Spinner) findViewById(R.id.severity_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this,
R.array.Severity_array, android.R.layout.simple_dropdown_item_1line);
// Specify the layout to use when the list of choices appears
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
severity.setAdapter(adapter3);
// 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
cid = i.getStringExtra(TAG_CID);
// 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();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setMessage("Loading task details. Please wait...");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.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("cid", cid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = JSONParser.makeHttpRequest(
url_read_mytask, "GET", params);
// check your log for json response
Log.d("Single Task Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray my_taskObj = json
.getJSONArray(TAG_MYTASK); // JSON Array
// get first product object from JSON Array
JSONObject my_task = my_taskObj.getJSONObject(0);
// task with this cid found
// Edit Text
// display task data in EditText
cus_name_txtbx = (EditText) findViewById(R.id.cus_name_txt);
cus_name_txtbx.setText(my_task.getString(TAG_NAME));
contact_no_txtbx = (EditText) findViewById(R.id.contact_no_txt);
contact_no_txtbx.setText(my_task.getString(TAG_CONTACT));
ticket_no_txtbx = (EditText) findViewById(R.id.ticket_no_txt);
ticket_no_txtbx.setText(my_task.getString(TAG_TICKET));
task_detail_txtbx = (EditText) findViewById(R.id.task_detail_txt);
task_detail_txtbx.setText(my_task.getString(TAG_TASKDETAIL));
}
else
{
// task with cid 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
tDialog.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();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setMessage("Saving task ...");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String cus_name = cus_name_txt.getText().toString();
String contact_no = contact_no_txt.getText().toString();
String ticket_no = ticket_no_txt.getText().toString();
String task_detail = task_detail_txt.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_CID, cid));
params.add(new BasicNameValuePair(TAG_NAME, cus_name));
params.add(new BasicNameValuePair(TAG_CONTACT, contact_no));
params.add(new BasicNameValuePair(TAG_TICKET, ticket_no));
params.add(new BasicNameValuePair(TAG_TASKDETAIL, task_detail));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = JSONParser.makeHttpRequest(url_update_mytask,
"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
tDialog.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();
tDialog = new ProgressDialog(My_Task.this);
tDialog.setMessage("Deleting Product...");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
tDialog.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("cid", cid));
// getting product details by making HTTP request
JSONObject json = JSONParser.makeHttpRequest(
url_delete_mytask, "POST", params);
// check your log for json response
Log.d("Delete Task", 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
tDialog.dismiss();
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
My JSONParser code is:
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 mehtod
public static 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;
my all database is in localhost and it is not opening an activity. displays an error "Stopped unexpectedly":( How can i get exact results. Kindly guide me
© Stack Overflow or respective owner