Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.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
使用JSON和PHP从Mysql数据库获取数据到listView_Php_Android_Mysql_Json - Fatal编程技术网

使用JSON和PHP从Mysql数据库获取数据到listView

使用JSON和PHP从Mysql数据库获取数据到listView,php,android,mysql,json,Php,Android,Mysql,Json,我正在尝试从android listview中的mysql数据库获取数据。但不知何故,我无法在listView中显示数据 我是在教程的帮助下尝试的,即 下面是我的主要活动。java public class MainActivity extends Activity { private String jsonResult; private String url = "http://10.0.2.2/markit/login.php"; private ListView listView;

我正在尝试从android listview中的mysql数据库获取数据。但不知何故,我无法在listView中显示数据

我是在教程的帮助下尝试的,即

下面是我的主要活动。java

public class MainActivity extends Activity {
 private String jsonResult;
 private String url = "http://10.0.2.2/markit/login.php";
 private ListView listView;
 private TextView textv1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView = (ListView) findViewById(R.id.listView1);
  textv1=(TextView)findViewById(R.id.textView1);
  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>> employeeList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String name = jsonChildNode.optString("employee_name");
    String number = jsonChildNode.optString("employee_no");
    String outPut = name + "-" + number;
    //textv1.setText(name);
    //textv1.setText(jsonResult);
    employeeList.add(createEmployee("employees", outPut));
   }
  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),
     Toast.LENGTH_SHORT).show();
  }

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

 private HashMap<String, String> createEmployee(String name, String number) {
  HashMap<String, String> employeeNameNo = new HashMap<String, String>();
  employeeNameNo.put(name, number);
  return employeeNameNo;
 }
}
公共类MainActivity扩展活动{
私有字符串jsonResult;
专用字符串url=”http://10.0.2.2/markit/login.php";
私有列表视图列表视图;
私有文本视图文本1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(listView)findViewById(R.id.listView1);
textv1=(TextView)findViewById(R.id.textView1);
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 employeeList=新建ArrayList();
试一试{
JSONObject jsonResponse=新的JSONObject(jsonResult);
JSONArray jsonMainNode=jsonResponse.optJSONArray(“emp_info”);
for(int i=0;i
下面是mainactivity.xml

<LinearLayout 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" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

    </TableRow>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >
    </ListView>

</LinearLayout>

Login.php

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="markit"; //replace with database name

$con=mysql_connect("localhost", "root", "")or die("cannot connect"); 
mysql_select_db("markit")or die("cannot select DB");
$sql = "select * from emp_info"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 

更改此选项

 String name = jsonChildNode.optString("employee_name");
 String number = jsonChildNode.optString("employee_no");


您是否收到任何错误或异常?没有错误,但数据在列表中不可见…并且它显示的“-”数量与数据库中的条目数量相同我已尝试打印//textv1.setText(jsonResult);在Browser中执行php后,我们会得到一个JSON总结果,请尝试记录您的jsonResult,并查看来自服务器的内容。它是有效的json吗?这是在文本视图{“emp_info”:[{“emp_no”:“1”,“emp_name”:“Ravi”},{“emp_no”:“2”,“emp_name”:“Div”},{“emp_no”:“3”,“emp_name”:“Harry”},{“emp_no”:“4”,“emp_name”:“Suresh”},{“emp_no”:“5”,“emp_name”:“Suu”}
 String name = jsonChildNode.getString("emp_name");
 String number = jsonChildNode.getString("emp_no");