2

I am trying make app, where I am getting data from Mysql and populating list. I am using AsyncTask class and it works. I have there "Add" button which invoke AlertDialog where user can add new word to list. So I want use second AsyncTask class which will be executed when user click on "Add" button in AlertDialog. But this way doesn't work.

Getting AsyncTask work, but the second Post AsyncTask doesn't work and app crash when I click on "Add" button in AlertDialog.

When I try call only Getting AsyncTask (two times - on the start Activity and in the AlertDialog) app works.

When I call first Post AsyncTask it works and data are sent to mysql.

And When I call first executing of Post AsyncTask and then Getting (JSONParse) AsyncTask then app works too. App doesn't work only if JSONParse AsyncTask is executed before Post AsyncTask and Post AsyncTask is executed from AlertDialog.

Here is my 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();

        } 
}
    }

My Logcat output

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

And just for completeness my 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>

I will be very glad for any help.

I think I found problem. It should be this part of code

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

There was NullPointerException, when I replace title.getText().toString() for "something" AsyncTask Post works.


SOLVED

I add addView before findViewById and it works now. I totally don't understand why it is, if here is anybody who understandy it better he could explain it. I will be try found explanation on google

So the part of this code looks like this:

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();
    }
Bulva
  • 1,208
  • 14
  • 28
  • follow this answer it will give some ideas about your question http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-possible –  Nov 14 '14 at 12:48
  • I don't want parallel execution, I want execute one AsyncTask which ends and then on click make second AsyncTask. – Bulva Nov 14 '14 at 13:07

1 Answers1

0

Is it possible to make user only add items when JSONParse is finished? (so user will not be able to click the add button before it finished)

If its possible, move :

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

To the end of JSONParse's onPostExecute. This should fix the bug because it make sure JSONParse is finished before running another AsyncTask

Tips

You can use something like progress bar to show loading screen when JSONParse is still working, and hide the progress bar when JSONParse finished (inside onPostExecute)

Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
  • If I understand good your post, I think it is possible but it is not the reason why app crash. I moved this part of code but the app is still crashing. **But** there is a ProgressDialog which disappeared and then I click on Add Button, so I think first AsyncTask (JSONParse) should be done. – Bulva Nov 14 '14 at 13:06