vendredi 27 avril 2018

Android: saving checkbox-state of ListView items into instances of custom object

My ultimate goal is to store an instance of the custom object "Place" for each item of the ListView in an SQLite table.

step 1 would be simply extracting the Place objects and I was able to get the various member variables of Place using an adapter but I have been trying for days to get the checked-state of each checkbox within the listview but cannot get it to work and it shouldn't be that difficult. I have tried every listener I can think of but it is not registering when I check a box. Finally, I do need the checked-state as an integer (1 or 0) rather than a boolean so I can save it to the database. Below I have posted the code for a tester app version I have been working on so I stop screwing up the real thing and I really would appreciate any help!

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:onClick="itemClicked"
    android:paddingRight="8dp"/>

<TextView
    android:id="@+id/place_nameandaddress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:minHeight="?android:listPreferredItemHeight"/>

</LinearLayout>


public class Place {

String mName;
String mAddress;
double mLatitude;
double mLongitude;
public int mCheckedStatus;

public Place(String name, String address, double latitude, double longitude, int integer){
    mName = name;
    mAddress = address;
    mLatitude = latitude;
    mLongitude = longitude;
    mCheckedStatus = integer;
}

public String getName() {
    return  mName;
}

public String getAddress() {
    return  mAddress;
}

public double getLatitude() {
    return  mLatitude;
}

public double getLongitude() {
    return  mLongitude;
}

public int getCheckedStatus(){ return mCheckedStatus;}

public void setCheckedStatus(int integer){
    mCheckedStatus = integer;
}

public boolean isSelected() {
    if (mCheckedStatus ==1) {
        return true;
    } else {
        return false;
    }
 }
}

public class PlaceAdapter extends ArrayAdapter<Place> {

public PlaceAdapter(@NonNull Context context, int resource, ArrayList<Place> places) {
    super(context, 0, places);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.place_item, parent, false);
    }

    Place currentPlace = getItem(position);

    TextView placeview = convertView.findViewById(R.id.place_nameandaddress);

// remove commas so can later use commas to separate items of the arraylist
    String name = currentPlace.getName().replace(",", "");
    String address = currentPlace.getAddress().replace(",", "");
    placeview.setText(name + " at " + address);


    double latitude = currentPlace.getLatitude();
    double longitude = currentPlace.getLongitude();
    Log.i("Debugging: Lat and Long", String.valueOf(longitude) + String.valueOf(latitude));

    CheckBox checkbox = convertView.findViewById(R.id.checkbox);
      if (currentPlace.isSelected()) {
          checkbox.setChecked(true);
      } else {
          checkbox.setChecked(false);
      }

        return convertView;

    }
}




public class MainActivity extends AppCompatActivity {

ListView listView;
Uri mIntentUri;
CheckBox checkBox;
int checkboxstatus;
Place currentplace;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<Place> places = new ArrayList<Place>();
    places.add(new Place("name1", "address1", 12.3, 23.3, 0));
    places.add(new Place("name2", "address2", 12.4, 23.4, 0));
    places.add(new Place("name3", "address3", 12.5, 23.5, 0));
    places.add(new Place("name4", "address4", 12.6, 23.6, 0));
    places.add(new Place("name5", "address5", 12.7, 23.7, 0));
    listView = findViewById(R.id.listview);
    PlaceAdapter placeAdapter = new PlaceAdapter(this, 0, places);
    listView.setAdapter(placeAdapter);
}

//get user input from editor and saves value entered into new or edited goal into database
    public void saveGoal() {

       PlaceAdapter allplacesAdapter = (PlaceAdapter) listView.getAdapter();

        ArrayList<String> places = new ArrayList<>();
        double latitude = 0;
        double longitude = 0;

        for ( int i=0; i < allplacesAdapter.getCount();i++) {
            currentplace = allplacesAdapter.getItem(i);
            String name = currentplace.getName().replace(",","");
            String address = currentplace.getAddress().replace(",","");

            View view =  LayoutInflater.from(this).inflate(R.layout.place_item, listView, false);
            checkBox = view.findViewById(R.id.checkbox);
            if (checkBox.isChecked()){
                currentplace.setCheckedStatus(1);
            }
                else {
                currentplace.setCheckedStatus(0);
            }

            checkboxstatus = currentplace.getCheckedStatus();                
            latitude = currentplace.getLatitude();
            longitude = currentplace.getLongitude();
            String placeString = name + "," + address + "," + latitude + "," + longitude + "," + checkboxstatus;
            Log.i("Debugging: placeString",placeString);
            places.add(placeString);
        }
        String arrayString = android.text.TextUtils.join(";", places);
        Log.i("Debugging: arrayString",arrayString);

        if (TextUtils.isEmpty(arrayString)) {
            return;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(GoalContract.GoalEntry.COLUMN_PLACE, arrayString);
        Log.i("Debugging:contentValues", contentValues.toString());

        // informs user of whether values entered into the GoalEditor were saved or there was an error
        //if (mIntentUri == null) {
            Uri newUri = getContentResolver().insert(GoalContract.GoalEntry.FINAL_CONTENT_URI, contentValues);
            if (newUri == null) {
                Toast.makeText(this, "Error with saving goal", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Goal successfully saved", Toast.LENGTH_LONG).show();
            }
    }

// sets options menu if GoalEditor screen
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_goaleditor, menu);
    return true;
}

// determines what should happen if the different menu options in the GoalEditor screen are selected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_save:
            saveGoal();
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
  }
}




Aucun commentaire:

Enregistrer un commentaire