我在运行php文件时获取了json数据,但是我没能在android页面上获取它。我也使用
检查了连接 //checking the connection with server-.php file
int i =response.getStatusLine().getStatusCode();
System.out.println(i); // Checking the connection,If connected i=200
连接正确。 i = 200的值。
没有显示错误,但我仍然无法获取Android上的数据。
Php文件: - SampleConLogin1.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
<?php
$sql=mysqli_query($con,"SELECT * FROM `Test` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
$vendorid=$row['Vendor_ID'];
$username=$row['username'];
$password=$row['password'];
?>
<?php
$a = array($vendorid,$username,$password);
array_push($result,$a);
}
echo json_encode(array("result"=>$result));
?>
.php文件的输出: - 运行.php文件后生成的输出
Connected successfully {"result":[["1","nupur","nupur"],["4","",""],["3","nupur","1234"],["5","RAJ","RAJ"],["6","RAJ","RAJ"],["7","",""],["8","",""],["9","",""],["10","",""],["11","",""],["12","RAM","RAM"],["13","RAM","RAM"],["14","RAM","RAM"],["15","RAM","RAM"],["16","Nupur","Nupur"],["17","Nupur","Nupur"],["18","Nupur","Nupur"],["19","Nupur","Nupur"],["20","Rohit","Rohit"],["21","RAM","RAM"],["22","",""],["23","",""],["24","RAM","RAM"],["35","SAGAR","SAGAR"],["34","SAGAR","SAGAR"],["33","SAGAR","SAGAR"],["32","RAM","RAM"],["31","",""],["36","SAGAR","SAGAR"],["37","SAGAR","SAGAR"],["38","SAGAR","SAGAR"],["39","SAGAR","SAGAR"],["40","SAGAR","SAGAR"],["41","SAGAR","SAGAR"],["73","",""],["43","SAGAR","SAGAR"],["44","SAGAR","SAGAR"],["45","SAGAR","SAGAR"],["46","SAGAR","SAGAR"],["47","username","password"],["74","SAGAR","SAGAR"],["75","SAGAR","SAGAR"],["72","Krishna","Krishna"],["68","Honey","Honey"],["69","Ram","Ram"],["70","Ram","Ram"],["71","Ram","Ram"]]}
Json数据: - 使用json编辑器后,我得到了json格式的结果。我从php文件中获取json数据
-object {1}
-result [47]
-0 [3]
0 : 1
1 : nupur
2 : nupur
-1 [3]
0 : 4
1 :
2 :
-2 [3]
0 : 3
1 : nupur
2 : 1234
-3 [3]
0 : 5
1 : RAJ
2 : RAJ
-4 [3]
0 : 6
1 : RAJ
2 : RAJ
5 [3]
............................
Android -MainActivity.Java
package com.example.nupur.fetchjson;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ActionBarActivity {
String myJson;
private static final String TAG_RESULTS="result";
private static final String TAG_VENDOR_ID="id";
private static final String TAG_USERNAME="username";
private static final String TAG_PASSWORD="password";
JSONArray peoples =null;
ArrayList<HashMap<String, String>> personList;
ListView list;
// TextView check;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView) findViewById(R.id.listView);
//check=(TextView) findViewById(R.id.check);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try{
JSONObject jsonObj = new JSONObject(myJson);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
// check.setText(myJson);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String VENDOR_ID = c.getString(TAG_VENDOR_ID);
String username = c.getString(TAG_USERNAME);
String password = c.getString(TAG_PASSWORD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_VENDOR_ID,VENDOR_ID);
persons.put(TAG_USERNAME,username);
persons.put(TAG_PASSWORD,password);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_view,
new String[]{TAG_VENDOR_ID,TAG_USERNAME,TAG_PASSWORD},
new int[]{R.id.Vendor_id, R.id.username, R.id.password}
);
list.setAdapter(adapter);
}catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class getDATAJSON extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://kezinking.com/SampleConLogin1");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try{
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
//checking the connection with server-.php file
int i =response.getStatusLine().getStatusCode();
System.out.println(i); // Checking the connection,If connected i=200
}catch (Exception e) {
// Oops
}finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPostExecute(String result) {
myJson=result;
showList();
}
}
getDATAJSON g = new getDATAJSON();
g.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/check"/>
</LinearLayout>
Android- list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="@+id/Vendor_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textStyle="bold" />
<TextView
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"/>
<TextView
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textStyle="bold" />
</LinearLayout>
Android:- **AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nupur.fetchjson">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
答案 0 :(得分:0)
正如我所看到的,您正在尝试根据您从PHP脚本获得的json响应中的密钥获取数据。在show数据函数中,你这样编写来解析结果json数组中的数据。
JSONObject c = peoples.getJSONObject(i);
String VENDOR_ID = c.getString(TAG_VENDOR_ID);
String username = c.getString(TAG_USERNAME);
String password = c.getString(TAG_PASSWORD);
但是你从php脚本得到的结果是不接触它包含数组数组的对象数组。 所以你的php文件应该像这样给json响应。
{"result":[{"Vendor_ID":"1","username":"nupur","password":"nupur"},{"Vendor_ID":"2","username":"abc","password":"xyz"}]}
为了生成上面的json响应,你需要像这样更改你的php脚本。
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
<?php
$sql=mysqli_query($con,"SELECT * FROM `Test` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
$result[]=$row;
}
echo json_encode(array("result"=>$result));
?>
您的MainActvity中的另一项更改会更改此行
private static final String TAG_VENDOR_ID="id";
到这个
private static final String TAG_VENDOR_ID="Vendor_ID";
因为您将在json响应中获得Vendor_ID而不是id。
我希望这会对你有所帮助。 如果您发现任何问题,请随时提出。