-1

I am trying to get the background to change on click after 500 ms. All it does right now is go black. It doesn't even show the view just a black screen. The list of colors comes from a database, the JSON data is parsed for the color value. I am using Android 6 API 23.

public class CycleColors extends AppCompatActivity {

    private static final String TAG     =  CycleColors.class.getName();

    static List<String> colorsList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cycle_colors);

        Button doneBtn  = (Button)findViewById(R.id.btnDone);

        doneBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clickDoneButton();
            }
        });

        getData();
        Intent intent   = getIntent();
        new cycle(this).execute();

    }

    public void clickDoneButton()
    {
        finish();
    }

    class cycle extends AsyncTask<Void, Void, Void>
    {
        private Activity    activity;
        View                view;

        public cycle(Activity a)
        {
            activity    = a;
            view        = activity.getWindow().getDecorView();
        }

        protected Void doInBackground(Void... param)
        {
            activity.runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    while(true)
                    {
                        for (String c: colorsList)
                        {
                            int color   = Color.parseColor(c);
                            Log.d(TAG, color+"");
                            view.setBackgroundColor(color);
                            SystemClock.sleep(500);
                        }
                    }
                }
            });
            Log.d(TAG, "returned null");
            return null;
        }
    }



    private void getData() {

        final String            serverURL;
        final JsonArrayRequest  request;
        final RequestQueue      queue;

        serverURL   = "https://api.mlab.com/api/1/databases/comp3717final/collections/colours?apiKey=qR2ag5UaRrHBxDm6KEyg95EESmfY5Bcf";
        queue       = Volley.newRequestQueue(this);
        request     = new JsonArrayRequest(serverURL,
                new onJSONResponse(),
                new onJSONError());
        queue.add(request);
    }

    private class onJSONResponse implements Response.Listener<JSONArray>
    {
        @Override
        public void onResponse(JSONArray response)
        {
            final int length;
            int i;
            i = 0;
            length = response.length();

            try {
                for (; i < length; i++) {
                    final JSONObject colorObject;
                    final JSONObject hexObject;
                    final String colorName;
                    final String hexCode;

                    colorObject = response.getJSONObject(i);
                    colorName = colorObject.getString("color");
                    hexCode = colorObject.getString("value");
                    Log.d(TAG, colorName + " => " + hexCode);
                    colorsList.add(colorName);
                }
            } catch (final JSONException ex) {
                Log.d(TAG, "Error getting json object: " + i, ex);
                colorsList.clear();
            }
            Log.d(TAG, "working");
        }
    }

    private static class onJSONError implements Response.ErrorListener
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            Log.d(TAG, "JSON ERROR");
        }
    }
}

The layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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: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.peymantp.androidfinal.CycleActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Done"
        android:id="@+id/button6"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="32dp" />
</RelativeLayout>
noname
  • 305
  • 4
  • 15
  • You don't need an `AsyncTask` to change the background color and your `while(true)` is an infinite loop. If you want to delay some code I'd recommend `Handler.postDelayed` http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android – Sammy T Dec 05 '16 at 04:59
  • I tried what you linked to. I had to add `Looper.prepare()` otherwise the app would crash. Unlike before I can see the view now but it still doesnt cycle through colors. Heres the updated code. `Looper.prepare(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { for (String c : colorsList) { int color = Color.parseColor(c); Log.d(TAG, color + ""); view.setBackgroundColor(color); } } }, 100);` – noname Dec 05 '16 at 05:42

1 Answers1

0

getData which has network calls and AsyncTask execution happening simultaneously, which may cause colorList initialization after asyncTask is done. You need to call getData in synchronized way before AsysncTask access colorList.

Vinodh
  • 1,069
  • 2
  • 10
  • 22
  • How would I do it in a synchronized way? Can you give an example? – noname Dec 05 '16 at 05:22
  • In a simple way, take one boolean variable set it to true when you have done adding items in colorList in onResponse callback. And in doInBackgroiund, indefinitely check for boolean variable. – Vinodh Dec 05 '16 at 05:28