2013-05-13 36 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