-1

Привет, ребята, новичок в Android и в настоящее время изучают Android. Я создаю систему входа для своего приложения. Вот мой AsyncTaskПолучение исключения «java.lang.IllegalStateException: Содержимое было уничтожено», используя Json + String одновременно

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

     BufferedReader in = null; 

     ArrayList<NameValuePair> dataToSend = new ArrayList<>(); 
     dataToSend.add(new BasicNameValuePair("user_email", user.email)); 
     dataToSend.add(new BasicNameValuePair("user_pass", user.password)); 
     HttpParams httpRequestParams = new BasicHttpParams(); 
     HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT); 
     HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT); 
     HttpClient client = new DefaultHttpClient(httpRequestParams); 
     HttpPost post = new HttpPost(SERVER_ADDRESS + "login.php"); 
     User returnedUser= null; 
     try { 

      post.setEntity(new UrlEncodedFormEntity(dataToSend)); 
      HttpResponse httpResponse = client.execute(post); 
      HttpEntity entity = httpResponse.getEntity(); 

      in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); 
      String response = ""; 
      String line = ""; 
      while ((line = in.readLine())!= null){ 
       response+= line; 
      } 
      in.close(); 
      Log.d("qwerty", response); 

      if(response.equals("notAct\t\t")){ 
       return "notAct"; 
      }else if(response.equals("Error\t\t")){ 
       return "Error"; 
      } 
      String result = EntityUtils.toString(entity); 
      final JSONObject jObject = new JSONObject(result); 

      if (jObject.length() == 0) { 
       progressDialog.dismiss(); 
       AlertDialog.Builder builder = new AlertDialog.Builder(context); 
       builder.setMessage("Connection Error json"); 
       builder.setPositiveButton("ok", null); 
       builder.show(); 
      } else { 
       String user_id = jObject.getString("user_id"); 
       String user_name = jObject.getString("user_name"); 
       returnedUser = new User(user.email, user.password, user_name, user_id); 
       Log.d("qwerty", "Exception time"); 
       userCallback.done(returnedUser); 
      } 
     }catch(NullPointerException e){  
      e.printStackTrace(); 
     } catch (JSONException e){ 
      e.printStackTrace(); 
     } catch(ArithmeticException e) { 
      e.printStackTrace(); 
     } catch (ConnectTimeoutException e) { 
      Log.d("qwerty", "RunTime"); 
      return "Abc"; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 


@Override 
     protected void onPostExecute(String result) { 
      try { 
       if (result.equals("notAct")) { 
        //account activated 
       } else if (result.equals("Error")) { 
        //email does't exist 
       }else if (result.equals("Abc")) { 
        //connection time out 
       } 
      }catch(NullPointerException e){ 
       //null pointer exception 
      }catch (RuntimeException e){ 
       // 
      } catch (Exception e){ 
       // 
      } 
      super.onPostExecute(result); 
     } 

Все исключения handeled но JSON и строки, которые берутся из файла PHP этого AsyncTask не работают вместе

, если я пишу кодирование Json Перед прочтением строки (String Response), затем json Прочитайте его, но он не сможет прочитать ошибку, как если бы пользователь ввел неверные данные пользователя. Заранее благодарим за помощь.

+0

'EntityUtils.toString (объект)' + 'in.readLine()' где ('в' потребляя сущность) ... так что вы ожидали? ... знаете ли вы, что вы используете другой код для повторения одной и той же вещи дважды? – Selvin

+0

no coz am new in android и не понял, что именно вы говорите о ** EntityUtils.toString (entity) + in.readLine() где (при потреблении объекта) ** –

+0

использовать только 'String result = EntityUtils. toString (entity); 'и избавиться от цикла while. Как только вы прочитаете InputStream, исходящий из Http-вызова один раз, вы не сможете сделать это снова. Вот что означал Selvin – Blackbelt

ответ

0

Вот правильный код

 try { 

      post.setEntity(new UrlEncodedFormEntity(dataToSend)); 
      HttpResponse httpResponse = client.execute(post); 
      //HttpEntity entity = httpResponse.getEntity(); 
      //final JSONObject jObject = new JSONObject(EntityUtils.toString(entity)); 

      in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); 
      String response = ""; 
      String line = ""; 
      while ((line = in.readLine())!= null){ 
       response+= line; 
      } 
      in.close(); 
      Log.d("qwerty", response); 

      if(response.equals("notAct\t\t")){ 
       return "notAct"; 
      }else if(response.equals("Error\t\t")){ 
       return "Error"; 
      }else { 
       final JSONObject jObject = new JSONObject(response); 

       if (jObject.length() == 0) { 
        progressDialog.dismiss(); 
        AlertDialog.Builder builder = new AlertDialog.Builder(context); 
        builder.setMessage("Connection Error json"); 
        builder.setPositiveButton("ok", null); 
        builder.show(); 
       } else { 
        String user_id = jObject.getString("user_id"); 
        String user_name = jObject.getString("user_name"); 
        returnedUser = new User(user.email, user.password, user_name, user_id); 
        Log.d("qwerty", "Exception time"); 
        userCallback.done(returnedUser); 
       } 
      } 
      //String result = EntityUtils.toString(entity); 

     }catch(NullPointerException e){ 
      e.printStackTrace(); 
     } catch (JSONException e){ 
      e.printStackTrace(); 
     } catch(ArithmeticException e) { 
      e.printStackTrace(); 
     } catch (ConnectTimeoutException e) { 
      Log.d("qwerty", "RunTime"); 
      return "Abc"; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
Смежные вопросы