gpt4 book ai didi

Android Volley onErrorResponse 没有给出错误

转载 作者:太空狗 更新时间:2023-10-29 15:51:25 27 4
gpt4 key购买 nike

我正在尝试使用 volley 进行用户登录和注册,但在尝试登录或注册时遇到了问题。我尝试连接的服务器在我的本地主机上,它已打开并正在工作,我可以从其他应用程序访问它。

当我输入登录/注册凭据并按下按钮时,我收到一条日志,指出错误消息为空。问题是应用程序没有崩溃,日志 cat 没有指向任何导致错误的行,所以我不知道到底出了什么问题。

我已经尝试了不同的 volley 错误方法,例如 error.networkResponse 和其他一些方法来尝试获取更多信息,但没有一个返回任何信息。

我查看了网站上针对遇到类似问题的人的其他解决方案,但似乎没有任何效果。

谁能向我解释为什么会出现此错误?

记录猫日志

Login Error: null

类打印日志 - LoginActivity

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import com.example.rory.pocketchef.R;
import com.example.rory.pocketchef.app.AppConfig;
import com.example.rory.pocketchef.app.AppController;
import com.example.rory.pocketchef.helper.SQLiteHandler;
import com.example.rory.pocketchef.helper.SessionManager;

public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;

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

inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);

// SQLite database handler
db = new SQLiteHandler(getApplicationContext());

// Session manager
session = new SessionManager(getApplicationContext());

// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, FirstActivity.class);
startActivity(intent);
finish();
}

// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();

// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}

});

// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});

}

/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";

pDialog.setMessage("Logging in ...");
showDialog();

StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();

try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");

// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);

// Now store the user in SQLite
String uid = jObj.getString("uid");

JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");

// Inserting row in users table
db.addUser(name, email, uid, created_at);

// Launch main activity
Intent intent = new Intent(LoginActivity.this, FirstActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {

@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);

return params;
}

};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}

private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}

AppController 类

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}

public static synchronized AppController getInstance() {
return mInstance;
}

public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}

return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

list

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rory.pocketchef" >

<uses-permission android:name="android.permission.INTERNET" />

<android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application
android:name=".app.AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_logo"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/MyMaterialTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SingleRecipeDisplay"
android:label="@string/title_activity_single_recipe_display"
android:theme="@style/MyMaterialTheme" >
</activity>
<activity android:name=".Favourites" >
</activity>
<activity android:name=".Help" >
</activity>
<activity android:name=".activity.RegisterActivity">
</activity>
<activity android:name=".activity.LoginActivity">
</activity>

</application>

</manifest>

尝试注册时记录 Cat,(登录尝试的结果相同)

02-25 12:09:19.558 20001-20001/com.example.rory.loginandregistration E/RegisterActivity: Login Error: null
02-25 12:09:19.579 20001-20001/com.example.rory.loginandregistration D/Volley: [1] Request.finish: 7636 ms: [ ] http://178.167.255.22:8886/android_login_api/login.php 0x1d219ab4 NORMAL 1

Log Cat 打印堆栈

02-25 12:28:17.680 9729-9729/com.example.rory.pocketchef W/System.err: com.android.volley.TimeoutError
02-25 12:28:17.680 9729-9729/com.example.rory.pocketchef W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:147)
02-25 12:28:17.680 9729-9729/com.example.rory.pocketchef W/System.err: at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
02-25 12:28:28.391 9729-9743/com.example.rory.pocketchef I/art: Background sticky concurrent mark sweep GC freed 32313(1656KB) AllocSpace objects, 2(40KB) LOS objects, 35% free, 15MB/23MB, paused 9.512ms total 135.206ms

最佳答案

getMessage() 有时可以为空。我是这样读volley onErrorResponse()的,volley有直接/子直接异常类如下

Known Direct Subclasses
AuthFailureError, NetworkError, ParseError, ServerError, TimeoutError

Known Indirect Subclasses
NoConnectionError

使用 instanceOf 检查特定错误

if(error instanceof TimeOutError)
*show timeout error occured*
else if(error instanceof ServerError)
*show server error occured*
same for others

I have tried the different volley error methods like error.networkResponse

是的,阅读错误响应也很好,你可以确定服务器端到底发生了什么。 (服务器端发生错误时,服务器必须返回错误响应)不要忘记阅读error.networkResponse.statusCode 也是。

要获取有关此访问的更多信息Java doc VolleyError

已更新
在本地机器服务器上工作时:要记住的事情

  1. 始终使用系统 IP 地址(而不是本地主机)
  2. 确保本地路径正确。
  3. 始终在浏览器上测试 API/urls 或使用 Postman 检查并移动到 Android 项目。在使用这些东西进行测试时,您解决了许多服务器错误。

关于Android Volley onErrorResponse 没有给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com