0

I am trying to follow an Android tutorial to modify a MySQL database data from Android app. I am fairly new to the concept of JSON parsing and I am stuck at setting the values of toggles in my app's list-view according to the 'status' values received from database through JSON. In my database, I have a field named 'status' in table 'devices', and a ToggleButton is associated with each row received through JSON. I want to use the retrieved values (0 or 1) to set my associated toggle in the app to ON if the value is 1 and to OFF if the retrieved value is 0. But I don't know how I can achieve that.

Here's the doInBackground function from the activity that shows my list-view:

protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String status = c.getString(TAG_STATUS);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_STATUS, status);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewDeviceActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllDevicesActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_STATUS},
                        new int[] { R.id.pid, R.id.name, R.id.status });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

The XML file is:

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

    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
    <TextView
        android:id="@+id/pid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <TextView
        android:id="@+id/status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="7dip"
        android:textSize="17dip"
        android:textStyle="bold" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="7dp"
        android:text="ToggleButton" />

</RelativeLayout>

The values (name, ID and status) are received just fine, I have reached thus far: Screenshot of the app after execution of above code.

But I have no idea how to use the received 'status' value to change toggle associated with every list-view item. I tried to define the ToggleButton in the onCreate method like this:

tb = (ToggleButton) findViewById(R.id.toggleButton1);

And then tried this in the for loop of doInBackground method above:

if (status == "1")
{
     tb.setChecked(true);           
}

But the app crashes if I do that may be because I have not idea where to put the associated code. Any help regarding this is appreciated.

Thank you!

Uzair A.
  • 1,586
  • 2
  • 14
  • 30
  • 1
    "the app crashes" -> LOGCAT – 2Dee Sep 05 '14 at 12:51
  • @2Dee: From what I see, I doubt LOGCAT would be of any help because I am unable to understand how to use the incoming data in the first place. Putting the above-mentioned snippet in the doInBackground method (which causes the crash) was only a trial on my part. If anyone would be so kind to just look at the code and guide me in the direction of how to use the incoming 'status' values to modify 'ToggleButton' state, I could take it from there. – Uzair A. Sep 06 '14 at 05:44
  • 1
    First, you could have a look at http://stackoverflow.com/questions/4369537/update-ui-from-thread to understand the basics of AsyncTask (e.g. now, you're using a Runnable in onPostExecute, that's useless). Then find a good tutorial on custom Adapters so you learn how to manipulate views inside a listview. That should get you going ;) – 2Dee Sep 06 '14 at 10:35

1 Answers1

1

i used editText to retrieve value from JSON then convert it into toggle button

try this in your onPostExecute()

protected void onPostExecute(Void result) {
        try {
            EditText1.setText(json.getString("your_param"));
            EditText1.setVisibility(View.INVISIBLE);


            if (EditText1.getText().toString().equalsIgnoreCase("1")) {

                toggleButton1.setChecked(true);
            } else if (EditText1.getText().toString().equalsIgnoreCase("0")) {

                toggleButton1.setChecked(false);

            }
    }
Ian
  • 38
  • 4