gpt4 book ai didi

java - 当我更改 minSDKVersion 时发生 NetworkOnMainThreadException 错误

转载 作者:行者123 更新时间:2023-12-01 23:06:51 26 4
gpt4 key购买 nike

我开发了一个登录和注册系统,当 minSDKVersion 设置为 8 时,代码工作正常,但是当我将 minSDkVersion 更改为更高版本(例如 11 或 12)时,当我尝试登录或注册时,应用程序崩溃。发生了什么变化我应该在代码中编写以便我可以在更高版本中运行。LoginActivity.java 文件如下:

   package com.example.trial;

import java.util.HashMap;

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

import android.app.Activity;
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.TextView;

import com.example.trial.library.DatabaseHandler;
import com.example.trial.library.UserFunctions;

public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

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

// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);

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

public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);

// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");

// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));

// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);

// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);

// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});

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

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

RegisterActivity.java 文件是:

    package com.example.trial;

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

import com.example.trial.library.DatabaseHandler;
import com.example.trial.library.UserFunctions;

import android.app.Activity;
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.TextView;

public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

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

// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);

// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);

// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");

// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});

// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

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

logcat 看起来像这样:

   03-24 01:20:22.154: E/AndroidRuntime(1787): FATAL EXCEPTION: main
03-24 01:20:22.154: E/AndroidRuntime(1787): android.os.NetworkOnMainThreadException
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
03-24 01:20:22.154: E/AndroidRuntime(1787): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-24 01:20:22.154: E/AndroidRuntime(1787): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-24 01:20:22.154: E/AndroidRuntime(1787): at libcore.io.IoBridge.connect(IoBridge.java:112)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.net.Socket.connect(Socket.java:842)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-24 01:20:22.154: E/AndroidRuntime(1787): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.example.trial.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.example.trial.library.UserFunctions.loginUser(UserFunctions.java:43)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.example.trial.LoginActivity$1.onClick(LoginActivity.java:56)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.view.View.performClick(View.java:4240)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.view.View$PerformClick.run(View.java:17721)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.Handler.handleCallback(Handler.java:730)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.Handler.dispatchMessage(Handler.java:92)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.os.Looper.loop(Looper.java:137)
03-24 01:20:22.154: E/AndroidRuntime(1787): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.lang.reflect.Method.invokeNative(Native Method)
03-24 01:20:22.154: E/AndroidRuntime(1787): at java.lang.reflect.Method.invoke(Method.java:525)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-24 01:20:22.154: E/AndroidRuntime(1787): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-24 01:20:22.154: E/AndroidRuntime(1787): at dalvik.system.NativeStart.main(Native Method)

最佳答案

从 API 级别 11 开始,您无法在 UI 线程上执行网络操作。

因此,您必须使用AsyncTaskThread

AsyncTask 示例。

 class DowloadTest extends AsyncTask<String, Integer, String>

{
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(YourActivityName.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
};

@Override
protected String doInBackground(String... params) {
// parse your data here
return null;

}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);

pDialog.dismiss();

}

}
}

然后在需要时执行此函数,例如,

  new DowloadTest().execute();

更多引用请访问 Here

关于java - 当我更改 minSDKVersion 时发生 NetworkOnMainThreadException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22601730/

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