连接错误的json异常

时间:2016-08-13 08:29:57

标签: php android mysql json post

我已经使用php和json创建了一个登录页面,但当我离线并使用该程序而不是显示错误时,程序将关闭。 如何显示此消息:"请检查您的网络连接"? 现在它说不幸的是start1已经停止了。

Android代码:

public class Login extends Activity {

EditText user,pass;
Button btnReg;
private static String url = "http://akosamanus.xzn.ir/Login.php";
private ProgressDialog pd;
JSONParser jparser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


    user = (EditText)findViewById(R.id.etgetuser);
    pass = (EditText)findViewById(R.id.etgetpass);
    btnReg = (Button)findViewById(R.id.btnReg);

    btnReg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            new loadperson().execute();

        }
    });



}

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




    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(Login.this);
        pd.setMessage("login");

        pd.show();
    }

    @Override
    protected String doInBackground(String... strings) {


        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();

        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username",username));
            params.add(new BasicNameValuePair("password",password));

            Log.d("request!", "starting");

            JSONObject json = jparser.makeHttpRequest(url, "POST", params);
            Log.d("Login attempt", json.toString());
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Successfully Login!", json.toString());



                Intent ii = new Intent(Login.this,com.example.eagle.start1.SelectPage.class);
                ii.putExtra("UserName", username);
                startActivity(ii);
                return json.getString(TAG_MESSAGE);
            }else{

                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();

        }



        return null;
    }

    @Override
    protected void onPostExecute(String message) {

        pd.dismiss();
        if (message != null){
            Toast.makeText(Login.this, message, Toast.LENGTH_SHORT).show();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

public class ConnectionDetector {

    public boolean isConnectingToInternet(Context context) {

        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context
                                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }

        if (haveConnectedWifi || haveConnectedMobile) {
            try {
                URL url = new URL("https://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection)   url.openConnection();
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "delete");
                urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                Log.e("internet error", "" + e);
                return false;
            }
        } else {
            return false;
        }
    }
}

并且在doInBackground方法中使用isConnectingToInternet(context)如果为true则继续后台任务,否则返回一些有意义的定义无网络。

答案 1 :(得分:0)

首先检查netwrok是否已连接:

english

然后在你的onClickListener中使用它:

 public boolean isConnectedToNetwork() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

同时将权限添加到btnReg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(isConnectedToNetwork()) new loadperson().execute(); else Toast.makeText(Login.this,"Please check your network connection",Toast.LENGTH_SHORT).show(); } });

AndroidMenifest