如何在Android Studio(JAVA)中实现新的对话框错误

huangapple go评论67阅读模式
英文:

How to implement a new Dialog error in Android Studo (JAVA)

问题

以下是要翻译的代码部分:

So here is the status code for the errors. Not sure if the codes are random or not (I didn't make this project)

    public class StatusCodeUtil {
    
        public static final int AWS_GATEWAY_ERROR = 1;
        public static final int URL_INVALID = 2;
        public static final int INTERNAL_SERVER_ERROR = 14;
        public static final int ENDPOINT_INFO_STORAGE_INCOMPLETE = 7;
        public static final int NO_PERMISSION_GET_DEVICE_ID = 8;
        public static final int INVALID_API_FUNCTION = 18;
        public static final int INVALID_HTTP_STATUS_CODE = -1;
        public static final int NO_NETWORK_ERROR = 3; <- This is the status code I want to work
    } 

Here is the Callback for the errors

    public abstract class  ApiCallBack<T> implements Callback<ApiResponse<T>> {
    
        private ParabitSDKBeaconApplication application;
    
        public ApiCallBack(ParabitSDKBeaconApplication application) {
            this.application = application;
        }
    
        @Override
        public void onResponse(Call<ApiResponse<T>> call, Response<ApiResponse<T>> response) {
            Long roundTripTime = getRoundTripTime(response);
    
            if (response.isSuccessful()) {
                ApiResponse<T> responseBody = response.body();
                onApiResponse(responseBody.getMessage(), response.code(), responseBody.getData());
            } else {
                /**
                 * error level 1 (HTTP client or gateway error)
                 * */
                String errorBodyJson = getErrorBodyStr(response);
                // can not user ApiResponse<T> to catch the json here
                // will lead to exception: java.lang.AssertionError: illegal type variable reference
                // no good way to solve this (Gson's problem)
                ApiErrorResponse errorBody = GsonUtil.jsonStrToObject(errorBodyJson,
                        new TypeToken<ApiErrorResponse>(){});
    
                if (errorBody.getMessage().equalsIgnoreCase("forbidden")) { // x-api-key invalid
                    if (getLogControlManager().isLog()) {
                        Log.e(PARABIT_SDK_LOG, "AWS Gateway Error: " + errorBody.getMessage());
                    }
    
                    onError(new ApiErrorCodeInfo(AWS_GATEWAY_ERROR, response.code(),
                            errorBody.getMessage()));
                } else if (errorBody.getMessage().equalsIgnoreCase(
                        "missing authentication token")) {
                    if (getLogControlManager().isLog()) {
                        Log.e(PARABIT_SDK_LOG, "AWS Gateway Error: " + errorBody.getMessage());
                    }
                    onError(new ApiErrorCodeInfo(INVALID_API_FUNCTION, response.code(),
                            errorBody.getMessage()));
                } else {
                    if (getLogControlManager().isLog()) {
                        Log.e(PARABIT_SDK_LOG, "Other Error Response: " + errorBody.getMessage());
                    }
                    // should never happen for now
                    onError(new ApiErrorCodeInfo(INTERNAL_SERVER_ERROR, response.code(),
                            errorBody.getMessage()));
                }
            }
        }
    
        @Override
        public void onFailure(Call<ApiResponse<T>> call, Throwable t) {
            /**
             * error level 1 (HTTP client or gateway error)
             * */
            if (t instanceof UnknownHostException) { // host of end point is unknown
                if (getLogControlManager().isLog()) {
                    Log.e(PARABIT_SDK_LOG, "onFailure: " + "UnknownHostException");
                }
                onError(new ApiErrorCodeInfo(URL_INVALID, t.getLocalizedMessage()));
            } else {
                if (getLogControlManager().isLog()) {
                    Log.e(PARABIT_SDK_LOG, "onFailure: " + t.getLocalizedMessage());
                }
                onError(new ApiErrorCodeInfo(INTERNAL_SERVER_ERROR,
                        t.getLocalizedMessage()));
            }
        }
    
        public static<T> String getErrorBodyStr(Response<ApiResponse<T>> response) {
            if (response.errorBody() == null) {
                return "";
            }
    
            String errorBodyStr = "";
            try {
                errorBodyStr = response.errorBody().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return errorBodyStr;
        }
    
        protected Long getRoundTripTime(Response response) {
            Long roundTripTime = response.raw().sentRequestAtMillis()
                    - response.raw().receivedResponseAtMillis();
            return roundTripTime;
        }
    
    //    public abstract void onSuccess(String successMsg, List<T> data);
        public abstract void onApiResponse(String ApiMsg, int httpStatusCode, List<T> data);
        public abstract void onError(ApiErrorCodeInfo apiErrorCodeInfo);
    
        protected LogControlManager getLogControlManager() {
            return SdkApplicationInstance.getSdkLogControlManager(application);
        }
    }

 The code in the Activity that controls which error is shown

      loginViewModel.loginStatusInfo.observe(this, loginStatusInfo -&gt; {
                if (loginStatusInfo.getStatus() == API_SUCCESS_STATUS){
                    hideLoadingDialog();
                    startHomeActivity();
                }else if (loginStatusInfo.getStatus() == INTERNAL_SERVER_ERROR) {
                    hideLoadingDialog();
                    loginErrorDialog(getString(R.string.fail_to_login_server_error));
                }else if(loginStatusInfo.getStatus() == NO_NETWORK_ERROR){&lt;- I added this else if
                    hideLoadingDialog();
                    loginErrorDialog(getString(R.string.network_require_msg));
                }
                else {
                    hideLoadingDialog();
                    loginErrorDialog(loginStatusInfo.getMessage());
                }
            });

希望对你有所帮助。

英文:

So I want to add a dialog message to my app. There already an option for other types of error's. I just want to add an error for when there's no mobile data and WiFi. It's an older app, so it's taking me a bit more to understand, but here's what I got.

So here is the status code for the errors. Not sure if the codes are random or not (I didn't make this project)

public class StatusCodeUtil {
public static final int AWS_GATEWAY_ERROR = 1;
public static final int URL_INVALID = 2;
public static final int INTERNAL_SERVER_ERROR = 14;
public static final int ENDPOINT_INFO_STORAGE_INCOMPLETE = 7;
public static final int NO_PERMISSION_GET_DEVICE_ID = 8;
public static final int INVALID_API_FUNCTION = 18;
public static final int INVALID_HTTP_STATUS_CODE = -1;
public static final int NO_NETWORK_ERROR = 3; &lt;- This is the status code I want to work
} 

Here is the Callback for the errors

public abstract class  ApiCallBack&lt;T&gt; implements Callback&lt;ApiResponse&lt;T&gt;&gt; {
private ParabitSDKBeaconApplication application;
public ApiCallBack(ParabitSDKBeaconApplication application) {
this.application = application;
}
@Override
public void onResponse(Call&lt;ApiResponse&lt;T&gt;&gt; call, Response&lt;ApiResponse&lt;T&gt;&gt; response) {
Long roundTripTime = getRoundTripTime(response);
if (response.isSuccessful()) {
ApiResponse&lt;T&gt; responseBody = response.body();
onApiResponse(responseBody.getMessage(), response.code(), responseBody.getData());
} else {
/**
* error level 1 (HTTP client or gateway error)
* */
String errorBodyJson = getErrorBodyStr(response);
// can not user ApiResponse&lt;T&gt; to catch the json here
// will lead to exception: java.lang.AssertionError: illegal type variable reference
// no good way to solve this (Gson&#39;s problem)
ApiErrorResponse errorBody = GsonUtil.jsonStrToObject(errorBodyJson,
new TypeToken&lt;ApiErrorResponse&gt;(){});
if (errorBody.getMessage().equalsIgnoreCase(&quot;forbidden&quot;)) { // x-api-key invalid
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, &quot;AWS Gateway Error: &quot; + errorBody.getMessage());
}
onError(new ApiErrorCodeInfo(AWS_GATEWAY_ERROR, response.code(),
errorBody.getMessage()));
} else if (errorBody.getMessage().equalsIgnoreCase(
&quot;missing authentication token&quot;)) {
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, &quot;AWS Gateway Error: &quot; + errorBody.getMessage());
}
onError(new ApiErrorCodeInfo(INVALID_API_FUNCTION, response.code(),
errorBody.getMessage()));
} else {
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, &quot;Other Error Response: &quot; + errorBody.getMessage());
}
// should never happen for now
onError(new ApiErrorCodeInfo(INTERNAL_SERVER_ERROR, response.code(),
errorBody.getMessage()));
}
}
}
@Override
public void onFailure(Call&lt;ApiResponse&lt;T&gt;&gt; call, Throwable t) {
/**
* error level 1 (HTTP client or gateway error)
* */
if (t instanceof UnknownHostException) { // host of end point is unknown
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, &quot;onFailure: &quot; + &quot;UnknownHostException&quot;);
}
onError(new ApiErrorCodeInfo(URL_INVALID, t.getLocalizedMessage()));
} else {
if (getLogControlManager().isLog()) {
Log.e(PARABIT_SDK_LOG, &quot;onFailure: &quot; + t.getLocalizedMessage());
}
onError(new ApiErrorCodeInfo(INTERNAL_SERVER_ERROR,
t.getLocalizedMessage()));
}
}
public static&lt;T&gt; String getErrorBodyStr(Response&lt;ApiResponse&lt;T&gt;&gt; response) {
if (response.errorBody() == null) {
return &quot;&quot;;
}
String errorBodyStr = &quot;&quot;;
try {
errorBodyStr = response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
return errorBodyStr;
}
protected Long getRoundTripTime(Response response) {
Long roundTripTime = response.raw().sentRequestAtMillis()
- response.raw().receivedResponseAtMillis();
return roundTripTime;
}
//    public abstract void onSuccess(String successMsg, List&lt;T&gt; data);
public abstract void onApiResponse(String ApiMsg, int httpStatusCode, List&lt;T&gt; data);
public abstract void onError(ApiErrorCodeInfo apiErrorCodeInfo);
protected LogControlManager getLogControlManager() {
return SdkApplicationInstance.getSdkLogControlManager(application);
}
}

The code in the Activity that controls which error is shown

  loginViewModel.loginStatusInfo.observe(this, loginStatusInfo -&gt; {
if (loginStatusInfo.getStatus() == API_SUCCESS_STATUS){
hideLoadingDialog();
startHomeActivity();
}else if (loginStatusInfo.getStatus() == INTERNAL_SERVER_ERROR) {
hideLoadingDialog();
loginErrorDialog(getString(R.string.fail_to_login_server_error));
}else if(loginStatusInfo.getStatus() == NO_NETWORK_ERROR){&lt;- I added this else if
hideLoadingDialog();
loginErrorDialog(getString(R.string.network_require_msg));
}
else {
hideLoadingDialog();
loginErrorDialog(loginStatusInfo.getMessage());
}
});

Any help will be appreciated, Thank you.

答案1

得分: 0

So I actually called ConectivityManager on the loginViewModel.loginStatusInfo method and it worked.

loginViewModel.loginStatusInfo.observe(this, loginStatusInfo -> {
if (loginStatusInfo.getStatus() == API_SUCCESS_STATUS) {
hideLoadingDialog();
startHomeActivity();
} else if (loginStatusInfo.getStatus() == INTERNAL_SERVER_ERROR) {
hideLoadingDialog();
loginErrorDialog(getString(R.string.fail_to_login_server_error));
} else if (ConnectivityManager.TYPE_MOBILE == 0) {
hideLoadingDialog();
networkErrorDialog(getString(R.string.network_require_msg));
} else {
hideLoadingDialog();
loginErrorDialog(loginStatusInfo.getMessage());
}
});

英文:

So I actually called ConectivityManager on the loginViewModel.loginStatusInfo method and it worked.

   loginViewModel.loginStatusInfo.observe(this, loginStatusInfo -&gt; {
if (loginStatusInfo.getStatus() == API_SUCCESS_STATUS){
hideLoadingDialog();
startHomeActivity();
}else if (loginStatusInfo.getStatus() == INTERNAL_SERVER_ERROR) {
hideLoadingDialog();
loginErrorDialog(getString(R.string.fail_to_login_server_error));
}else if(ConnectivityManager.TYPE_MOBILE == 0){
hideLoadingDialog();
networkErrorDialog(getString(R.string.network_require_msg));
}
else {
hideLoadingDialog();
loginErrorDialog(loginStatusInfo.getMessage());
}
});

huangapple
  • 本文由 发表于 2023年2月14日 07:23:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定