java - 使用 JSON 和 PHP 从 Mysql DB 获取数据时出错

标签 java android mysql json

我正在学习构建 Android 应用程序,我需要一些帮助来从 MySQL 获取数据。我关注了this tutorial这样做,但我收到此错误:

Error org.json.JSONEXception: Value of type java.lang.String cannot be converted to JSONObject

在我的 MainActivity 上,我有一个按钮,单击该按钮将打开第二个 Activity 。第二个 Activity 必须从数据库获取并显示数据。这是第二个 Activity Restaurant.java

的代码
public class Restaurants extends Activity {
     private String jsonResult;
     private String url = "http://10.0.2.2/app1/GetRestaurants.php";
     private ListView listView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.restaurants);
         listView = (ListView) findViewById(R.id.listView1);
         accessWebService();
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
     }

    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
    try {
        HttpResponse response = httpclient.execute(httppost);
        jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString();
    }

    catch (ClientProtocolException e) {
           e.printStackTrace();
    } catch (IOException e) {
           e.printStackTrace();
      }
    return null;
 }

 private StringBuilder inputStreamToString(InputStream is) {
     String rLine = "";
     StringBuilder answer = new StringBuilder();
     BufferedReader rd = new BufferedReader(new InputStreamReader(is));

 try {
    while ((rLine = rd.readLine()) != null) {
    answer.append(rLine);
 }
}

 catch (IOException e) {
 // e.printStackTrace();
    Toast.makeText(getApplicationContext(),
    "Error..." + e.toString(), Toast.LENGTH_LONG).show();
 }
    return answer;
 }

     @Override
     protected void onPostExecute(String result) {
     ListDrwaer();
   }
 }// end async task

 public void accessWebService() {
    JsonReadTask task = new JsonReadTask();
    // passes values for the urls string array
    task.execute(new String[] { url });
 }

 // build hash set for list view
 public void ListDrwaer() {
     List<Map<String, String>> restaurantList = new ArrayList<Map<String, String>>();

 try {
     JSONObject jsonResponse = new JSONObject(jsonResult);
     JSONArray jsonMainNode = jsonResponse.optJSONArray("restoranti");

     for (int i = 0; i < jsonMainNode.length(); i++) {
     JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
     String name = jsonChildNode.optString("name");
     String menu = jsonChildNode.optString("menu");
     String outPut = name + "-" + menu;
     restaurantList.add(createRestaurants("restoranti", outPut));
   }
 } catch (JSONException e) {
      Toast.makeText(getApplicationContext(), "Error " + e.toString(),
      Toast.LENGTH_SHORT).show();
  }

 SimpleAdapter simpleAdapter = new SimpleAdapter(this, restaurantList,
    android.R.layout.simple_list_item_1,
    new String[] { "restoranti" }, new int[] { android.R.id.text1 });
    listView.setAdapter(simpleAdapter);
 }

 private HashMap<String, String> createRestaurants(String name, String menu) {
      HashMap<String, String> restaurantNameNo = new HashMap<String, String>();
      restaurantNameNo.put(name, menu);
      return restaurantNameNo;
 }
}

这是餐厅.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp" >
</ListView>

如果需要发布更多代码,请告诉我。非常感谢您的帮助。

我还发现了this answer到了几乎相似的帖子,并试图做出相同的事情,但对我不起作用。相同的错误和空白页。

最佳答案

// Maybe this will help ... 
    private class JsonReadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
    try {
        HttpResponse response = httpclient.execute(httppost);
        jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString();

// LETS RETURN SOMETING ... 
        return jsonResult;
    }

    catch (ClientProtocolException e) {
           e.printStackTrace();
    } catch (IOException e) {
           e.printStackTrace();
      }
    return null;
 }

关于java - 使用 JSON 和 PHP 从 Mysql DB 获取数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26631267/

相关文章:

java - 从 Eclipse ADT 迁移到 Android Studio 2.1 - 错误 : package android. support.v4.view 不存在

android - Navigation.findNavController()无法找到 View

php - 如何根据值将mysql中的行计入两个或多个变量?

用于错误报告的代码的 Android SQLite 转储数据库

android - 使用 Google Play 商店安装依赖的 apk

php - 将 Google map API V2 升级到 V3

mysql - 如何在Spring Boot中实现MYSQL的case功能

java - XML解析错误: not well-formed for Twilio

java - 如何将特定的java文件与cucumber中的特定功能文件进行匹配

Java贪吃蛇游戏——重画特定的drawString()方法