java - 如何在 Android 中实现 LoginActivity?
问题描述
我正在尝试LoginActivity
在 Android Studio 中实现预制,但无济于事。我被困在文件LoginDataSource.java中。下面是整个课程。
public class LoginDataSource {
public Result<LoggedInUser> login(final String username, final String password) {
try {
String url = "http://192.168.1.10:1234/my/api";
// Instantiate the RequestQueue.
RequestQueue requestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("Response:", response);
// Display the first 500 characters of the response string.
// textView.setText("Response is: " + response.substring(0, 500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// textView.setText("That didn't work!");
Log.e("Error:", error.toString());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user", username);
params.put("pass", password);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
LoggedInUser fakeUser =
new LoggedInUser(
java.util.UUID.randomUUID().toString(),
"John Doe");
return new Result.Success<>(fakeUser);
} catch (Exception e) {
return new Result.Error(new IOException("Error logging in", e));
}
}
public void logout() {
// TODO: revoke authentication
}
}
getCacheDir()
以红色突出显示,原因说明Cannot resolve method 'getCacheDir' in 'LoginDataSource'
。我尝试将参数更改为,context.getCacheDir()
但文件中没有context
可用的参数,我无法从任何地方导入。
我在这里做错了什么?这让我发疯。
解决方案
getCacheDir() 必须在 Context 对象上调用,因此您需要将 Context 传入才能登录。因此将登录名更改为登录名(最终字符串用户名,最终字符串密码,最终上下文上下文),然后调用 context.getCacheDir()
推荐阅读
- android - 不频繁的 Handler.post 导致大量丢帧和崩溃
- java - 如何使用 WebClient 或 HttpClient 获取请求指标
- oauth - 如何以 Slack 机器人用户的身份完成 Sign-In-With-Slac-cycle?
- git - Git - 从文件更改为符号链接未在合并中捕获
- ruby-on-rails - 未创建帖子,无法加载图像。铁轨上的红宝石
- ios - Flutter TextFormField iOS 键盘白色建议
- javascript - 带有点击标签的 HTML 横幅,但在验证器中它说它丢失了
- mongodb - MongoDB 存储问题(9001 已在使用)
- next.js - Next.js 全局重定向到小写 URL
- x11 - xcb_get_geometry_reply 返回比 Gnome 上的真实窗口稍大的窗口几何图形