我可以在一个活动中有两个AsyncTask类(不能同时工作)

时间:2014-11-14 12:37:42

标签: android mysql android-asynctask

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

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

当我尝试只调用Getting AsyncTask(两次 - 在启动Activity和AlertDialog中)app工作。

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

当我第一次执行Post AsyncTask然后调用Getting(JSONParse)AsyncTask时,app也可以运行。只有在从AlertDialog执行Post AsyncTask和Post AsyncTask之前执行JSONParse AsyncTask时,App才会起作用。

这是我的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()替换为“some”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();
    }

1 个答案:

答案 0 :(得分:0)

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

如果可能,请移动:

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

JSONParse的{​​{1}}结尾。这应该可以修复错误,因为它确保在运行另一个onPostExecute

之前完成了JSONParse

<强>提示

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