Passing the contents of the selected row to another activity - android

Can anyone advise me on how to pass the values of the selected row in a custom viewList to another activity in android. What i mean is that i have a custom ListView which has 2 textView and a checkbox. When the user checks a checkbox and hits the submit button i want to store the values of the 2 textView fields and pass it along to the next activity. Passing to the activity is not the problem. The problem is i cant figure out how to store the values of the checked row.
The code is pasted below.
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class contacts extends Activity implements OnItemClickListener {
static final String TAG = "contacts";
ArrayList<String> contactName = new ArrayList<String>();
ArrayList<String> contactNumber = new ArrayList<String>();
ArrayList<String> checkboxArray = new ArrayList<String>();
MyAdapter myAdapter;
Button AddNumber;
String numberIntent;
View vi;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
getAllContacts(this.getContentResolver());
listView = (ListView) findViewById(R.id.lists);
myAdapter = new MyAdapter();
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(this);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
// adding
AddNumber = (Button) findViewById(R.id.AddNumbers);
AddNumber.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedContacts = new StringBuilder();
Log.d(TAG, "onClick" + myAdapter.mCheckStates.size());
for (int i = 0; i < contactName.size(); i++)
{
if (myAdapter.mCheckStates.get(i) == true) {
checkedContacts.append(contactName.get(i).toString());
checkedContacts.append("\n");
} else {
Log.d(TAG, "No OnClick" + contactName.get(i).toString());
}
}
Toast.makeText(contacts.this, checkedContacts,
Toast.LENGTH_LONG).show();
SparseBooleanArray checked = listView.getCheckedItemPositions();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
myAdapter.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC");
while (cursor.moveToNext()) {
String name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(TAG, "getAllContacts" + phoneNumber);
contactName.add(name);
contactNumber.add(phoneNumber);
}
cursor.close();
Intent in = new Intent(this, TrackLogic.class);
in.putExtra("contact", contactName.toArray());
in.putExtra("contact1", contactNumber.toArray());
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView phoneView, contactView;
CheckBox checkBox;
MyAdapter() {
mCheckStates = new SparseBooleanArray(contactName.size());
mInflater = (LayoutInflater) contacts.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return contactName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
contactView = (TextView) vi.findViewById(R.id.contact_name);
phoneView = (TextView) vi.findViewById(R.id.phone_number);
checkBox = (CheckBox) vi.findViewById(R.id.checkBox_id);
contactView.setText(contactName.get(position));
phoneView.setText(contactNumber.get(position));
checkBox.setTag(position);
checkBox.setChecked(mCheckStates.get(position, false));
checkBox.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
Log.d(TAG, "setChecked");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
Any help will be greatly appreciated.. Thanks!

If you are going to use shared prefs (probably a good idea) - something along these lines might be what you are looking for:
//in caller activity (save shared prefs value) ...
String phone = phoneView.getText().toString();
private SharedPreferences prefs;
prefs = getSharedPreferences("yourPrefName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("phone", phone);
editor.commit();
//in called activity ...
private SharedPreferences prefs;
prefs = getSharedPreferences("yourPrefName", Context.MODE_PRIVATE);
String phone=prefs.getString("phone", null); //will be null if "phone" not found
Hope this helps ...

There's a few different options that Android provides for storing persistent data. They are documented in the following link: http://developer.android.com/guide/topics/data/data-storage.html
You may want to start with a basic SharedPreferences implementation and go from there.

Related

Why my listview not refresh when I press back button and come back to activity?

I'm tired already with my code. I'm writing chat application. My app consist of two activity. First activity has a listview of wich each row contain a last message which was send for the user while a second activity contain the whole conversation. In my app I used socket.io for android. My app works fine. Listview is refresh when a data is receive but when I press back button and then come back to the activity a listview not refresh itself already. In logs console I see that a data has received and "changed" method is called but listview is not refresh. What is wrong in belows code?
package com.example.seadog.fb_dialog;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import java.util.ArrayList;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends Activity {
public static ArrayList arrayList = new ArrayList();
public ListView listView;
public MyBaseAdapter adapter;
public TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Get Socket.io Object
*/
SocketIO socketIo = new SocketIO();
Socket mSocket = socketIo.getSocket(); // get socket
Integer id = socketIo.getId(); // get Website ID
if(mSocket == null) {
socketIo.Connection();
mSocket = socketIo.getSocket();
mSocket.on("message", new Emitter.Listener() {
/*
* Message Listener
*/
#Override
public void call(Object... args) {
Boolean isset = false;
try {
JSONObject object = (JSONObject) args[0];
String _id = object.getString("_id");
String message = object.getString("message");
JSONObject obj = new JSONObject();
obj.put("direction", "fb-lt");
obj.put("message", message);
obj.put("date", "2017-05-29T12:15:49.245Z");
for(int i = 0; i < arrayList.size(); i++){
ListData ld = (ListData) arrayList.get(i);
String id = ld.getId();
if(_id.equals(id)){
JSONArray Data = ld.getData();
Data.put(obj);
ld.setDescription(message);
arrayList.set(i, ld);
isset = true;
Log.d("LOG", message);
}
}
if(!isset) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
ListData ld = new ListData();
ld.set_id(_id);
ld.setID(1);
ld.setTitle("Klient:");
ld.setDescription(message);
ld.setData(jsonArray);
arrayList.add(ld);
}
} catch (JSONException e) {
e.printStackTrace();
}
changed();
}
});
}
/*
* Populate a listview
*/
listView = (ListView) findViewById(R.id.listView);
adapter = new MyBaseAdapter(this, arrayList);
listView.setAdapter(adapter);
/*
* OnItemClickListener
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Conversation.class);
intent.putExtra("item", position);
startActivity(intent);
TextView textView = (TextView) view.findViewById(R.id.descitem);
textView.setTypeface(null, Typeface.NORMAL);
}
});
textView = (TextView) findViewById(R.id.count);
}
private void changed() {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
Log.d("LOG:", "adapter refresh");
}
});
}
}
MyBaseAdapter Class:
package com.example.seadog.fb_dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
Context context;
ArrayList<ListData> items = new ArrayList();
LayoutInflater inflater;
int id = 0;
public MyBaseAdapter(Context context, ArrayList items) {
this.context = context;
this.items = items;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListData getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
id = position > 0 ? getItem(position - 1).getID() : 0;
mViewHolder.Title.setText(currentListData.getTitle());
mViewHolder.Desc.setText(currentListData.getDescription());
if(1==1){
mViewHolder.Title.setVisibility(View.GONE);
}else {
if (id != currentListData.getID()) {
mViewHolder.Title.setVisibility(View.VISIBLE);
} else {
mViewHolder.Title.setVisibility(View.GONE);
}
}
return convertView;
}
private class MyViewHolder {
TextView Title, Desc;
public MyViewHolder(View item) {
Title = (TextView) item.findViewById(R.id.txtitem);
Desc = (TextView) item.findViewById(R.id.descitem);
Typeface title = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Title.setTypeface(title);
Typeface desc = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Desc.setTypeface(desc, Typeface.BOLD);
}
}
}
#Override
protected void onRestart() {
Intent intentBack = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentBack);
super.onRestart();
}
you did not have any callback after you back to this activity .
You can either override onResume() method or startActivityForResult and do something in the onAcitvityForResult method.

How to set alert dialog box in customize listview item by click long press

I want to set songs as a ringtone or alarm tone or message tone etc in list view by long pressing the list item. I want to show an dialog box which perform these action. How to show a dialog box by long pressing a list item and set action in dialog box? Please help me...
com.example.ring;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class Naat extends Activity implements
OnItemClickListener {
private ListView listView;
public static MediaPlayer mp;
Button bt;
PopAdapter adapter;
ArrayList<String> dataItems = new ArrayList<String>();
public static int[] rings = {R.raw.arabicmusic, R.raw.arabicmusic1, R.raw.arabicmusic12,
R.raw.arabicmusic13, R.raw.arabicmusic14, R.raw.arabicmusic15,
R.raw.arabicmusic18, R.raw.arabicmusic16, R.raw.arabicmusic17};
public static int imgadrss = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_naat);
String[] dataArray = getResources().getStringArray(R.array.listdata);
List<String> dataTemp = Arrays.asList(dataArray);
dataItems.addAll(dataTemp);
listView = (ListView) findViewById(R.id.listnaat);
// bt = (Button) findViewById(R.id.button1);
adapter = new PopAdapter(Naat.this, dataItems);
// adapter.setCustomButtonListner(MainActivity.this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
// #Override
// public void onButtonClickListner(int position, String value) {
// mp.create(this, rings[position]);
// mp.start();
//
// Toast.makeText(MainActivity.this, "Button click " + value,
// Toast.LENGTH_SHORT).show();
//
// }
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "" + position, 2000).show();
imgadrss = rings[position];
}
}
Adapter class
com.example.ring;
import java.util.ArrayList;
import android.content.Context;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class NaatAdapter extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position, String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public NaatAdapter(Context context, ArrayList<String> dataItem) {
super(context, R.layout.singlerow, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.singlerow, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView
.findViewById(R.id.textView1);
viewHolder.button = (Button) convertView.findViewById(R.id.button1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position, temp);
}
// MainActivity.mp.create(context, MainActivity.imgadrss);
// MainActivity.mp.start();
MediaPlayer mp = MediaPlayer.create(context, Naat.rings[position]);
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
}
} else {
if (mp != null) {
mp.start();
}
}
// mp.stop();
Toast.makeText(context, "" + position, 2000).show();
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}
You can use this
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
// TODO Auto-generated method stub
Log.d("in onLongClick");
//Open alert dialog here
return true;
}
});

Issue with set the already checked to load and after again update

I am facing the problem to view the checked item of the listview and after if user want to modify the checked item to other item then he can modify check-box. After modify he again want to view what i checked in list. My code not working correct to view what he checked. Please help and it much appreciate
Here is my adapter class:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.kns.model.CategoryModel;
import com.sunil.selectmutiple.R;
public class CategoryAdapter extends BaseAdapter{
private final List<CategoryModel> list;
private final Activity context;
private LayoutInflater mInflater=null;
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
private static final String TAG="CategoryAdapter";
String catid1;
String catid2;
String catid3;
public CategoryAdapter(Activity context, List<CategoryModel> list, String catid1, String catid2, String catid3) {
// super(context, R.layout.listcheck, list);
mInflater = context.getLayoutInflater();
this.context = context;
this.list = list;
this.catid1=catid1;
this.catid2=catid2;
this.catid3=catid3;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = mInflater.inflate(R.layout.cate_list_item, parent, false);
}
CategoryModel p = getProduct(position);
TextView text = (TextView) view.findViewById(R.id.textView_custname);
CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkBox1);
checkbox.setOnCheckedChangeListener(myCheckChangList);
checkbox.setTag(position);
String catid=p.getCat_id();
Log.v(TAG, "Cat id is: "+catid);
Log.v(TAG, "Cat id1 is: "+catid1);
Log.v(TAG, "Cat id2 is: "+catid2);
Log.v(TAG, "Cat id3 is: "+catid3);
if (catid1.trim().equalsIgnoreCase("0") && catid2.trim().equalsIgnoreCase("0") && catid3.trim().equalsIgnoreCase("0")) {
checkbox.setChecked(p.isIsselected());
}
else{
if (catid.trim().equalsIgnoreCase(catid1)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid2)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid3)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else{
checkbox.setChecked(false);
}
}
text.setText(p.getCat_name());
// checkbox.setChecked(p.isIsselected());
return view;
}
CategoryModel getProduct(int position) {
return ((CategoryModel) getItem(position));
}
public ArrayList<CategoryModel> getChecked() {
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
for (CategoryModel details : list) {
if (details.isIsselected())
list1.add(details);
}
return list1;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ArrayList<CategoryModel> list1=getChecked();
Log.v(TAG, "checked size is: "+list1.size());
if (isChecked) {
if (list1.size() >= 3) {
buttonView.setChecked(false);
//getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
Toast.makeText(context, "Please select max 3 Categories.", Toast.LENGTH_LONG).show();
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
};
}

Android 4.4.2: Using Listview with combobox inside Fragment

I have a list view inside a fragment like this:
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);
}
}
}
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.

How do i pass the value of my username and its id to the next activity?

I want to be able to click on the "username" which will lead me to a new class - SetMed.java. Along with the username, i would like it's ID's to be passed on as well. I have tried using Intent but it does not work. Any help is greatly appreciated.
This is my MainActivity.java
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ListView_CheckBoxActivity extends Activity {
//Adapter
CheckboxAdapter listItemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Buttons and incident response
Button getValue=(Button)findViewById(R.id.get_value);
getValue.setOnClickListener(listener);
//listview
ListView list = (ListView) findViewById(R.id.list);
//Array list to store the data
ArrayList<HashMap<String, Object>> listData=new ArrayList<HashMap<String,Object>>();
String []name={"Diabetes","example","example","example","example"};
String []id={"Insulin, Glucagon, Prandin","example","example","example","example"};
for(int i=0;i<5;i++)
{
HashMap<String, Object>
map=new HashMap<String, Object>();
map.put("friend_image", R.drawable.icon);
map.put("friend_username", name[i]);
map.put("friend_id", id[i]);
map.put("selected", false);
//Add data
listData.add(map);
}
//Adapter
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
}
//Incident Response
OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(ListView_CheckBoxActivity.this, SetMed.class);
boolean[] array = new boolean[5];
array[0] = CheckboxAdapter.isChecked();
intent.putExtra("status", array);
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="Medicine Selected:";
for(int j=0; j<listItemAdapter.getCount(); j++)
{
System.out.println("state.get("+j+")=="+state.get(j));
if(state.get(j)!=null)
{
#SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
options+="\n"+username;
}
}
//Display selection
startActivity(intent)
}
};
}
This is my CheckBoxAdapter class.
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
public class CheckboxAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> listData;
//Record checkbox state
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
// Constructor
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData)
{
this.context = context;
this.listData = listData;
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
// Rewrite View
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
TextView id = (TextView) convertView.findViewById(R.id.friend_id);
id.setText((String) listData.get(position).get("friend_id"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
state.put(position, isChecked);
} else
{
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
public static boolean isChecked() {
// TODO Auto-generated method stub
return false;
}
Class SetMed
public class SetMed extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_set_med);
TextView diabetes = (TextView) findViewById(R.id.diabetes);
Bundle bundle = this.getIntent().getExtras();
if (bundle.getBoolean("Diabetes", false)) {
diabetes.setText("Diabetes");
} else {
diabetes.setText("");
}
}
}

Categories

Resources