简体   繁体   中英

Value Database of type java.lang.String cannot be converted to JSONObject

The data given using the code below is inserted into the database but doesn't show the dialog box whether it is successful or not.

My target api is 23.

Should I use gson?

Please help.

public class BackgroundTask extends AsyncTask<String, Void, String> {

String register_url = "http://192.168.1.101/loginapp/register.php";

    Context ctx;

    Activity activity;

    ProgressDialog progressDialog;

    AlertDialog.Builder builder;

    public BackgroundTask(Context ctx)
    {
        this.ctx = ctx;
        activity = (Activity)ctx;
    }

    @Override
    protected void onPreExecute() {
        builder = new AlertDialog.Builder(activity);
        progressDialog = new ProgressDialog(ctx);
        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("Connecting to server...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.show();

        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String method = params[0];
        if(method.equals("register"))
        {
            try {
                URL url = new URL(register_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String name = params[1];
                String email = params[2];
                String password = params[3];
                String data = URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
                        URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line = "";
                while((line=bufferedReader.readLine()) != null)
                {
                    stringBuilder.append(line+"\n");
                }
                httpURLConnection.disconnect();
                Thread.sleep(5000);
                // return string builder as normal string.
                return  stringBuilder.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String json) {
        try {
            progressDialog.dismiss();
            JSONObject jsonObject = new JSONObject(json);
            //need to get json array from json object.
            JSONArray jsonArray = jsonObject.getJSONArray("server_response");
            //now we can get each of the json data from json array.
            JSONObject jo = jsonArray.getJSONObject(0);
            //now we can read each data from json object;
            String code = jo.getString("code");
            String message = jo.getString("message");
            if(code.equals("reg_true"))
            {
                showDialog("Registration Success..",message,code);
            }
            else if(code.equals("reg_false"))
            {
                showDialog("Registration failed..",message,code);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    public void showDialog(String title, String message, String code)
    {
            builder.setTitle(title);
           if(code.equals("reg_true")||code.equals("reg_false"))
           {
               builder.setMessage(message);
               builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       dialog.dismiss();
                       activity.finish();
                   }
               });
               AlertDialog alertDialog = builder.create();
               alertDialog.show();

           }
    }
}

The return value of doInBackground() method is passed to onPostExecute(). Inside this method :

    @Override
    protected String doInBackground(String... params) {
        String method = params[0];
        if(method.equals("register"))
        {
            try {
                URL url = new URL(register_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                //....
                // return string builder as normal string.
                return  stringBuilder.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;            //YOU ARE RETURNING NULL. CHECK WHETHER params[0] is "register"
    }
    //....
    @Override
    protected void onPostExecute(String json) { //json might be null. Try to print it using log.debug()
        try {
            progressDialog.dismiss();
            JSONObject jsonObject = new JSONObject(json);   //This might throw exception
            //...
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

Paste the log in pastebin and attach a link here. And also see : String cannot be converted to JSONObject exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM