2017-09-29 53 views
-4

我想显示信息检索从服务器使用PHP在Android应用程序,我已经检索到的信息与字符串与JSON格式在这里是检索代码和PHP代码。 PHP代码如何在android studio中从字符串中提取信息?

<?php 
if($_SERVER['REQUEST_METHOD']=='POST') 
{ 

    //Getting values 
    $username = $_POST['username']; 
    require_once('dbConnect.php'); 

    $sql = "SELECT * FROM `employee` WHERE username='$username'"; 
    $result=mysqli_query($con,$sql); 
    $row = mysqli_fetch_array($result,MYSQLI_ASSOC); 
    echo json_encode($row); 
} 

的Android检索代码

@Override 
    protected String doInBackground(Void... params) { 
     // TODO: attempt authentication against a network service. 

     HashMap<String,String> params1= new HashMap<>(); 
     params1.put(Config.KEY_EMP_UN,mUsername); 

     RequestHandler rh = new RequestHandler(); 
     String res = rh.sendPostRequest(Config.URl_RET, params1); 
     return res; 
     // TODO: register the new account here. 
    } 

    @Override 
    protected void onPostExecute(final String success) { 
     Toast.makeText(Main2Activity.this,success,Toast.LENGTH_LONG).show(); 
     final TextView Textview1 = (TextView)findViewById(R.id.textView); 
     Textview1.setText(success); 
    } 

这检索如下图所示格式信息enter image description here

什么是想要做的是提取名称,型号,薪水,密码并将它们显示在单独的TextView中。我可以这样做吗?

+0

谷歌的 “Android JSON”。另外,你的PHP代码中有一个可能的SQL注入问题。 –

+0

为什么你不问之前搜索? –

回答

1

把你的服务器响应,并解析它像这样

try { 
JSONObject jsonObject = new JSONObject(response); 

if (jsonObject.has("name")) { 
String name=jsonObject.getString("name"); 
} 
if (jsonObject.has("designation")) { 
String designation=jsonObject.getString("designation"); 
} 
if (jsonObject.has("salary")) { 
int salary=jsonObject.getInt("salary"); 
} 
if(jsonObject.has("password")){ 
String password=jsonObject.getString("password"); 
} 
}catch (Exception e) { 

} 
0

你解析JSON:

JSONObject jsonObject=new JSONObject(success); 
//key value for eg : name,salary etc 
// now do whatever you want to do 
jsonObject.getString("your key value"); 
0

有很多可能的重复这个问题,所以我建议你阅读这个答案后,关闭了这个问题。

你在这里有一个JSON响应,为了解析JSON中的信息,你必须使用JSON解析器。像Gson,Jackson,Moshi这样的图书馆将能够做到这一点。

如果您使用Gson,您必须生成响应的模型类,可以使用jsonschema2pojo手动编写或自动生成响应。一旦Gson解析你的JSON,你可以使用你的模型类获取器来访问数据。

教程的链接

https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON

的Youtube视频

https://www.youtube.com/watch?v=y96VcLgOJqA

相关问题