2013-05-13 74 views
0

我是Android新手,我試圖將我的android應用程序連接到本地服務器phpmyadmin。我已經看到了一些關於通過PHP頁面(使用JSON)交互Android-MySql的教程,但是我的輸出有問題(例如,如何將我從JSON獲得的字符串轉換爲字符串?)。爲了讓你更好地理解這個問題,這是我的代碼:在Android中使用MySql項目將JSON轉換爲字符串

JSONParser.java

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; 

} 
} 

這是我的PHP文件 「get_product.php」(數據庫連接工作正常):

<?php 

$response = array(); 
require_once __DIR__ . '/db_connect.php'; 
$db = new DB_CONNECT(); 

if (isset($_GET["ID"])) { 
$ID_work = $_GET['ID']; 

$result = mysql_query("SELECT * FROM PRODUCTS WHERE ID = $ID"); 

if (!empty($result)) { 
    if (mysql_num_rows($result) > 0) { 

     $result = mysql_fetch_array($result); 

     $product = array(); 
     $product["ID"] = $result["ID"]; 
     $product["title"] = $result["title"]; 
     $product["description"] = $result["description"]; 

     // 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 { 
$response["success"] = 0; 
$response["message"] = "Required field(s) is missing"; 

echo json_encode($response); 
} 

?> 

在清單我接入Internet的權限,現在,在我的活動我插入:

private static String url = "http://IP_ADDRESS/connect/get_product.php"; 

但現在哪有我保存在字符串中獲得的標題和說明?

非常感謝您的幫助!

@Sajmon:這是logcat的

05-13 19:53:32.322: E/JSON Parser(10336): Error parsing data org.json.JSONException: Value <HTML><HEAD><TITLE> of type java.lang.String cannot be converted to JSONObject 
05-13 19:53:32.322: D/AndroidRuntime(10336): Shutting down VM 
05-13 19:53:32.322: W/dalvikvm(10336): threadid=1: thread exiting with uncaught exception (group=0x4001d578) 
05-13 19:53:32.332: E/AndroidRuntime(10336): FATAL EXCEPTION: main 
05-13 19:53:32.332: E/AndroidRuntime(10336): java.lang.RuntimeException: Unable to start activity ComponentInfo{package/package.MyActivity}: java.lang.NullPointerException 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.ActivityThread.access$1500(ActivityThread.java:121) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.os.Handler.dispatchMessage(Handler.java:99) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.os.Looper.loop(Looper.java:138) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.ActivityThread.main(ActivityThread.java:3701) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at java.lang.reflect.Method.invokeNative(Native Method) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at java.lang.reflect.Method.invoke(Method.java:507) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at dalvik.system.NativeStart.main(Native Method) 
05-13 19:53:32.332: E/AndroidRuntime(10336): Caused by: java.lang.NullPointerException 
05-13 19:53:32.332: E/AndroidRuntime(10336): at package.MyActivity.onCreate(MyActivity.java:158) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
05-13 19:53:32.332: E/AndroidRuntime(10336): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623) 
05-13 19:53:32.332: E/AndroidRuntime(10336): ... 11 more 

和行158:

String title = obj.getString("title"); 
+0

,你面臨的問題?首先得到json,然後解析它 – 2013-05-13 16:48:10

+0

在PHP方面確保你防止sql注入。在你使用$ _GET或$ _POST等任何地方使用mysql_real_escape_string來獲得你要在SQL語句中使用的變量。 – Fraggle 2013-05-13 18:22:29

回答

1

讓你幾乎得到了它。其實你的makeHttpRequest()方法返回JSONObjectPHP腳本返回。

現在你只需要解析你的JSON並從中檢索並保存數值。

這裏是解決方案僞代碼

JSONParser parser = new JSONParser(); 
JSONObject obj = parser.makeHttpRequest("GET", <url>, <params>); 
// getting data from JSON 
String title = obj.getString("title"); 
String decription = obj.getString("description"); 
+0

謝謝你的幫助!我嘗試如下,但我的設備中的應用程序崩潰..我在哪裏做錯了? (抱歉格式化..) – kareth 2013-05-13 17:34:06

+0

公共類A擴展活動{ \t .. \t String ID; private static String url =「...」; JSONParser parser = new JSONParser(); \t private static final String TAG_ID =「ID」; \t公共無效的onCreate(捆S){ \t \t ... \t \t嘗試{ \t \t列表<的NameValuePair> PARAMS =新的ArrayList <的NameValuePair>(); \t \t params.add(new BasicNameValuePair(「ID」,ID)); \t \t \t JSONObject obj = parser.makeHttpRequest(url,「GET」,params); \t \t \t String title = obj.getString(「title」); \t \t \t String description = obj。的GetString( 「描述」); \t \t} catch(JSONException e){ \t \t \t e.printStackTrace(); \t} \t} \t .. } – kareth 2013-05-13 17:37:28

+0

@kareth在您的問題中添加您的完整logcat。 – Sajmon 2013-05-13 17:51:13