Android : I need to retrive specific data from an ID using PHP code. But I get null values while running the code

on Thursday, September 4, 2014


Here is my PHP code



$response = array();

include_once('../connections/connection.php');

$id = $_GET['id'];

$result = mysql_query("SELECT * FROM vacancy_list WHERE 'id' = '$id'") or die(mysql_error());

//For each row, add the field to the corresponding column
$result = mysql_fetch_assoc($result);

$vacancy = array();
$vacancy["id"] = $result["id"];
$vacancy["title"] = $result["title"];
$vacancy["date"] = $result["date"];
$vacancy["country"] = $result["country"];
$vacancy["description"] = $result["description"];
// $vacancy["status"] = $row["status"];


$response["success"] = 1;

$response["vacancy"] = array();
array_push($response["vacancy"], $vacancy);


// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);

mysql_close($connection);
?>


The result :



{"success":1,"vacancy":[{"id":null,"title":null,"date":null,"country":null,"description":null}]}


Every time I pass value in $id = $_GET['id']; result is same it displays null in all the field. I tried sending value directly from the URL it doesn't work..


What i am trying to do is get the ID from the android click event. every time click the list view it goes to another page but displays null value


Here is my android code:



package com.acos.allcorniceoverseas;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.acos.allcorniceoverseas.lib.DatabaseSQLite;
import com.acos.allcorniceoverseas.lib.JSONParser;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Vacancy extends ListActivity{

DatabaseSQLite dataController = new DatabaseSQLite(this);

private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> vacancyList;

// url to get all products list
private static String url_all_products = "http://hariyalihost.com/sql_to_pdf/vacancy.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_VACANCY = "vacancys";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_COUNTRY = "country";
private static final String TAG_DESC = "description";
// private static final String TAG_UPDATESTATUS = "status";
private static final String TAG_DATE ="date";

// products JSONArray
JSONArray products = null;

//MainActivity ma = new MainActivity();

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);

// Hashmap for ListView
vacancyList = new ArrayList<HashMap<String, String>>();
//ma.checkInternetConnection();

// 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 vid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();

// Starting new intent
Intent in = new Intent(getApplicationContext(),
Vacancy_Detail.class);
// sending pid to next activity
in.putExtra(TAG_ID, vid);

// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
/*lv.setOnScrollListener(new OnScrollListener(){
public void onScrollStateChanged(AbsListView view, int scrollState) {}

public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {

int lastInScreen = firstVisibleItem + visibleItemCount;
});*/

}

// 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(Vacancy.this);
pDialog.setMessage("Loading vacancy. 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_VACANCY);

// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);

// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String country = c.getString(TAG_COUNTRY);
String desc = c.getString(TAG_DESC);
// String uStatus = c.getString(TAG_UPDATESTATUS);
String udate = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_COUNTRY, country);
map.put(TAG_DESC, desc);
// map.put(TAG_UPDATESTATUS, uStatus);
map.put(TAG_DATE, udate);
// adding HashList to ArrayList
vacancyList.add(map);

// dataController.updateSyncStatus(c.get("id").toString(), c.getString("status").toString());
// DatabaseSQLite ds = new DatabaseSQLite(getApplicationContext());
// ds.getAllVacancy();
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Vacancy.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(
Vacancy.this, vacancyList,
R.layout.list_row, new String[]{ TAG_ID, TAG_TITLE, TAG_COUNTRY, TAG_DESC, TAG_DATE },
new int[]{R.id.pid, R.id.title, R.id.country, R.id.desc, R.id.vdate});

setListAdapter(adapter);

}
});

}

}
}


This code display value in list item whenever I click the list it goes to another "vacancy_detail" page

Here is vacancy_detail 's code:



package com.acos.allcorniceoverseas;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.acos.allcorniceoverseas.lib.JSONParser;

public class Vacancy_Detail extends Activity{

TextView tv1, tv2, tv3, tv4;

String vid;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> vacancyList;

// url to get all products list
private static String url_vacancy_detail = "http://hariyalihost.com/sql_to_pdf/vacancy_detail.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_VACANCY = "vacancy";
private static final String TAG_PID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_COUNTRY = "country";
private static final String TAG_DESC = "description";
private static final String TAG_DATE ="date";

// products JSONArray
JSONArray vacancy = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy_detail);

// getting product details from intent
Intent i = getIntent();

// getting product id (id) from intent
vid = i.getStringExtra(TAG_PID);

new GetVacancyDetails().execute();
}

/**
* Background Async Task to Get complete vacancy details
* */
class GetVacancyDetails extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Vacancy_Detail.this);
pDialog.setMessage("Loading vacancy 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("id", vid));

// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jParser.makeHttpRequest(
url_vacancy_detail, "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_VACANCY); // JSON Array

// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);

// vacancy with this pid found

tv1 = (TextView) findViewById(R.id.tvTitle);
tv2 = (TextView) findViewById(R.id.tvDate);
tv3 = (TextView) findViewById(R.id.tvCountry);
tv4 = (TextView) findViewById(R.id.tvDesc);

// display product data in EditText
tv1.setText(product.getString(TAG_TITLE));
tv2.setText(product.getString(TAG_DATE));
tv3.setText(product.getString(TAG_COUNTRY));
tv4.setText(product.getString(TAG_DESC));

}else{
// product with pid not found
tv1.setText("No details 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();
}
}
}

0 comments:

Post a Comment