gpt4 book ai didi

android - 我可以在一个 Activity 中有两个 AsyncTask 类吗(不同时工作)

转载 作者:行者123 更新时间:2023-11-30 22:54:42 25 4
gpt4 key购买 nike

我正在尝试制作应用程序,我从 Mysql 获取数据并填充列表。我正在使用 AsyncTask 类并且它有效。我有一个“添加”按钮,它调用 AlertDialog,用户可以在其中添加新单词到列表中。所以我想使用第二个 AsyncTask 类,当用户单击 AlertDialog 中的“添加”按钮时将执行该类。但这种方式行不通。

让 AsyncTask 工作,但第二个 Post AsyncTask 不起作用,当我单击 AlertDialog 中的“添加”按钮时应用程序崩溃。

当我尝试仅调用 Getting AsyncTask(两次 - 在启动 Activity 和 AlertDialog 中)应用程序时有效。

当我第一次调用 Post AsyncTask 时,它工作并且数据被发送到 mysql。

当我调用先执行 Post AsyncTask 然后调用 Getting (JSONParse) AsyncTask 时,应用程序也可以正常工作。仅当 JSONParse AsyncTask 在 Post AsyncTask 之前执行并且 Post AsyncTask 从 AlertDialog 执行时,应用程序才工作。

这是我的 MainActivity

    package com.example.bakalarka;


import android.os.Bundle;
import android.os.AsyncTask;
import android.app.ProgressDialog;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
import android.util.Log;
import android.widget.Button;


import android.app.AlertDialog;
import android.content.DialogInterface;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.NameValuePair;

import org.json.JSONArray;


public class MainActivity extends Activity {
private final static String URL_GET = "http://bulva.byethost33.com/connect.php";
private final static String URL_POST = "http://bulva.byethost33.com/post.php";
Button pridat_btn;
Button zrusit_btn;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pridat_btn = (Button) findViewById (R.id.add_btn);
zrusit_btn = (Button) findViewById (R.id.remove_btn);
pridat_btn.setOnClickListener (new OnClickListener(){
@Override
public void onClick (View view) {
add();
}
});
new JSONParse().execute();
}




private void add() {
final View addView=getLayoutInflater().inflate(R.layout.add, null);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Adding new category");
builder.setView(addView);
builder.setMessage("Write name of new category:");

builder.setPositiveButton(R.string.pridat, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
EditText title = (EditText)findViewById (R.id.title);
new Post().execute(title.getText().toString());
}
});
builder.setNegativeButton(R.string.zrusit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});

builder.show();
}

public void postData (String value) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_POST);

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("kategorie", value));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}



private class JSONParse extends AsyncTask<Void, Void, String> {
private ProgressDialog pDialog;
List<String> r = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getApplicationContext(), android.R.layout.simple_list_item_1, r);

ListView list = (ListView) findViewById (R.id.listView1);

@Override
protected void onPreExecute () {
super.onPreExecute();
pDialog = new ProgressDialog (MainActivity.this);
pDialog.setMessage ("Getting categories");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(Void...unused) {
String data = null;


try {
DefaultHttpClient client = new DefaultHttpClient ();
HttpGet request = new HttpGet (URL_GET);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
Log.e("STRING", data);



}
catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}

return data;
}
@Override
protected void onPostExecute (String data) {
try {
JSONArray json = new JSONArray (data);
for (int i = 0; i<json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
String name = obj.getString("name");
Log.e ("STRING", name);
r.add(name);
list.setAdapter(adapter);
}
}
catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}


pDialog.dismiss();
}
}
private class Post extends AsyncTask<String, Void, Void> {
private ProgressDialog pDialog;

@Override
protected void onPreExecute () {
super.onPreExecute();
pDialog = new ProgressDialog (MainActivity.this);
pDialog.setMessage ("Sending new category");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected Void doInBackground(String...params) {
postData (params[0]);


return null;
}
@Override
protected void onPostExecute (Void unused) {

pDialog.dismiss();

}
}
}

我的 Logcat 输出

11-14 12:58:55.538: E/Trace(617): error opening trace file: No such file or directory (2)
11-14 12:58:56.048: I/Choreographer(617): Skipped 33 frames! The application may be doing too much work on its main thread.
11-14 12:58:56.098: D/gralloc_goldfish(617): Emulator without GPU emulation detected.
11-14 12:58:56.418: I/Choreographer(617): Skipped 75 frames! The application may be doing too much work on its main thread.
11-14 12:58:57.338: I/Choreographer(617): Skipped 30 frames! The application may be doing too much work on its main thread.
11-14 12:59:00.258: I/Choreographer(617): Skipped 33 frames! The application may be doing too much work on its main thread.
11-14 12:59:01.227: D/dalvikvm(617): GC_CONCURRENT freed 159K, 3% free 8244K/8455K, paused 18ms+60ms, total 299ms
11-14 12:59:01.367: E/STRING(617): 11-14 12:59:01.367: E/STRING(617): [{"id":"1","nazev":"Strakapoud B\u011bloh\u0159bet\u00fd"},{"id":"2","nazev":"S\u00fdkora babka"},{"id":"3","nazev":"Katr\u00e1n tatarsk\u00fd"},{"id":"4","nazev":"ba\u0159i\u010dka p\u0159\u00edmo\u0159sk\u00e1"},{"id":"5","nazev":"ba\u017eanka vej\u010dit\u00e1"},{"id":"6","nazev":"b\u011blolist \u017elutav\u00fd"},{"id":"7","nazev":"bika klasnat\u00e1"},{"id":"8","nazev":"blatnice bahenn\u00ed"},{"id":"9","nazev":"bledule letn\u00ed"},{"id":"10","nazev":"brad\u00e1\u010dek srd\u010dit\u00fd"},{"id":"11","nazev":"bublinatka obecn\u00e1"},{"id":"12","nazev":"bytel rozprost\u0159en\u00fd"},{"id":"13","nazev":"\u010dilimn\u00edk b\u00edl\u00fd"},{"id":"15","nazev":"kakat"},{"id":"16","nazev":"kakat"},{"id":"17","nazev":"kakani"},{"id":"18","nazev":"kakacek"}] 11-14 12:59:01.367: E/STRING(617): 11-14 12:59:01.537: E/STRING(617): Strakapoud Bělohřbetý
11-14 12:59:01.537: E/STRING(617): Sýkora babka
11-14 12:59:01.557: E/STRING(617): Katrán tatarský
11-14 12:59:01.557: E/STRING(617): bařička přímořská
11-14 12:59:01.557: E/STRING(617): bažanka vejčitá
11-14 12:59:01.567: E/STRING(617): bělolist žlutavý
11-14 12:59:01.567: E/STRING(617): bika klasnatá
11-14 12:59:01.567: E/STRING(617): blatnice bahenní
11-14 12:59:01.567: E/STRING(617): bledule letní
11-14 12:59:01.597: E/STRING(617): bradáček srdčitý
11-14 12:59:01.597: E/STRING(617): bublinatka obecná
11-14 12:59:01.597: E/STRING(617): bytel rozprostřený
11-14 12:59:01.597: E/STRING(617): čilimník bílý
11-14 12:59:01.608: E/STRING(617): kakat
11-14 12:59:01.637: E/STRING(617): kakat
11-14 12:59:01.637: E/STRING(617): kakani
11-14 12:59:01.637: E/STRING(617): kakacek
11-14 12:59:01.647: I/Choreographer(617): Skipped 64 frames! The application may be doing too much work on its main thread.
11-14 12:59:06.057: D/dalvikvm(617): GC_CONCURRENT freed 45K, 3% free 8617K/8839K, paused 17ms+6ms, total 73ms
11-14 12:59:06.057: D/dalvikvm(617): WAIT_FOR_CONCURRENT_GC blocked 42ms
11-14 12:59:06.117: D/dalvikvm(617): GC_FOR_ALLOC freed 70K, 4% free 8912K/9223K, paused 38ms, total 38ms
11-14 12:59:06.127: I/Choreographer(617): Skipped 42 frames! The application may be doing too much work on its main thread.
11-14 12:59:07.677: I/Choreographer(617): Skipped 60 frames! The application may be doing too much work on its main thread.
11-14 12:59:10.258: D/AndroidRuntime(617): Shutting down VM
11-14 12:59:10.258: W/dalvikvm(617): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-14 12:59:10.268: E/AndroidRuntime(617): FATAL EXCEPTION: main
11-14 12:59:10.268: E/AndroidRuntime(617): java.lang.NullPointerException
11-14 12:59:10.268: E/AndroidRuntime(617): at com.example.bakalarka.MainActivity$2.onClick(MainActivity.java:80)
11-14 12:59:10.268: E/AndroidRuntime(617): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
11-14 12:59:10.268: E/AndroidRuntime(617): at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 12:59:10.268: E/AndroidRuntime(617): at android.os.Looper.loop(Looper.java:137)
11-14 12:59:10.268: E/AndroidRuntime(617): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 12:59:10.268: E/AndroidRuntime(617): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 12:59:10.268: E/AndroidRuntime(617): at java.lang.reflect.Method.invoke(Method.java:511)
11-14 12:59:10.268: E/AndroidRuntime(617): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 12:59:10.268: E/AndroidRuntime(617): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 12:59:10.268: E/AndroidRuntime(617): at dalvik.system.NativeStart.main(Native Method)
11-14 12:59:12.228: I/Process(617): Sending signal. PID: 617 SIG: 9

为了完整起见,我的 XML:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.bakalarka.MainActivity" >

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2" >
</ListView>

<Button
android:id="@+id/add_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/pridat" />

<Button
android:id="@+id/remove_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/smazat" />


</LinearLayout>

AlertDialog xml (add.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>

<EditText
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dip"
/>
</LinearLayout>

如果有任何帮助,我将非常高兴。

我想我发现了问题。应该是这部分代码

new Post().execute(title.getText().toString());

当我将 title.getText().toString() 替换为“某事”AsyncTask Post 作品时出现 NullPointerException。


已解决

我在 findViewById 之前添加了 addView,它现在可以工作了。我完全不明白为什么会这样,如果有人能更好地理解它,他可以解释一下。我会尝试在谷歌上找到解释

所以这段代码的部分看起来是这样的:

private void add() {

final View addView=getLayoutInflater().inflate(R.layout.add, null);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Přidání kategorie");
builder.setView(addView);
builder.setMessage("Zadejte název nové kategorie:");

builder.setPositiveButton(R.string.pridat, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
String category;
EditText title = (EditText)addView.findViewById (R.id.title);
category = title.getText().toString();

new Post().execute(category);
}
});
builder.setNegativeButton(R.string.zrusit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});

builder.show();
}

最佳答案

是否可以让用户仅在 JSONParse 完成时添加项目? (因此用户将无法在完成之前单击添加按钮)

如果可能的话,移动:

    pridat_btn.setOnClickListener (new OnClickListener(){
@Override
public void onClick (View view) {
add();
}
});

JSONParseonPostExecute 结束。这应该修复错误,因为它确保 JSONParse 在运行另一个 AsyncTask

之前完成

提示

JSONParse 仍在工作时,您可以使用 progress bar 之类的东西来显示加载屏幕,并在 时隐藏 progress bar JSONParse 完成(在 onPostExecute 内)

关于android - 我可以在一个 Activity 中有两个 AsyncTask 类吗(不同时工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26930202/

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