【问题标题】:Couldn't get json_encode($resu) in android onPostExecute(String res)无法在 android onPostExecute(String res) 中获取 json_encode($resu)
【发布时间】:2018-01-31 09:18:58
【问题描述】:

我正在尝试将我的 android 应用程序与后端 MySQL 连接,并且我使用 php 作为服务器端语言,但问题是我正在从 php 中回显 $res 数组,它无法在 Android onPoseExecute(String res) 中访问。

我在其他应用程序中尝试过相同的代码,它在那里工作得非常好..但是这段代码没有显示正确的响应,也没有在创建 Json 对象时出现错误。

我的用户名是在OnCrate()的android代码中定义的。

这是我的 php 代码:

session_start();
$con = mysqli_connect("localhost", "root", "", "SWR");

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return $str;
}   

$empID = strtoupper(clean($_POST['username']));
$resu = array();
$resu["status"] = true;
$sql3="insert into t_booked_hall values ('','$empID','','','','','','1','','','0','','0','','','','','','','','0','','','0','','')";    
$result3 = mysqli_query($con,$sql3);    
echo json_encode($resu);

安卓代码:

public class SigninActivity  extends AsyncTask<String, Void , String>{
    protected void onPreExecute(){}

    @Override
    protected String doInBackground(String... arg0) {
        try{
            link="https://haripriyag2362.000webhostapp.com/login_php.php";
            String data  = URLEncoder.encode("username", "UTF-8") + "=" +
                    URLEncoder.encode(username, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write( data );
            wr.flush();
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }
            return sb.toString();
        } catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }

    //final context context = this;
    @Override
    protected void onPostExecute(String result){
        try{
            JSONObject jObj = new JSONObject(result);

            if(jObj.getBoolean("status")) {
                 Toast.makeText(emp_home.this,"Invalid Succesful..",Toast.LENGTH_SHORT);
            }
            else{
                Toast.makeText(emp_home.this,"Invalid Login ! Try Again",Toast.LENGTH_SHORT);
            }
        }catch (JSONException ex) {
            ex.printStackTrace();
        }
    }
}

【问题讨论】:

  • 尝试在while循环中删除break;doInBackground方法
  • 是的。你现在只读一行。
  • it is not accessed in Android onPoseExecute(String res).. 这是什么意思?您本可以告诉我们 String res 包含的内容。
  • JSONObject jObj = new JSONObject(result);你不应该盲目这样做,因为还有一个声明return new String("Exception: " + e.getMessage());。所以首先检查 res 是否以 "Exception:" 开头。
  • 谢谢先生,@greenapps 正在删除,在 while 循环中插入解决了问题

标签: php android json


【解决方案1】:

你必须删除 break;在while循环中

您可以使用 getJSONfromURL(url) 函数从服务器获取数组响应

 public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httppost = new HttpPost(url);



        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (ConnectTimeoutException e) {
        //Here Connection TimeOut excepion
    } catch (Exception e) {
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
    }

    return jArray;
}

【讨论】:

  • @chandu 有帮助吗?
猜你喜欢
  • 2012-11-05
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 1970-01-01
相关资源
最近更新 更多