android - 应用程序在没有网络连接的情况下意外关闭

标签 android mysql json

我制作了一个 Android 登录应用程序,用于验证 mysql 数据库中的用户名和密码,如果它们匹配,则打开另一个 Activity 。当设备连接到互联网时,该应用程序运行正常,但当在没有网络连接的情况下打开该应用程序时,它会意外关闭。任何帮助,将不胜感激。不幸的是我是在 AIDE 中开发的,无法发布 logcat。

MainActivity.java

      MainActivity.java
      package com.mycompany.dynamic;
      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.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.EditText;
      import android.widget.Toast;
      import android.widget.*;
      import android.graphics.*; 
      public class MainActivity extends Activity implements OnClickListener{
             private EditText user, pass;
             private Button bLogin;
              // Progress Dialog
             private ProgressDialog pDialog;

           // JSON parser class
          JSONParser jsonParser = new JSONParser();
          private static final String LOGIN_URL = "http://necrecords.16mb.com/login.php";
          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.main);      
                  user = (EditText)findViewById(R.id.username);
                  pass = (EditText)findViewById(R.id.password);          
                  bLogin = (Button)findViewById(R.id.login);
                TextView tx1 = (TextView)findViewById(R.id.welcometv);
                Typeface custom_font1 = Typeface.createFromAsset(getAssets(), "fonts/myfont1.otf");
                tx1.setTypeface(custom_font1);
                TextView tx2 = (TextView)findViewById(R.id.welcometexttv);
                Typeface custom_font2 = Typeface.createFromAsset(getAssets(), "fonts/myfont2.ttf");
                tx2.setTypeface(custom_font2);
                  bLogin.setOnClickListener(this);
                        }

            @Override
            public void onClick(View v) {
                  // TODO Auto-generated method stub
                  switch (v.getId()) {
                  case R.id.login:
                              new AttemptLogin().execute();
                  // here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
                  default:
                        break;
                  }
            }

            class AttemptLogin extends AsyncTask<String, String, String> {
                   /**
               * Before starting background thread Show Progress Dialog
               * */
                  boolean failure = false;

              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
                  pDialog = new ProgressDialog(MainActivity.this);
                  pDialog.setMessage("Attempting for login...");
                  pDialog.setIndeterminate(false);
                  pDialog.setCancelable(true);
                  pDialog.show();
              }

                  @Override
                  protected String doInBackground(String... args) {
                        // TODO Auto-generated method stub
                         // here Check for success tag
                  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 = jsonParser.makeHttpRequest(
                             LOGIN_URL, "POST", params);

                      // checking  log for json response
                      Log.d("Login attempt", json.toString());

                      // success tag for json
                      success = json.getInt(TAG_SUCCESS);
                      if (success == 1) {
                        Log.d("Successfully Login!", json.toString());

                        Intent ii = new Intent(MainActivity.this,MainMenu.class);
                        finish();
      // this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
                              startActivity(ii);
                        return json.getString(TAG_MESSAGE);
                      }else{

                        return json.getString(TAG_MESSAGE);

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

                  return null;
                  }
                  /**
               * Once the background process is done we need to  Dismiss the progress dialog asap
               * **/
              protected void onPostExecute(String message) {

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

JSONParser.java

  JSONParser.java
  package com.mycompany.dynamic;
  import org.apache.http.HttpEntity;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import org.apache.http.HttpResponse;
  import java.io.InputStreamReader;
  import java.io.UnsupportedEncodingException;
  import java.util.List;
  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.util.Log;
  public class JSONParser {
        static InputStream is = null;
        static JSONObject jsonObj ;
        static String json = "";

      // default no argument constructor for jsonpaser class
      public JSONParser() {

      }


      public JSONObject getJSONFromUrl(final String url) {

          // Making HTTP request
          try {

              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);

              // Executing POST request & storing the response from server  locally.
              HttpResponse httpResponse = httpClient.execute(httpPost);

  HttpEntity httpEntity = httpResponse.getEntity();

              is = httpEntity.getContent();

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

          try {


              // Create a BufferedReader
           BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              // Declaring string builder 
              StringBuilder str = new StringBuilder();
              //  string to store the JSON object.
              String strLine = null;

              // Building while we have string !equal null.
              while ((strLine = reader.readLine()) != null) {
                  str.append(strLine + "\n");
              }

              // Close inputstream.
              is.close();
              // string builder data conversion  to string.
              json = str.toString();
          } catch (Exception e) {
              Log.e("Error", " something wrong with converting result " + e.toString());
          }

          // Try block used for pasrseing String to a json object
          try {
              jsonObj = new JSONObject(json);
          } catch (JSONException e) {
              Log.e("json Parsering", "" + e.toString());
          }

          // Returning json Object.
          return jsonObj;

      }



      public JSONObject makeHttpRequest(String url, String method,
              List<NameValuePair> params) {

          // Make HTTP request
          try {

              // checking request method
              if(method == "POST"){

                  // now defaultHttpClient object
                  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 (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }

          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              StringBuilder str = new StringBuilder();
              String strLine = null;
              while ((strLine = reader.readLine()) != null) {
                  str.append(strLine + "\n");
              }
              is.close();
              json = str.toString();
          } catch (Exception e) {

        }

          // now will try to parse the string into JSON object
          try {
              jsonObj = new JSONObject(json);
          } catch (JSONException e) {

    }


          return jsonObj;

      }

  }

最佳答案

在调用服务器之前确保网络正常工作

 if(isNetworkAvailable){
    new AttemptLogin().execute();
     }

当没有收到数据时,json解析器无法解析数据并抛出异常。 网络可用性的方法可能是

     public  boolean isNetworkAvailable(Context context) {
    // TODO Auto-generated method stub
    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;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

关于android - 应用程序在没有网络连接的情况下意外关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889850/

相关文章:

sql - 在查询之前和之后获取行

c# - 有没有办法让 JSON.net 尊重 System.Text.Json JsonPropertyName 属性

android - 调用带 * 字符的电话号码

java - 如何创建可序列化对象并传递给 bundle.putSerializable(key, value)

android - 比较android中的两个图像

android - 无法关闭与 Google Play 游戏的回合制多人游戏

mysql - 查找在某个时间段内出现而在另一个时间段内没有出现的用户ID

mysql - 如何为mysql的错误信息添加一种新的语言?

javascript - 如何在 Javascript 中使 JSON.Parser 适应 NaN?

javascript - 如何使用 PHP 和 JS 将 URL 中的 json 数组与另一个 json 数组组合起来