当我尝试连接到Mysql时,如何在检测到JSONException时修复错误?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当我尝试连接到Mysql时,如何在检测到JSONException时修复错误?相关的知识,希望对你有一定的参考价值。

我尝试连接到mysql。我在ligne“jObj = new JSONObject(json);”上捕获异常使用“pDialog.setMessage(”7777“);”因为pDialog显示“7777”时应用程序停止了

这是我的班级

JSON parser.Java

package com.larig2.test;

/**
 * Created by GNassro on 26/02/2018.
 */

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.UnsupportedEncodingException;
        import java.util.List;

        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.NameValuePair;
        import org.apache.http.client.ClientProtocolException;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.client.utils.URLEncodedUtils;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.json.JSONException;
        import org.json.JSONObject;

        import android.app.ProgressDialog;
        import android.util.Log;
        import java.util.Date;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params,ProgressDialog pDialog) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
//convert byte-stream to character-stream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            try {
                while((line = reader.readLine())!=null){
                    sb.append(line+"
");

                }
//close the input stream
                is.close();
                json = sb.toString();
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {

                    // TODO Auto-generated catch block
                    pDialog.setMessage("7777");
                    pDialog.show();

                    e.printStackTrace();

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                pDialog.setMessage("00000");
                pDialog.show();
                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            pDialog.setMessage("99999");
            pDialog.show();
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jObj;
    }
}

Sig您_client.Java

package com.larig2.test;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.content.Intent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Signin_Client extends AppCompatActivity {
    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputNom;
    EditText inputPrenom;
    EditText inputCIN;
    EditText inputJour;
    Spinner inputMois;
    EditText inputAnnee;
    Spinner inputAdresse;
    EditText inputTel;
    EditText inputMail;
    EditText inputPwd;

    //attribute string
    String nom;
    String prenom;
    String cin;
    String jour;
    String mois;
    String annee;
    String sexe;
    String adresse;
    String tel;
    String mail;
    String pwd;
    String date;


    // url to create new product
    private static String url_create_product = "http://192.168.1.177/Karhabti/signup_client.php";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin__activity_client);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final Intent contactus = new Intent(this, Contactez_nous.class);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                startActivity(contactus);
            }
        });
        //Spinner for Address Start  ****


        Spinner spinner = (Spinner) findViewById(R.id.adresse);
// Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.Tunisia_State, R.layout.spinnerthem1);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
        adapter.setDropDownViewResource(R.layout.spinnerthem);
        spinner.setAdapter(adapter);


        //Spinner for Address End  ****

        //Spinner for Months Date Start  ****


        Spinner spinnerMonths = (Spinner) findViewById(R.id.mois);
// Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapterMonths = ArrayAdapter.createFromResource(this,
                R.array.Mois_Date, R.layout.spinnerthem1);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner

        adapterMonths.setDropDownViewResource(R.layout.spinnerthem);
        spinnerMonths.setAdapter(adapterMonths);
        //Spinner for Months Date End  ****


        //select input

        inputNom = (EditText) findViewById(R.id.nom);
        inputPrenom = (EditText) findViewById(R.id.prenom);
        inputCIN = (EditText) findViewById(R.id.CIN);
        inputJour = (EditText) findViewById(R.id.jour);
        inputMois = (Spinner) findViewById(R.id.mois);
        inputAnnee = (EditText) findViewById(R.id.annee);
        inputAdresse = (Spinner) findViewById(R.id.adresse);
        inputTel = (EditText) findViewById(R.id.tel);
        inputMail = (EditText) findViewById(R.id.mail);
        inputPwd = (EditText) findViewById(R.id.pwd);
    }

    public void signupClickC(View view) {
        cin = inputCIN.getText().toString();
        new CreateNewClient().execute();
    }


    /**
     * Background Async Task to Create new product
     * */
    class CreateNewClient extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Signin_Activity_client.this);
            pDialog.setMessage("Creation en cours ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("nomC", "Med"));
            params.add(new BasicNameValuePair("prenomC", "Ali"));
            params.add(new BasicNameValuePair("CIN", cin));
            params.add(new BasicNameValuePair("date","1999-11/11" ));
            params.add(new BasicNameValuePair("sexe", "h"));
            params.add(new BasicNameValuePair("adresse", "gafsa"));
            params.add(new BasicNameValuePair("tel", "556"));
            params.add(new BasicNameValuePair("mail", "khhg"));
            params.add(new BasicNameValuePair("psw", "kdlkdj"));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params, pDialog);
            pDialog.setMessage("22222");
            pDialog.show();
            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), ClientSpace.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

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

            pDialog.dismiss();
        }

    }

}

我的问题是如何解决这个异常虽然插入到Mysql是成功的?

答案

你应该在JsonPArser类中创建pDialog对象而不是作为参数传递..在JsonParser类中使用下面的代码并且不要同时使用两个prgressDialog.ProgressDialog pd = new ProgressDialog(context); progressDialog.setMessage(your message);

以上是关于当我尝试连接到Mysql时,如何在检测到JSONException时修复错误?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Eclipse IDE 中连接到 mysql db? [复制]

如何通过 SSH 连接到 MySQL Docker 容器?

如何从 Perl 连接到 MySQL?

无法使用 PHP 页面连接到 MySQL

尝试连接到远程 MySQL 主机(错误 2003)

如何从 mac 连接到 aws Redshift db