嗨,我是android json的新手...在这里我将id发送到我的php服务器,用于从数据库获取数据,但没有得到任何value.plz帮助 在这里,当我点击按钮时,它将转到下一个活动并将id也用于下一个活动... 这是我的主要活动......
package com.example.mydata;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button tab1,tab2,tab3,tab4;
private static final String TAG_BID = "Id";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tab1=(Button)findViewById(R.id.tab1);
tab1.setOnClickListener(this);
tab2=(Button)findViewById(R.id.tab2);
tab2.setOnClickListener(this);
tab3=(Button)findViewById(R.id.tab3);
tab3.setOnClickListener(this);
tab4=(Button)findViewById(R.id.tab4);
tab4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.tab1:
String id = "1";
Intent i=new Intent(MainActivity.this,Table1Activity.class);
//startActivity(i);
i.putExtra(TAG_BID, id);
// starting new activity and expecting some response back
startActivityForResult(i, 100);
break;
case R.id.tab2:
break;
case R.id.tab3:
break;
case R.id.tab4:
break;
}
}
@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);
}
}
}
这是我的json文件..
package com.example.mydata;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import 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 mehtod
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;
}
}
这是我的下一个活动
public class Table1Activity extends Activity {
TextView txtName;
TextView txtPrice;
TextView txtDesc;
String id;
JSONObject product;
//String Id;
//JSONObject product;
//String doc;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product us-book/Get_product_details.php
private static final String url = "http://app-developments.com/Jasmita/Address-book/Get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USER = "Address_Book";
private static final String TAG_ID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_EMAIL = "Address";
// JSONArray user = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table1);
Toast.makeText(getApplicationContext(), "welcome", 3000).show();
//new GetProductDetails().execute();
Intent i = getIntent();
// getting product id (pid) from intent
id = i.getStringExtra(TAG_ID);
// Getting complete product details in background thread
new GetProductDetails().execute();
// Getting complete product details in background thread
// save button click event
// Delete button click event
}
/**
* 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(Table1Activity.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("id", id));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params);
// check your log for json response
Log.d("Single book Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_USER); // JSON Array
// get first product object from JSON Array
product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.ID1);
txtPrice = (TextView) findViewById(R.id.name1);
txtDesc = (TextView) findViewById(R.id.add1);
// display product data in EditText
txtName.setText(product.getString(TAG_ID));
txtPrice.setText(product.getString(TAG_NAME));
txtDesc.setText(product.getString(TAG_EMAIL));
}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代码
<?php
$response = array();
require_once __DIR__ . '/db_connect1.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
if (isset($_GET["id"])) {
$id = $_GET['id'];
// get a product from products table
$result = mysql_query("SELECT * FROM Address_Book WHERE Id =$id ");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$Address_Book = array();
$Address_Book["id"] = $row["id"];
$Address_Book["Name"] = $row["Name"];
$Address_Book["Address"] = $row["Address"];
// success
$response["success"] = 1;
// user node
$response["Address_Book"] = array();
array_push($response["Address_Book"], $Address_Book);
// 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);
}
?>