Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JSON和PHP从Mysql数据库获取数据时出错_Java_Android_Mysql_Json - Fatal编程技术网

Java 使用JSON和PHP从Mysql数据库获取数据时出错

Java 使用JSON和PHP从Mysql数据库获取数据时出错,java,android,mysql,json,Java,Android,Mysql,Json,我正在学习构建android应用程序,我需要从MySQL获取数据方面的帮助。我按此操作,但出现以下错误: 错误org.json.JSONEXception:无法将java.lang.String类型的值转换为JSONObject 在我的主活动中,我有一个按钮,单击该按钮可打开第二个活动。第二个活动必须从数据库获取并显示数据。这是第二个活动的代码Restaurant.java public class Restaurants extends Activity { private Stri

我正在学习构建android应用程序,我需要从MySQL获取数据方面的帮助。我按此操作,但出现以下错误:

错误org.json.JSONEXception:无法将java.lang.String类型的值转换为JSONObject

在我的主活动中,我有一个按钮,单击该按钮可打开第二个活动。第二个活动必须从数据库获取并显示数据。这是第二个活动的代码
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;
 }
}
公共类餐厅扩展活动{
私有字符串jsonResult;
专用字符串url=”http://10.0.2.2/app1/GetRestaurants.php";
私有列表视图列表视图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(右布局、餐厅);
listView=(listView)findViewById(R.id.listView1);
accessWebService();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
//访问web的异步任务
私有类JsonReadTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(参数[0]);
试一试{
HttpResponse response=httpclient.execute(httppost);
jsonResult=inputStreamToString(
response.getEntity().getContent()).toString();
}
捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
私有StringBuilder inputStreamToString(InputStream为){
字符串rLine=“”;
StringBuilder answer=新建StringBuilder();
BufferedReader rd=新的BufferedReader(新的InputStreamReader(is));
试一试{
而((rLine=rd.readLine())!=null){
答:追加(rLine);
}
}
捕获(IOE异常){
//e.printStackTrace();
Toast.makeText(getApplicationContext(),
“错误…”+e.toString(),Toast.LENGTH_LONG).show();
}
返回答案;
}
@凌驾
受保护的void onPostExecute(字符串结果){
ListDrwaer();
}
}//结束异步任务
public void accessWebService(){
JsonReadTask=新建JsonReadTask();
//传递URL字符串数组的值
执行(新字符串[]{url});
}
//为列表视图生成哈希集
公共无效列表{
List restaurantList=新建ArrayList();
试一试{
JSONObject jsonResponse=新的JSONObject(jsonResult);
JSONArray jsonMainNode=jsonResponse.optJSONArray(“restoranti”);
for(int i=0;i
这是restaurants.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>

如果需要发布更多代码,请让我知道。非常感谢你的帮助

我还找到了一个几乎相似的帖子,并试图做同样的事情,但对我不起作用。同样的错误和空白页。

//也许这会有帮助。。。
// 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;
 }
私有类JsonReadTask扩展了AsyncTask{ @凌驾 受保护的字符串doInBackground(字符串…参数){ HttpClient HttpClient=新的DefaultHttpClient(); HttpPost HttpPost=新的HttpPost(参数[0]); 试一试{ HttpResponse response=httpclient.execute(httppost); jsonResult=inputStreamToString( response.getEntity().getContent()).toString(); //让我们返回一些。。。 返回jsonResult; } 捕获(客户端协议例外e){ e、 printStackTrace(); }捕获(IOE异常){ e、 printStackTrace(); } 返回null; }
response.getEntity().getContent()的内容是什么?您似乎没有得到JSON对象?而且您总是返回null(因此在相同的方法中没有结果)。不幸的是,应用程序停止了
并且应用程序崩溃。您对
response.getEntity().getContent()的内容是什么意思
?您是否收到jsonResult…您从呼叫中得到了什么?调试此部分或记录它…以查看发生了什么。好的,我已将文件和DB上载到远程主机(internet)而不是本地主机上,并且工作正常。因此,问题出在我的本地主机上。