php - 如何在 android Activity 中读取 Json 响应。

标签 php android json android-activity android-asynctask

当详细信息未在 textedit 中填写时,我从 php 获得的 json 响应为 {"success":0,"message":"Please Enter the Valid detail."}。所以我想读取成功和消息值,并且我想将该消息显示为 Toast。我该怎么做。

这是异步任务:

  class CreateUser extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setMessage("Creating User...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        //int success;

        // try {
        // Building Parameters
        HashMap<String, String> Params = new HashMap<String, String>();
        Params.put("username", username);
        Params.put("password", password);
        Params.put("email", email);
        Params.put("ph", ph);

        Log.d("request!", "starting");
        String encodedStr = getEncodedData(Params);

        //Will be used if we want to read some data from server
        BufferedReader reader = null;

        //Connection Handling
        try {
            //Converting address String to URL
            URL url = new URL(LOGIN_URL);
            //Opening the connection (Not setting or using CONNECTION_TIMEOUT)
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            //Post Method
            con.setRequestMethod("POST");
            //To enable inputting values using POST method
            //(Basically, after this we can write the dataToSend to the body of POST method)
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            //Writing dataToSend to outputstreamwriter
            writer.write(encodedStr);
            //Sending the data to the server - This much is enough to send data to server
            //But to read the response of the server, you will have to implement the procedure below
            writer.flush();

            //Data Read Procedure - Basically reading the data comming line by line
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while((line = reader.readLine()) != null) { //Read till there is something available
                sb.append(line + "\n");     //Reading and saving line by line - not all at once
            }
            line = sb.toString();           //Saving complete data received in string, you can do it differently

            //Just check to the values received in Logcat
            Log.i("custom_check","The values :");
            Log.i("custom_check",line);

            //Object b = line;
            Log.i("length", String.valueOf(line.length()));



            if (line.length() == 55) {
                Log.d("User Created!", line);
                SharedPreferences set = getSharedPreferences (UserNum, 0);
                set.edit().putString(uu,username).commit();
               // Toast.makeText(Register.this, "User Registered", Toast.LENGTH_SHORT).show();
                Intent i=new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
                finish();
                //return line.getString(TAG_MESSAGE);
            }else{
                  Log.d("Login Failure!", "failed");
                 // return b.getString(TAG_MESSAGE);
                Toast.makeText(Register.this, "Username already in use", Toast.LENGTH_SHORT).show();

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(reader != null) {
                try {
                    reader.close();     //Closing the
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //Same return null, but if you want to return the read string (stored in line)
        //then change the parameters of AsyncTask and return that type, by converting
        //the string - to say JSON or user in your case
        return null;
    }

    private String getEncodedData(Map<String,String> data) {
        StringBuilder sb = new StringBuilder();
        for(String key : data.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(data.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if(sb.length()>0)
                sb.append("&");

            sb.append(key + "=" + value);
        }
        return sb.toString();
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted

        pDialog.dismiss();
                     if (file_url != null){
            Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

} 

最佳答案

这很简单,把这段代码放在下面 line = sb.toString();

JSONObject jsonObject = new JSONObject(line);

String sucess=jsonObject.getString("success");
String message=jsonObject.getString("message");

关于php - 如何在 android Activity 中读取 Json 响应。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936968/

相关文章:

json - 从 Rust 中的 Json 枚举中读取特定字段

Android EditText inputType ="none"不起作用,变为 "textMultiLine"

asp.net-mvc - MVC : How to Return a String as JSON

php - 将 LIMIT 1 添加到 COUNT 查询

javascript - 从 jquery 发送国际电话到 codeigniter Controller 发送空?

android - 在 Room 中编写基于某个枚举值进行选择的类型安全查询

android - 使用 YouTube apk?

json - 使用 AWS Glue 爬网程序/分类器/ETL 作业将带有数组的 JSON 展平

php - 从MySQL中的三个表中的数据创建多维数组

php - WP 获取第一个和最后一个帖子标题