mardi 5 mai 2015

How to save dynamic checkbox from database?

I'm having problem in saving the state for my dynamic checkbox. I'm also using Json and list adapter to take data from the database.

I know that savePreferences("CheckBox_Value", checkBox.isChecked()); is used for saving state for a single checkbox but due to my little knowledge in android programming, I'm really clueless on how to change it into a looping statement. If anyone can help me then it would be a big thanks since I'm stuck for 3 weeks already with this coding.

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://ift.tt/1bwElcm";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "list";
private static final String TAG_PID = "quantity";
private static final String TAG_NAME = "items";

// products JSONArray
JSONArray products = null;

Button simpan, padam;
EditText editText;
CheckBox checkBox;
ListView list;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    list = getListView();
    checkBox = (CheckBox)findViewById(R.id.checkBox);
    editText = (EditText) findViewById(R.id.EditText);
    simpan = (Button)findViewById(R.id.simpan);  
    simpan.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {
        // TODO Auto-generated method stub

          int cntChoice = list.getAdapter().getCount();

          for(int i = 0; i < cntChoice; i++) {
               savePreferences("CheckBox_Value" + i, checkBox.isChecked());
            }

        savePreferences("storedName", editText.getText().toString());
        Toast.makeText(AllDetails.this, "Data saved.",Toast.LENGTH_LONG).show();    
}});

    loadSavedPreferences();

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();


    // Loading products in Background Thread
    new LoadAllProducts().execute();

}

This is the loadSavePreferences functions:

 private void loadSavedPreferences() {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AllDetails.this);
    int count = list.getCount();

    for (int i = 0; i < count; i++) 
    {   
        boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value"+i, false);

    if (checkBoxValue) 
    {
        checkBox.setChecked(true);
    } 
    else 
    {
        checkBox.setChecked(false);
    }

    }

    String name = sharedPreferences.getString("storedName", "YourName");

        editText.setText(name);

    } 

This is the savePreferences for the Checkbox:

  private void savePreferences(String key, boolean value) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 
    Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);       
    editor.commit();
    }

This is the part to obtain data:

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllDetails.this);
        pDialog.setMessage("Loading Data. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    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);

                    // 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);

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

        return null;
    }

This is the onPostExecute function:

/**
     * 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(
                        AllDetails.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.quantity, R.id.items });

                // updating listview
                setListAdapter(adapter);

            }
        });     
     }

Aucun commentaire:

Enregistrer un commentaire