2016-08-01 107 views
0

我在运行php文件时获取了json数据,但未能在android页面上获取它。我检查了连接也使用在Android中使用php获取Json格式数据的数据库信息

//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

你在doInBackground()的结果变量中有什么? –

+0

你有什么错误吗? –

+0

不会有错误。 –

回答

0

,我可以看到你试图获取基于密钥的数据JSON响应,你从你的PHP脚本中获得。在您的show data函数中,您可以像这样编写来解析结果json Array中的数据。

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脚本。在MainActvity

$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)); 
?> 

一次机会改变这一行

private static final String TAG_VENDOR_ID="id"; 

这个

private static final String TAG_VENDOR_ID="Vendor_ID"; 

,因为你将在JSON响应不是id来获取VENDOR_ID。

我希望这会帮助你。 如果您发现任何问题随时问。

+0

现在我的json数据以正确的格式出现了。但仍然没有结果在Android上。 –

+0

回声“连接成功”;从您的php代码中删除此行 –