0

I have a list view inside a fragment like this: enter image description here

The contacts section shows the user contacts and the groups section shows user groups. both of them are using fragments. I have been able to implement the custom listview for them. Code for contactadaptor used to populate the listview in contact section is given below:

package com.project.iandwe.Adaptor;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.project.iandwe.Data.ContactData;
import com.project.iandwe.R;

import java.util.ArrayList;

/**
 * Created by NathanDrake on 6/4/2014.
 */

public class ContactSelectAdaptor extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {

    ArrayList<ContactData> listViewRows;
    Context context;
    public SparseBooleanArray checkboxState;

 public ContactSelectAdaptor(Context context){

        //Resources resources = context.getResources();
        this.context =context;
        UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(context);
        Cursor cursor = userDatabaseAdapter.getUserContacts();
        listViewRows = new ArrayList<ContactData>();
        checkboxState = new SparseBooleanArray();
        while (cursor.moveToNext()){
         //   ContactData listViewRow = new ListViewRow();
             String contact_id = cursor.getString(0);
            String first_name = cursor.getString(1);
          String last_name = cursor.getString(2);
            String email = cursor.getString(3);
           String icon = cursor.getString(4);

          //  Log.d("ContactSelectAdaptor"," " + contact_id + " " + first_name + " " + last_name+ " " + email);

            if (last_name == null){
                last_name = " ";
            }

            listViewRows.add(new ContactData(contact_id,first_name,last_name,email,icon));
        }
        cursor.close();
    }

    @Override
    public int getCount() {
        return listViewRows.size();
    }

    @Override
    public Object getItem(int position) {
        return listViewRows.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

         View row = convertView;
         ViewClass viewClass = null;

        if (row==null) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.listview_contact_select, parent, false);
            viewClass = new ViewClass(row);
            row.setTag(viewClass);
        }

        else {

            viewClass = (ViewClass) row.getTag();
        }
       /* ImageView imageView = (ImageView) view.findViewById(R.id.imageViewProfile);
        TextView textViewName = (TextView) view.findViewById(R.id.textViewDisplayName);
        TextView textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress);
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected);
        */
        ContactData contactData = listViewRows.get(position);

        Uri uri = contactData.getIcon();
        if (uri!=null){ viewClass.imageView.setImageURI(uri); }
        else { viewClass.imageView.setImageResource(R.drawable.ic_contacts); }

        viewClass.textViewName.setText(contactData.getFirst_name());
        viewClass.textViewEmail.setText(contactData.getEmail());
        viewClass.checkBox.setTag(position);
        viewClass.checkBox.setChecked(checkboxState.get(position,false));
        viewClass.checkBox.setOnCheckedChangeListener(this);

        return row;
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        checkboxState.put((Integer) buttonView.getTag(), isChecked);
    }

    class ViewClass {
        ImageView imageView;
        TextView textViewName;
        TextView textViewEmail;
        CheckBox checkBox;

        ViewClass (View view){

            imageView = (ImageView) view.findViewById(R.id.imageViewProfile);
             textViewName = (TextView) view.findViewById(R.id.textViewDisplayName);
            textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress);
             checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected);

        }
    }
}

This is how i try to pick up the contacts that have been selected by the user:

package com.project.iandwe.Menu;


import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.project.iandwe.Adaptor.ContactSelectAdaptor;
import com.project.iandwe.Adaptor.UserDatabaseAdapter;
import com.project.iandwe.R;

import java.util.ArrayList;

/**
 * Created by NathanDrake on 5/4/2014.
 */
public class ContactsFragments extends Fragment {

    TextView textView;
    ListView listView;
    String eventId;

    public ContactsFragments(){}

    public ContactsFragments (String eventID){
        this.eventId=eventID;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
      return   inflater.inflate(R.layout.fragment_contact,container, false );
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(getActivity());
        //textView = (TextView) getActivity().findViewById(R.id.textViewSample);
       // textView.setText(userDatabaseAdapter.getUserContacts());
        listView = (ListView) getActivity().findViewById(R.id.listViewContacts);
        ContactSelectAdaptor contactSelectAdaptor = new ContactSelectAdaptor(getActivity());
        listView.setAdapter(contactSelectAdaptor);
        listView.setVisibility(View.VISIBLE);

        /* Checking who all customers have been invited to the events
        * http://stackoverflow.com/questions/18162931/get-selected-item-using-checkbox-in-listview */
        Cursor cursor = userDatabaseAdapter.getUserContacts();
        cursor.moveToFirst();

        for (int i=0; i<contactSelectAdaptor.checkboxState.size();i++){

            if (contactSelectAdaptor.checkboxState.get(i)==true){
                String contact_id = cursor.getString(0);
                String first_name = cursor.getString(1);
                String last_name = cursor.getString(2);
                String email = cursor.getString(3);
                //String icon = cursor.getString(4);
               long id = userDatabaseAdapter.insertUserInvite(eventId,contact_id,email,first_name,last_name,0,0,0,0);
               if (id<0){
                   Log.e("UserEventContactInsert","Failure");
               }
            }

            cursor.moveToNext();
        }

        cursor.close();

    }


}

AS i am new to android, i am not sure if the above code to check for user selection of checkboxes should be done in which section of the fragment? I would actually like to populate this data if the user has selected the Done menu presented on the top right corner but then i am finding it difficult to spend the sparse boolean array from fragment to activity. Is there a way this can be accomplished?

Adding code for the main activity which has the "Done" menu button:

package com.project.iandwe;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.project.iandwe.Adaptor.FragmentContactAdaptor;
import com.project.iandwe.Adaptor.UserDatabaseAdapter;

/**
 * Created by NathanDrake on 5/21/2014.
 */
public class AddContacts extends FragmentActivity {

    ViewPager viewPager = null;
    String name;
    String eventId,description,date, time, location;

    protected void  onCreate( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_contacts);
        viewPager = (ViewPager) findViewById(R.id.pager_contacts);

        FragmentManager fragmentManager = getSupportFragmentManager();
        viewPager.setAdapter(new FragmentContactAdaptor(fragmentManager));
        //viewPager.setCurrentItem(1);
        Intent intent = getIntent();
        eventId = intent.getExtras().getString("eventId");
        name = intent.getExtras().getString("name");
        description = intent.getExtras().getString("description");
        date = intent.getExtras().getString("date");
        time = intent.getExtras().getString("time");
        location = intent.getExtras().getString("location");


    }

    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.add_event_finish,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_finish:
                //UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(this);
                //long id =   userDatabaseAdapter.insertUserEvent(name,description,date,time,location);
                 //if (id>0 ) {
                 Toast.makeText(this,"Event successfully Created",Toast.LENGTH_LONG).show();
                 Intent intent = new Intent(this, HomePage.class);
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                 startActivity(intent);
                 finish();
                // }
                return true;
            default:
            return super.onOptionsItemSelected(item);
        }
    }
}
nathandrake
  • 427
  • 1
  • 4
  • 19
  • please anyone provide some input.. any input.. i am just struck at this one and can't figure out how to go about it – nathandrake Jun 21 '14 at 12:31
  • `above code to check for user selection of checkboxes` ? Well i don't see that code. Could you explain better what is happening please? First you set up the listbox with the adapter. Do you have difficulties with that? After that the user can check some boxes. Then at last you want to know wich boxes are checked. Now where do you need help? – greenapps Jun 21 '14 at 22:47
  • when a user picks an option in checkbox, i populate the sparse boolean array which i then plan to use by using the for loop to match each with contact as given in the for loop inside the onactivitycreated function of the fragment.. since this function runs on activity, i am thinking at that time sparse boolean array would be empty.. so i need to place this code inside another function.. since the next function can be onclick of the activitysub menu but then i will have to deal with moving sparse array from fragment to activity which i m not sure how to go about doing that – nathandrake Jun 22 '14 at 17:56
  • Like this: ???? I don't understand what you are saying. And you are not reacting/confirming what i thought was happening. If you want help you better have to explain. – greenapps Jun 22 '14 at 18:02
  • firstly i setup the listbox using the adaptor so i get all the contacts along with an image, email address and a combobox which is what i expected. then user is actually able to check the boxes as the check boxes are clickable and i store these values in sparse array based on state change in check boxes.. but how to get which check boxes have been checked when user clicks the "done" menu on the activity is creating problem – nathandrake Jun 22 '14 at 18:09
  • Ok. That is clear now. Remove `public SparseBooleanArray checkboxState;` from the adapter class and put it in your fragment class. In this way it is easy reacheble by de code for the done menu. Please add the code for the done menu handler also. After that we continue. – greenapps Jun 22 '14 at 18:18
  • how do i reach the done menu inside the activity from the fragment itself? – nathandrake Jun 22 '14 at 19:06
  • Think that the situation is different: how from the done menu handler do i reach `checkboxState`? Where is your menu handler code now? In a activity or that fragment? You have a piece of menu code already i suppose. You will have more menu items. So post that code. Be it in an activity or that fragment. – greenapps Jun 22 '14 at 21:15
  • added the code for the main activity which has the menu button "done" code.. i hope that helps in resolving this one – nathandrake Jun 22 '14 at 22:26
  • Step by step... Now i do not see a R.id.done menu in it. Why did you omit it? Please put it already in. Or did you? Then why don't i see it? – greenapps Jun 22 '14 at 22:58
  • For viewPager you have set as adapter an instance of your FragmentContactAdapter. viewPager is reachable from that menu code and so your adapter and hence your checkboxState. Well if you put it in again. Sorry. Sorry again... This is about the listview. Have to think about it. Tomorrow there is another day... – greenapps Jun 22 '14 at 23:10
  • `This is how i try to pick up the contacts that have been selected by the user:`Well you have some code in onActivityCreated wich is what I suppose you are referring to (with cursor and contactSelectAdaptor in a loop). If that is true then it is clearly the wrong place as in onActivityCreated the user has not yet done anything. If this is your code you want to execute in the done menu then take it out and purt it in the done menu. Adapt your code here please. Further you have two adapters that's the reason I made a mistake yesterday. – greenapps Jun 23 '14 at 07:11
  • Your story about what is all happening is not complete. What is missing is the connection between your `FragmentActivity` and The `Fragment` with the `listview`. You have at least two fragments so tell a complete story. Think you have to show here `fragment_contact.xml` too. Which is the first fragment that displays? – greenapps Jun 23 '14 at 07:15

1 Answers1

1

In the menu done handler try to get your adapter in this way:

ContactsFragments fragment = (ContactsFragments) getSupportFragmentManager()
                    .findFragmentByTag("ContactsFragments");

ListView listView = fragment.listView;

ContactSelectAdaptor adapter = (ContactSelectAdaptor)listView.getAdaptor();

If you have the adaptor then your sparseb boolean array is visible.

greenapps
  • 11,154
  • 2
  • 16
  • 19