Android 4.4.2: Using Listview with combobox inside Fragment - android

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.

Related

Listview to display only one item clicked not all of the list

Here is my code of the populated listview adapter that I have
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class ListViewAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView companyName = (TextView) convertView.findViewById(R.id.companyName);
Contact m = DataList.get(position);
name.setText(m.getName());
companyName.setText(String.valueOf(m.getCompanyName()));
return convertView;
}
}
And here is my main
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new ListViewAdapter(this, l);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, ContactDetail.class);
startActivity(i);
}
});
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
}
this code works properly and populates my listview, however, when I click on an item in the listview I have another listview populating that displays all contact items...I just want ONE contact item to display.
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ListViewContactAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewContactAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.contactlistinfo, null);
ImageView i = (ImageView) convertView.findViewById(R.id.imageView2);
TextView tv2 = (TextView) convertView.findViewById(R.id.textView2);
TextView tv4 = (TextView) convertView.findViewById(R.id.textView4);
TextView tv6 = (TextView) convertView.findViewById(R.id.textView6);
TextView tv8 = (TextView) convertView.findViewById(R.id.textView8);
TextView tv17 = (TextView) convertView.findViewById(R.id.textView17);
TextView tv18 = (TextView) convertView.findViewById(R.id.textView18);
TextView tv19 = (TextView) convertView.findViewById(R.id.textView19);
TextView tv20 = (TextView) convertView.findViewById(R.id.textView20);
TextView tv10 = (TextView) convertView.findViewById(R.id.textView10);
TextView tv12 = (TextView) convertView.findViewById(R.id.textView12);
TextView tv14 = (TextView) convertView.findViewById(R.id.textView14);
TextView tv16 = (TextView) convertView.findViewById(R.id.textView16);
Contact m = DataList.get(position);
tv2.setText(m.getName());
tv4.setText(m.getCompanyName());
tv6.setText(m.getHome());
tv12.setText(m.getMobile());
tv14.setText(m.getWork());
tv8.setText(m.getStreet());
tv18.setText(m.getCity());
tv17.setText(m.getState());
tv19.setText(m.getZipCode());
tv20.setText(m.getCountry());
tv10.setText(m.getBirthdate());
tv16.setText(m.getEmail());
i.setImageURI(Uri.parse("https://s3.amazonaws.com/technical-challenge/v3/images/elmer-fudd-small.jpg"));
return convertView;
}
}
Now here is where I have it being populated. But why does it display as another list listview? I want only ONE item.
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ContactDetail extends AppCompatActivity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewContactAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_detail);
listView = (ListView) findViewById(R.id.list2);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++)
try {
JSONObject obj = response.getJSONObject(i);
// Phone
JSONObject phone = obj.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
String work = phone.getString("work");
//Address
JSONObject address = obj.getJSONObject("address");
String street = address.getString("street");
String city= address.getString("city");
String state= address.getString("state");
String country= address.getString("country");
String zipCode= address.getString("zipCode");
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
dataSet.setBirthdate(obj.getString("birthdate"));
dataSet.setEmail(obj.getString("emailAddress"));
dataSet.setHome(home);
dataSet.setMobile(mobile);
dataSet.setWork(work);
dataSet.setStreet(street);
dataSet.setState(state);
dataSet.setCity(city);
dataSet.setZipCode(zipCode);
dataSet.setCountry(country);
dataSet.setImage(obj.getString("largeImageURL"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(ContactDetail.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
I guess your ContactDetail activity is getting the list again. And why do you need to show a listview again if you only need one item upon clicking of one item in your first activity.
Anyway, if you still want to use listview in your ContactDetail then do this..
in your listview.setOnItemClickListener on MainActivity
Intent intent = new Intent(MainActivity.this, ContactDetail.this);
intent.putExtra("contact", l.get(position));
startActivity(intent);
in your ContactDetails activity, replace it with this.. remove that JsonArrayRequest
listView = (ListView) findViewById(R.id.list2);
Contact contact = getIntent().getSerializableExtra("contact");
l.add(contact);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
and also make sure that your Contact object implements Serializable

Set password visible/invisible in ListVIew with Custom Adapter

I have a ListView which displays wifi settings. Every Item inside my View has a button which allows to set the visibility of the password to visible or invisible. I am able to set the password to visible but not back. This is my code:
Customlistadapter
package com.app.wifibackup;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.app.wifibackup.R;
import java.security.acl.Owner;
import java.util.regex.Pattern;
import static android.R.attr.label;
class CustomListAdapter extends ArrayAdapter<String> {
final Context context = getContext();
String ssid;
String password;
String owner;
String comment;
String location;
String provider;
Boolean showPwd = false;
String hiddenPassword = "";
String bulletChar = "\u2022";
String passwordToShow;
public CustomListAdapter(Context context, String[] dataListFinal) {
super(context, R.layout.listitem_wifilist ,dataListFinal);
}
public String allElementsAdapter = "";
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.listitem_wifilist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_provider);
TextView textViewSsid = (TextView) customView.findViewById(R.id.list_item_datalist_textview_ssid);
final TextView textViewPassword = (TextView) customView.findViewById(R.id.list_item_datalist_textview_password);
TextView textViewOwner = (TextView) customView.findViewById(R.id.list_item_datalist_textview_owner);
final String singleListItem = getItem(position);
final String[] singleListItemArray = singleListItem.split("\t");
final String id = singleListItemArray[0];
ssid = singleListItemArray[1];
password = singleListItemArray[2];
owner = singleListItemArray[3];
comment = singleListItemArray[4];
location = singleListItemArray[5];
provider = singleListItemArray[6];
ImageButton imagebuttonEdit = (ImageButton) customView.findViewById(R.id.imageButton_edit);
ImageButton imagebuttonSetVisibility = (ImageButton) customView.findViewById(R.id.imageButton_setPasswordVisibility);
allElementsAdapter = id + ssid + password + owner + comment + location + provider;
switch (provider) {
case "empty":
image.setImageResource(R.drawable.icon_provider_dummy);
break;
case "FritzBox":
image.setImageResource(R.drawable.icon_provider_fritzbox);
break;
case "Speedport":
image.setImageResource(R.drawable.icon_provider_speedport);
break;
case "Unitymedia":
image.setImageResource(R.drawable.icon_provider_unitymedia);
break;
}
String ownerString = owner;
textViewSsid.setText(ssid);
textViewPassword.setText(setPasswordInvisibile(password));
textViewOwner.setText(ownerString);
imagebuttonEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String [] tmpDataArray = singleListItem.split("\t");
((MainActivity)context).openDialog("Edit", tmpDataArray);
}
});
imagebuttonSetVisibility.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String [] tmpDataArray = singleListItem.split("\t");
if (!showPwd){
showPwd = true;
textViewPassword.setText(setPasswordInvisibile(tmpDataArray[2]));
}
if (showPwd){
showPwd = false;
textViewPassword.setText(tmpDataArray[2]);
}
}
});
return customView;
}
private String setPasswordInvisibile(String pwd){
int passwordLength = pwd.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < passwordLength; i++) {
builder.append(bulletChar);
passwordToShow = builder.toString();
}
return passwordToShow;
}
}
Do you have some suggestions for me?

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.

Android ListView SearchView

I created an ListView which is filled by SQLite Database.
In my App you can add books to a database and you can view the booklist in the BookDataListActivity
Now I would like to implement a SearchView to filter the books. I used this Video https://www.youtube.com/watch?v=c9yC8XGaSv4&list=PLfBjz1j1UV9kdwpvU1YGsjKoNxOtoKTCs&index=1
But it doesnt work.
Following my code. Hopefully you can help me.
package com.kasutwentyseven.gui4selfshelf.Books;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.kasutwentyseven.gui4selfshelf.R;
public class BookDataListActivity extends Activity {
public ListView booklistView;
public SearchView searchView;
public SQLiteDatabase sqLiteDatabaseBooks;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView)findViewById(R.id.book_list_view);
searchView = (SearchView) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(),R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
bookListDataAdapter.getFilter().filter(text);
return false;
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if(cursor2.moveToFirst())
{
do{
String booktitle, bookauthor,bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
}while(cursor2.moveToNext());
}
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " is selected", Toast.LENGTH_LONG).show();
}
});
}
}
How do I implement a Filter?
EDIT: As asked the BookListAdapter
package com.kasutwentyseven.gui4selfshelf.Books;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.TextView;
import com.kasutwentyseven.gui4selfshelf.R;
import java.util.ArrayList;
import java.util.List;
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
}

Passing the contents of the selected row to another activity

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.

Categories

Resources