我第一次使用了asynctask。我还使用一个线程在一段时间后在同一个活动中自动启动一个新活动。
Android Studio在代码中没有显示错误,但如果我登录或等待我的新活动开始,我的应用程序会崩溃。
这是一个测试应用程序对我使用asynctask&与我的MySQL连接。
我的代码:
public class MainActivity extends AppCompatActivity {
EditText bQ,bR;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread=new Thread(){
@Override
public void run() {
try {
sleep(5*1000);
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
catch (Exception ex)
{}
}
};
thread.start();
ImageView ImageView = (ImageView) findViewById(R.id.imageView);
ImageView.setImageResource(R.drawable.fb);
bQ = (EditText)findViewById(R.id.username);
bR = (EditText)findViewById(R.id.password);
}
public void insertIntoDatabase() {
final String username = bQ.getText().toString();
final String password = bR.getText().toString();
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
try {
URL url = new URL("http://passwds.esy.es/upload.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
String userPass = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(paramUsername, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(paramPassword, "UTF-8");
bufferedWriter.write(userPass);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("Result:", result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(username, password);
}
public void submit(View view) {
insertIntoDatabase();
}
}
logcat的:
04-08 09:54:30.929 6707-6707/? I/art: Late-enabling -Xcheck:jni
04-08 09:54:30.957 6707-6714/? I/art: Debugger is no longer active
04-08 09:54:30.957 6707-6714/? I/art: Starting a blocking GC Instrumentation
04-08 09:54:30.986 6707-6707/? D/LenovoAppIconTheme: ExtraResources;cleanCachedIcon;clear cache..
04-08 09:54:31.145 6707-6707/? W/System: ClassLoader referenced unknown path: /data/app/com.books.admin.foxbooks-1/lib/arm
04-08 09:54:31.159 6707-6707/? I/InstantRun: starting instant run server: is main process
04-08 09:54:31.246 6707-6707/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
04-08 09:54:31.298 6707-6707/? V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
04-08 09:54:31.300 6707-6707/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@cb8650
04-08 09:54:31.300 6707-6707/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@b74c049
04-08 09:54:31.529 6707-6727/? I/Adreno: QUALCOMM build : c6f59fa, Ie9c95840c4
Build Date : 06/16/17
OpenGL ES Shader Compiler Version: XE031.09.00.03
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.5.5.R1.07.00.00.269.021
Remote Branch : NONE
Reconstruct Branch : NOTHING
04-08 09:54:31.535 6707-6727/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-08 09:54:31.535 6707-6727/? D/OpenGLRenderer: Swap behavior 1
04-08 09:54:31.571 6707-6707/? W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
04-08 09:54:36.623 6707-6707/com.books.admin.foxbooks V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@633747d
04-08 09:54:36.623 6707-6707/com.books.admin.foxbooks V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@714df72
04-08 09:54:36.794 6707-6707/com.books.admin.foxbooks D/AndroidRuntime: Shutting down VM
04-08 09:54:36.795 6707-6707/com.books.admin.foxbooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.books.admin.foxbooks, PID: 6707
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.books.admin.foxbooks/com.books.admin.foxbooks.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.books.admin.foxbooks.MainActivity2.onCreate(MainActivity2.java:21)
at android.app.Activity.performCreate(Activity.java:6705)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
答案 0 :(得分:0)
您正在后台线程中调用活动这就是为什么您会收到错误 你需要像这样打电话
Thread thread=new Thread(){
@Override
public void run() {
try {
sleep(5*1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
});
}
catch (Exception ex)
{}
}
};
thread.start();