hello friends i have listview that contain all install app and a checkbox.my problem is that when i check item using checkbox it is not remain permanently ie if i check some item using checkbox and exit app and then run app it should show all previous checked item.
here my package ApkListActivity.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.ibc.android.demo.appslist.adapter.ApkAdapter;
import com.ibc.android.demo.appslist.app.AppData;
public class ApkListActivity extends Activity {
PackageManager packageManager;
ListView apkList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
packageManager = getPackageManager();
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
/* To filter out System apps */
for (PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
if (!b) {
packageList1.add(pi);
}
}
Collections.sort(packageList1, new Comparator<PackageInfo>() {
public int compare(PackageInfo o1, PackageInfo o2) {
return o1.applicationInfo
.loadLabel(getPackageManager())
.toString()
.compareTo(
o2.applicationInfo.loadLabel(
getPackageManager()).toString());
}
});
apkList = (ListView) findViewById(R.id.applist);
apkList.setAdapter(new ApkAdapter(this, packageList1, packageManager));
apkList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long row) {
PackageInfo packageInfo = (PackageInfo) parent
.getItemAtPosition(position);
AppData appData = (AppData) getApplicationContext();
appData.setPackageInfo(packageInfo);
// Intent appInfo = new Intent(getApplicationContext(),
// ApkInfo.class);
// startActivity(appInfo);
PackageInfo country = (PackageInfo) parent
.getItemAtPosition(position);
Toast.makeText(
getApplicationContext(),
"Clicked on Row: "
+ country.applicationInfo.loadLabel(
getPackageManager()).toString(),
Toast.LENGTH_LONG).show();
}
});
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
}
and this is my ApkAdapter.java
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
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;
import com.ibc.android.demo.appslist.activity.R;
public class ApkAdapter extends BaseAdapter {
List<PackageInfo> packageList = null;
Activity context;
Context context2;
PackageManager packageManager;
private ArrayList<Boolean> checkList = new ArrayList<Boolean>();
boolean selected = false;
// List<ApplicationInfo> packageList = new ArrayList<ApplicationInfo>();
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
for (int i = 0; i < packageList.size(); i++) {
checkList.add(selected);
}
}
public int getCount() {
return ((null != packageList) ? packageList.size() : 0);
// return packageList.size();
}
public PackageInfo getItem(int position) {
return ((null != packageList) ? packageList.get(position) : null);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.apklist_item, null);
// holder = new ViewHolder();
}
PackageInfo data = packageList.get(position);
if (null != data) {
TextView apkName = (TextView) view.findViewById(R.id.appname);
ImageView apkicon = (ImageView) view.findViewById(R.id.icon_image);
TextView packageName = (TextView) view
.findViewById(R.id.packagename);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can
// identify the correct
// row in the listener
checkBox.setChecked(checkList.get(position)); // set the status
// as
// we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
;
apkicon.setImageDrawable(appIcon);
apkName.setText(appName);
packageName.setText(packageInfo.packageName);
}
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
checkList.set((Integer) buttonView.getTag(), isChecked);
}
};
}
You can save the List of Boolean values in a simple 1010101 format and then save this integer in SharedPreferences. When your app is opened, just use the integer to repopulate your checkboxes.
Related
I got a source code about GridView.
But, I confused why some code were error.
These are the code. I got error on OnClick Method in MainActivity. Is here anyone help me? Thanks
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
}
});
I want to each item that when it clicked shown the detailed image and text. I also get code like this but when I clicked "GingerBread" item, it goes to first item ("Astro")
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
// intent.putExtra("android.intent.extra.TEXT", Integer.parseInt(getIntent().getStringExtra("android.intent.extra.TEXT")));
intent.putExtra("title", item.getTitle());
//Start details activity
startActivity(intent);
overridePendingTransition(R.anim.home_detail_entry, R.anim.home_detail_exit);
}
});
MainActivity.java
package com.acer.gridview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
public static String[] bitmapName = {
"Astro", "Bender", "Cupcake", "Donut", "Eclair",
"Froyo", "Gingerbread", "HoneyComb"
};
public static int[] bitmapId = {
R.drawable.Astro, R.drawable.Bender, R.drawable.Cupcake, R.drawable.Eclair,
R.drawable.Froyo, R.drawable.Gingerbread, R.drawable.HoneyComb
};
private GridViewAdapter gridAdapter;
private GridView gridView;
ArrayList < ImageItem > imageItems;
private ArrayList < ImageItem > getData() {
imageItems = new ArrayList();
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
int i = 0;
for (;;) {
if (i > 7) {
return imageItems;
}
Bitmap localBitmap = BitmapFactory.decodeResource(getResources(), bitmapId[i], localOptions);
imageItems.add(new ImageItem(localBitmap, bitmapName[i]));
i += 1;
}
}
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
////////////This code shown error///////////////////
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
////////////This code shown error///////////////////
}
});
}
public void toDetail(int Int, String String) {
Intent localIntent = new Intent(this, DetailActivity.class);
localIntent.putExtra("android.intent.extra.TEXT", Integer.toString(Int));
localIntent.putExtra("title", String);
startActivity(localIntent);
}
/**
* A placeholder fragment containing a simple view.
*/
private boolean ActionBar(final Intent aIntent) {
try {
startActivity(aIntent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public void showDialog() {
LayoutInflater inflater = getLayoutInflater();
View localView = inflater.inflate(R.layout.help_dialog, null);
((ImageView) localView.findViewById(R.id.imageView1)).setImageResource(R.drawable.makhrojulhuruf);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(localView);
builder.show();
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
GridViewAdapter.java
package com.acer.gridview;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Acer on 08/02/2016.
*/
public class GridViewAdapter extends ArrayAdapter<ImageItem> {
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = (ImageItem) data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.java
package com.acer.gridview;
import android.graphics.Bitmap;
/**
* Created by Acer on 08/02/2016.
*/
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap Bitmap, String String)
{
setImage(Bitmap);
setTitle(String);
}
public Bitmap getImage()
{
return this.image;
}
public String getTitle()
{
return this.title;
}
public void setImage(Bitmap Bitmap)
{
this.image = Bitmap;
}
public void setTitle(String String)
{
this.title = String;
}
}
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;
}
}
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.
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("");
}
}
}
I am working on an android application in which i have implemented CustomListView having some images and texts. i am feeding data in listview after a webservice call it takes some time to render list and when i scroll the list it's not scrolling smoothly.
here is the code of my List Adapter:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.makamaka.Constant;
import com.tv.makamaka.R;
import com.tv.makamaka.comment.SmileyCommentDialogActivity;
public class MakaMakaProfileListAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private ArrayList<Object> itemList;
private Activity _activity;
String caption="";
String photoPath="";
String comments="";
String commentImage="";
String commentUserId="";
String likersImage="";
String likersType="";
String likersUserId="";
String mediaid="";
String mediaImageUrl="";
String mediaString="";
String mediaStringImage="";
String mediaStringUserId="";
String mediaType="";
String rating="";
String requestCount="";
String userid="";
String userProileImage="";
String withfriends="";
int index,index1,index2;
public MakaMakaProfileListAdapter(Activity activity, ArrayList<Object> itemList) {
this._activity = activity;
this.itemList = itemList;
mInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return itemList.size();
}
public Object getItem(int position) {
return itemList.get(position);
}
public Filter getFilter() {
return null;
}
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
TextView _commentTxt;
ImageView _userImage;
ImageView _smallUserImage;
ImageView _smallPostedUserImage;
ImageView _transparentImage;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.makamaka_profile_listrow, null);
holder = new ViewHolder();
holder._userImage=(ImageView)convertView.findViewById(R.id.posted_userimage);
holder._smallUserImage=(ImageView)convertView.findViewById(R.id.small_userimage);
holder._smallPostedUserImage=(ImageView)convertView.findViewById(R.id.small_posted_userimage);
holder._transparentImage=(ImageView)convertView.findViewById(R.id.transparent_smiley_image);
holder._commentTxt = (TextView) convertView.findViewById(R.id.comment_txt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._commentTxt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
holder._transparentImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(_activity,SmileyCommentDialogActivity.class);
_activity.startActivity(intent);
}
});
//////////////////SET VALUES ON LIST VIEW///////////////////////////
MakaMakaProfileBean makaMakaProfileBean=(MakaMakaProfileBean)itemList.get(position);
////////////////PARSE CAPTION///////////
caption=makaMakaProfileBean.getCaption();
ArrayList<String> captionList = new ArrayList<String>(Arrays.asList(caption.split(" , ")));
/*int index=caption.indexOf(",");
String caption1=caption.substring(0,index);
int index1=caption.indexOf(",", index+1);
String userName=caption.substring(index,index1+1);
String timeAgo=caption.substring(index1+1);*/
////////////////////////////////////////
////////////////PARSE COMMENTS////////////
comments=makaMakaProfileBean.getComments();
ArrayList<String> commentList = new ArrayList<String>(Arrays.asList(comments.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT IMAGES//////
commentImage=makaMakaProfileBean.getCommentImage();
ArrayList<String> commentImageList = new ArrayList<String>(Arrays.asList(commentImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT USER ID//////
commentUserId=makaMakaProfileBean.getCommentId();
ArrayList<String> commentUserIdList = new ArrayList<String>(Arrays.asList(commentUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER IMAGES//////
likersImage=makaMakaProfileBean.getlikersImage();
ArrayList<String> likersImageList = new ArrayList<String>(Arrays.asList(likersImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER TYPE//////
likersType=makaMakaProfileBean.getComments();
ArrayList<String> likerTypeList = new ArrayList<String>(Arrays.asList(likersType.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER USER ID//////
likersUserId=makaMakaProfileBean.getComments();
ArrayList<String> likerUserIdList = new ArrayList<String>(Arrays.asList(likersUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE OTHER PARAS//////
mediaid=makaMakaProfileBean.getmediaId();
mediaImageUrl=makaMakaProfileBean.getMediaImageUrl();
mediaString=makaMakaProfileBean.getMediaString();
mediaStringImage=makaMakaProfileBean.getMediaStringImage();
//mediaStringUserId=makaMakaProfileBean.
mediaType=makaMakaProfileBean.getMediaType();
rating=makaMakaProfileBean.getRating();
requestCount=makaMakaProfileBean.getRequestCount();
userid=makaMakaProfileBean.getUserId();
//userProileImage=makaMakaProfileBean.getUserProfileImage();
withfriends=makaMakaProfileBean.getWithFriends();
//////////////////////////////////////////
photoPath=makaMakaProfileBean.getUserProfileImage();
if(photoPath!=null){
URL url;
try {
url = new URL(photoPath);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder._userImage.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
int i=0;
while(i<captionList.size()){
if(i==0){
holder._commentTxt.setText((String)captionList.get(i));
}else if(i==1){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}else if(i==2){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}
i++;
}
return convertView;
/////////////////////////////////////////////////////////////////////
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case 123:
break;
default:
break;
}
}
};
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
//SEND EMAIL TO INVITE FRIEND
public void sendEmail(String emailId){
Intent intent = new Intent(Intent.ACTION_SEND);
//intent.setType("text/plain");
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, emailId);
intent.putExtra(Intent.EXTRA_SUBJECT,Constant.EMAIL_SUBJECT);
intent.putExtra(Intent.EXTRA_TEXT, Constant.EMAIL_CONTENT);
_activity.startActivity(Intent.createChooser(intent, "Send Email"));
}
}
Output:
Is there any way to make list with smooth scroll.
You're decoding the image in getView. That's an expensive call, and you're going to be doing it a lot while scrolling. Use an LRUCache to cache images, so you can reuse the results of previous decodes if they exist. Only decode it in getView if its not in the cache.