【问题标题】:Can I have two AsyncTask class in one activity (working not at the same time)我可以在一个活动中有两个 AsyncTask 类吗(不同时工作)
【发布时间】:2015-01-11 20:33:58
【问题描述】:

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

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

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

当我调用第一个 Post AsyncTask 时,它可以工作并将数据发送到 mysql。

当我调用 Post AsyncTask 的第一次执行,然后调用 Get (JSONParse) AsyncTask 时,应用程序也可以工作。仅当在 Post AsyncTask 之前执行 JSONParse AsyncTask 并且从 AlertDialog 执行 Post AsyncTask 时,应用程序才起作用。

这是我的 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();
    }

【问题讨论】:

  • 关注这个答案,它将对您的问题提供一些想法stackoverflow.com/questions/4068984/…
  • 我不想并行执行,我想执行一个 AsyncTask 结束,然后点击 make second AsyncTask。

标签: android mysql android-asynctask


【解决方案1】:

是否可以让用户只在JSONParse 完成时添加项目? (所以用户在完成之前将无法点击添加按钮)

如果可能,请移动:

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

JSONParseonPostExecute 结尾。这应该可以修复错误,因为它确保在运行另一个 AsyncTask 之前完成 JSONParse

提示

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

【讨论】:

  • 如果我理解你的帖子,我认为这是可能的,但这不是应用程序崩溃的原因。我移动了这部分代码,但应用程序仍然崩溃。 但是有一个 ProgressDialog 消失了,然后我点击了 Add Button,所以我认为应该首先完成 AsyncTask (JSONParse)。
猜你喜欢
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 2013-03-07
相关资源
最近更新 更多