使用 JSON 和 PHP 从 Mysql DB 获取数据到 listView
Posted
技术标签:
【中文标题】使用 JSON 和 PHP 从 Mysql DB 获取数据到 listView【英文标题】:Fetching data from Mysql DB to listView using JSON and PHP 【发布时间】:2014-05-07 17:36:09 【问题描述】:我正在尝试从 android listview 中的 mysql DB 获取数据。但不知何故,我无法在 listView 中显示数据
我在教程的帮助下尝试了这个,即http://codeoncloud.blogspot.in/2013/07/android-mysql-php-json-tutorial.html
下面是我的 MainActivity.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.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
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_
android:layout_ >
<TextView
android:id="@+id/textView1"
android:layout_
android:layout_
android:text="TextView" />
</TableRow>
<ListView
android:id="@+id/listView1"
android:layout_
android:layout_
>
</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);
?>
【问题讨论】:
您是否遇到任何错误或异常? 没有错误,但数据在列表中不可见......并且它显示的“-”数量与数据库中的条目数量一样多 我试图打印 //textv1.setText(jsonResult);这导致我们在浏览器中执行 php 后发现的总 JSON 结果 尝试记录您的 jsonResult 并查看来自服务器的内容。它是有效的json吗?并在此处发布结果。 这是在 textView 中打印 jsonResult 的结果 "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"] 【参考方案1】:改变这个
String name = jsonChildNode.optString("employee_name");
String number = jsonChildNode.optString("employee_no");
到
String name = jsonChildNode.getString("emp_name");
String number = jsonChildNode.getString("emp_no");
【讨论】:
以上是关于使用 JSON 和 PHP 从 Mysql DB 获取数据到 listView的主要内容,如果未能解决你的问题,请参考以下文章
如何正确使用 PHP 将 MySQL 对象编码为 JSON?
从MySQL获取数据并使用JSON在ListView中显示它