2017-12-06 18 views
-6

ここで私はユーザーを登録しようとしているときに、ユーザーに関するサーバーからの応答であるトーストが必要です。私は正常にjsonを使用してサーバーに投稿することができますが、応答がある場合は、画像を捕まえる方法を考えなければなりません。JSONエラー応答を取得してトーストするにはどうすればよいですか?

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{ 

private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword; 
private Button btnSignUp; 
private Button btnLinkLogin; 
private String message = ""; 
private int code = 0; 

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

    signupInputName = (EditText) findViewById(R.id.signup_input_name); 
    signupInputEmail = (EditText) findViewById(R.id.signup_input_email); 
    signupInputPassword = (EditText) findViewById(R.id.signup_input_password); 
    retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password); 

    btnSignUp = (Button) findViewById(R.id.btn_signup); 
    btnLinkLogin = (Button) findViewById(R.id.btn_link_login); 

    btnSignUp.setOnClickListener(this); 

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

      Intent i = new Intent(getApplicationContext(),LoginActivity.class); 
      startActivity(i); 
     } 
    }); 
} 

public String POST(String url, Person person) 
{ 
    InputStream inputStream = null; 
    String result = ""; 

    try { 

     // 1. create HttpClient 
     HttpClient httpclient = new DefaultHttpClient(); 

     // 2. make POST request to the given URL 
     HttpPost httppost = new HttpPost(url); 

     String json = ""; 

     // 3. build jsonObject 
     JSONObject jsonObject = new JSONObject(); 
     jsonObject.accumulate("user_name", person.getUsername()); 
     jsonObject.accumulate("email", person.getEmail()); 
     jsonObject.accumulate("password", person.getPassword()); 

     // 4. convert JSONObject to JSON to String 
     json = jsonObject.toString(); 

     // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
     // ObjectMapper mapper = new ObjectMapper(); 
     // json = mapper.writeValueAsString(person); 

     // 5. set json to StringEntity 
     StringEntity se = new StringEntity(json); 

     // 6. set httpPost Entity 
     httppost.setEntity(se); 

     // 7. Set some headers to inform server about the type of the content 
     httppost.setHeader("Accept", "application/json"); 
     httppost.setHeader("Content-type", "application/json"); 

     // 8. Execute POST request to the given URL 
     HttpResponse httpResponse = httpclient.execute(httppost); 

     // 9. receive response as inputStream 
     inputStream = httpResponse.getEntity().getContent(); 

     // 10. convert inputstream to string 
     if(inputStream != null) 
      result = convertInputStreamToString(inputStream); 
     else 
      result = "Error! email exist"; 

    } catch (Exception e) { 
     Log.d("InputStream", e.getLocalizedMessage()); 
    } 

    // 11. return result 
    return result; 
} 

@Override 
public void onClick(View view) { 
    if(validate() == 1) 
    { 
     Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show(); 
    } 
    else if (validate() == 2) 
    { 
     Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show(); 
    } 
    else if (validate() == 3) 
    { 
     Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show(); 
    } 
    else if (validate() == 4) 
    { 
     //Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show(); 
     new HttpAsyncTask().execute("http://ip-addressses/api/register"); 
    } 

} 

private class HttpAsyncTask extends AsyncTask<String, Void, String> 
{ 
    @Override 
    protected String doInBackground(String... urls) { 

     person = new Person(); 
     person.setUsername(signupInputName.getText().toString()); 
     person.setEmail(signupInputEmail.getText().toString()); 
     person.setPassword(signupInputPassword.getText().toString()); 

     return POST(urls[0],person); 
    } 
    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 

     JSONObject jObject; 

     try { 
      jObject = new JSONObject(result); 
      if (jObject.has("error")) { 
       String aJsonString = jObject.getString("error"); 
       Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show(); 
      } else { 
       Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show(); 
      } 
     } catch (JSONException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 


    } 
} 

private int validate() { 
    if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals("")) 
    { 
     code = 1; 
     message = "Complete the form!"; 
    } 
    else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString()))) 
    { 
     code = 2; 
     message = "Re-check password"; 
    } 
    else if (!isValidEmail(signupInputEmail.getText().toString())) { 
     code = 3; 
     message = "Invalid email"; 
    } 
    else 
     code = 4; 

    return code; 
} 

public final static boolean isValidEmail(String target) 
{ 
    if (target == null) { 
     return false; 
    } else { 
     Matcher match = Patterns.EMAIL_ADDRESS.matcher(target); 
     return match.matches(); 
    } 
} 

private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    String line = ""; 
    String result = ""; 
    while((line = bufferedReader.readLine()) != null) 
     result += line; 

    inputStream.close(); 
    return result; 

} 
} 

ポストマン応答メールが

image

答えて

1

存在する場合だけ、このコードを変更::

jObject = new JSONObject(result); 
    if (jObject.has("error")) 
    { 
     String aJsonString = jObject.getString("error"); 
     Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show(); 
    } 
    else 
    { 
     Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show(); 
    } 
    } 
    catch (JSONException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
     Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show(); 
    } 

ので、このコードによって、あなたの応答がjsonでない場合に例外がスローされますキャッチします。そしてここでトーストを見ることができます。

これだけです。より多くの助けが必要なら、私に知らせてください。

+0

ありがとうございました – ZJL

関連する問題