Set bind view in simple adapter? - java

I want to setup view binder in simple adapter to show photos from contacts, however I set two text view's with name and number with Hash Map, so third value is Image View where I want to put contact photo corresponding to contact ID.
Thank you in advance, Wolf.
Here is my code :
ArrayList<HashMap<String, String>> mapa = new ArrayList<HashMap<String, String>>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cur.getCount() > 0){
while(cur.moveToNext()){
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String photoUri = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
if(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
final Cursor numCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
for(numCur.moveToFirst(); !numCur.isAfterLast(); numCur.moveToNext()){
brTel = numCur.getString(numCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ime = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
tmpIme = new String[] {ime};
for(int i = 0; i < tmpIme.length; i++){
HashMap<String, String> imeMapa = new HashMap<String, String>();
imeMapa.put("imeLista", ime);
imeMapa.put("checkBox", photoUri);
imeMapa.put("Mobilni", brTel);
mapa.add(imeMapa);
}
}
numCur.close();
}
} // While
}
SimpleAdapter sa = new SimpleAdapter(getApplicationContext(), mapa, R.layout.imenik, new String[] {"imeLista", "checkBox", "Mobilni"}, new int[] {R.id.tvImeImenik, R.id.cbOznaci, R.id.tvSamoProba});
sa.setViewBinder(simpleSlika);
lImenik.setAdapter(sa);
and my view binder is :
private final SimpleAdapter.ViewBinder simpleSlika = new SimpleAdapter.ViewBinder() {
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView v = (ImageView)view;
v.setImageBitmap((Bitmap)data);
// return true to signal that bind was successful
return true;
}
return false;
}
};
but it's not working.
Help please???

Yes its possible, you just create your own adapter (extends BaseAdapter), override getView method and there add bitmap to imageview.
public ContactAdapter(Activity a,ArrayList<Object> list)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View v=convertView;
if(convertView==null)
v = inflater.inflate(R.layout.contact, null);
ImageView image = (ImageView)v.findViewById(R.id.img);
}
Something like this. You have to extends this.
Check also : Lazy load of images in ListView

Related

Highlight search results in ListView whlie typing in EditText [duplicate]

I am trying to do a search such that all the "visible" search letters should be highlighted. I tried using spannable but that didn't do the trick, maybe I wasnt doing it right? based on this: Highlight searched text in ListView items
How do i get to highlight the visible text? here's my filter :
private LayoutInflater mInflater;
private ValueFilter valueFilter;
public MySimpleArrayAdapter(Activity context) {
this.context = context;
mInflater = LayoutInflater.from(context);
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected synchronized FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Integer> filterList = new ArrayList<>();
int iCnt = listItemsHolder.Names.size();
for (int i = 0; i < iCnt; i++) {
if(listItemsHolder.Types.get(i).toString().indexOf("HEADER_")>-1){
continue;
}
if (listItemsHolder.Names.get(i).matches(getRegEx(constraint))||(listItemsHolder.Names.get(i).toLowerCase().contains(constraint.toString().toLowerCase()))) {
if(filterList.contains(i))
continue;
filterList.add(i);
}
}
results.count = filterList.size();
results.values = filterList;
}else {
String prefixString = getRegEx(constraint);
mSearchText = prefixString;
results.count = listItemsHolder.Names.size();
ArrayList<Integer> tList = new ArrayList<>();
for(int i=0;i<results.count;i++){
tList.add(i);
}
results.values = tList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Integer> resultsList = (ArrayList<Integer>)results.values;
if(resultsList != null) {
m_filterList = resultsList;
}
notifyDataSetChanged();
}
}
public String getRegEx(CharSequence elements){
String result = "(?i).*";
for(String element : elements.toString().split("\\s")){
result += element + ".*";
}
result += ".*";
return result;
}
Thanks in advance!
Here's my getview
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder holder;
if(filtering && m_filterList != null && m_filterList.size() > position)
position = m_filterList.get(position);
if (rowView == null) {
holder = new ViewHolder();
mInflater = context.getLayoutInflater();
rowView = mInflater.inflate(R.layout.rowlayout, null);
// configure view holder
holder.text = (TextView) rowView.findViewById(R.id.label);
holder.text.setTextColor(Color.WHITE);
holder.text.setSingleLine();
holder.text.setTextSize(15);
holder.text.setEllipsize(TextUtils.TruncateAt.END);
holder.text.setPadding(2, 2, 6, 2);
Typeface label = Typeface.createFromAsset(holder.text.getContext().getAssets(),
"fonts/arial-bold.ttf");
holder.text.setTypeface(label);
holder.image = (ImageView) rowView.findViewById(R.id.icon);
holder.image.setPadding(6, 4, 0, 4);
holder.image.getLayoutParams().height = (int) getResources().getDimension(R.dimen.icon_width_height);
holder.image.getLayoutParams().width = (int) getResources().getDimension(R.dimen.icon_width_height);
rowView.setBackgroundResource(R.drawable.row_border);
rowView.setPadding(2, 2, 6, 2);
rowView.setTag(holder);
}else {
// fill data
holder = (ViewHolder) rowView.getTag();
}
String id = listItemsHolder.getid(position);
String name = listItemsHolder.getName(position);
holder.image.setVisibility(View.VISIBLE);
if (name != null) {
holder.text.setText(listItemsHolder.getName(position));
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) holder.text.getLayoutParams();
params.leftMargin = 20;
}else{
holder.text.setText(id);
}
String fullText = listItemsHolder.getName(position);
// highlight search text
if (mSearchText != null && !mSearchText.isEmpty()) {
int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
int endPos = startPos + mSearchText.length();
if (startPos != -1) {
Spannable spannable = new SpannableString(fullText);
ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.text.setText(spannable);
} else {
holder.text.setText(fullText);
}
} else {
holder.text.setText(fullText);
}
return rowView;
}
Let's assume you have create a custom adapter, then you can refer to the following code:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
TextView text;
if (convertView == null) {
view = mInflater.inflate(mResource, parent, false);
} else {
view = convertView;
}
try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(mFieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
String item = getItem(position);
text.setText(item);
String fullText = getItem(position);
// highlight search text
if (mSearchText != null && !mSearchText.isEmpty()) {
int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
int endPos = startPos + mSearchText.length();
if (startPos != -1) {
Spannable spannable = new SpannableString(fullText);
ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText(spannable);
} else {
text.setText(fullText);
}
} else {
text.setText(fullText);
}
return view;
}
The mSearchText will be updated at the following inside performFiltering of ArrayFilter class.
String prefixString = prefix.toString().toLowerCase();
mSearchText = prefixString;
You can find more details in my sample code here or my GitHub (with lastest update).
Here is the screenshot
In your filter method, store the string used to perform the filter:
// Filter Class
public void filter(String searchString) {
this.searchString = searchString;
...
// Filtering stuff as normal.
}
You must declare a member string to store it:
public class ListViewAdapter extends BaseAdapter {
...
String searchString = "";
...
And, in getView you highlight the search term:
public View getView(final int position, View view, ViewGroup parent) {
...
// Set the results into TextViews
WorldPopulation item = worldpopulationlist.get(position);
holder.rank.setText(item.getRank());
holder.country.setText(item.getCountry());
holder.population.setText(item.getPopulation());
// Find charText in wp
String country = item.getCountry().toLowerCase(Locale.getDefault());
if (country.contains(searchString)) {
Log.e("test", country + " contains: " + searchString);
int startPos = country.indexOf(searchString);
int endPos = startPos + searchString.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.country.getText()); // <- EDITED: Use the original string, as `country` has been converted to lowercase.
spanText.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.country.setText(spanText, TextView.BufferType.SPANNABLE);
}
...
}
Hope it helps.
Hi on your adapter class ,make a spanneble text and set it to your textview, the below code you can use for reference.
if ("text contains filter value".toLowerCase().contains("filter".toLowerCase())) {
Spannable spanText = Spannable.Factory.getInstance().newSpannable("text contains filter value".toLowerCase());
Matcher matcher = Pattern.compile("filter".toLowerCase())
.matcher("text contains filter value".toLowerCase());
while (matcher.find()) {
spanText.setSpan(new ForegroundColorSpan(Color.RED), matcher.start(),
matcher.start() + "filter".length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
yourTextView.setText(spanText);
}
This is only demo for highlight text, you can implement your self by calling
highlight(searchText, originalText) in filter,
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
text = (TextView) findViewById(R.id.textView1);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
text.setText(highlight(editText.getText().toString(), text.getText().toString()));
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public static CharSequence highlight(String search, String originalText) {
String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
int start = normalizedText.indexOf(search);
if (start <= 0) {
return originalText;
} else {
Spannable highlighted = new SpannableString(originalText);
while (start > 0) {
int spanStart = Math.min(start, originalText.length());
int spanEnd = Math.min(start + search.length(), originalText.length());
highlighted.setSpan(new BackgroundColorSpan(Color.YELLOW), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = normalizedText.indexOf(search, spanEnd);
}
return highlighted;
}
}
}
Put this code before setting text in getview
Spannable wordtoSpan = new SpannableString("Your_text_in_getviews");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, edtFilter
.getText().toString().length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txt_contact.setText(wordtoSpan);
It can be done in a bit simpler way:
Define custom adapter:
class HighlightAutoCompleteAdapter(context: Context, resource: Int, private val textResId: Int, items: List<String>) :
ArrayAdapter<String>(context, resource, textResId, items) {
private val inflater = LayoutInflater.from(context)
var queryText = ""
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: inflater.inflate(textResId, parent, false)
val textView: TextView = view.findViewById(android.R.id.text1) as TextView
val fullText = getItem(position) as String
// highlight search text
val highlight: Spannable = SpannableString(fullText)
if (queryText.isNotEmpty()) {
val startPos: Int = fullText.toLowerCase(Locale.US).indexOf(queryText.toLowerCase(Locale.US))
val endPos: Int = startPos + queryText.length
if (startPos != -1) {
highlight.setSpan(StyleSpan(BOLD),
startPos,
endPos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
textView.text = highlight
return view
}
}
Create the adapter and listen to text changes to keep the adapter updated:
val searchEditText: AutoCompleteTextView = view.findViewById(R.id.search_edit_text)
val arrayAdapter = HighlightAutoCompleteAdapter(requireContext(), 0, R.layout.search_complete_item, autoCompletionList)
searchEditText.setAdapter(arrayAdapter)
searchEditText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
arrayAdapter.queryText = s?.toString() ?: ""
}
override fun afterTextChanged(s: Editable?) {}
})

How to add a "header" view at the top of each expanded group view in an ExpandableListView populated by SimpleCursorAdapter

I'm using an ExpandableListView inside one of my activities and populating the child and group views (separate .xml files with a few textviews for each) using a custom SimpleCursorAdapter. I'm looking to have the following functionality: When a group is clicked, the list of children populates and an additional header (two textviews) populates in position 0 of the child list to act as the titles of each column of data the child displays.
Here's the code for my SimpleCursorAdapter and a snippet of the relevant code in my activity:
SimpleCursorAdapter:
public class PayeeCursorAdapter extends SimpleCursorTreeAdapter {
private final String LOG_TAG = getClass().getSimpleName();
private PayeeActivity mActivity;
protected final HashMap<Integer, Integer> mGroupMap;
// No cursor is added to the adapter so that it only runs when the CursorLoader runs, instead of every time the activity does
public PayeeCursorAdapter(
Context context, // The activity where the adapter will be running
int groupLayout, // The .xml layout file for the group layout
int childLayout, // The .xml layout file for the child layout
String[] groupFrom, // String of column names in the cursor that is the data for each group item
int[] groupTo, // The ID of the views in the group layout that display the column from the groupFrom String[]
String[] childrenFrom, // String of column names in the cursor that is the data for each child item
int[] childrenTo) { // The ID of the views in the child layout that display the column from the childFrom String[]
super(context, null, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, childrenTo);
mActivity = (PayeeActivity) context;
mGroupMap = new HashMap<Integer, Integer>();
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
int groupPos = groupCursor.getPosition();
int groupId = groupCursor.getInt(groupCursor.getColumnIndex(BillMeContract.PayeeEntry._ID));
Log.d(LOG_TAG, "getChildrenCursor() for groupPos " + groupPos);
Log.d(LOG_TAG, "getChildrenCursor() for groupId " + groupId);
mGroupMap.put(groupId, groupPos);
Loader<Cursor> loader = mActivity.getSupportLoaderManager().getLoader(groupId);
if(loader != null && !loader.isReset()) {
mActivity.getSupportLoaderManager().restartLoader(groupId, null, mActivity);
} else {
mActivity.getSupportLoaderManager().initLoader(groupId, null, mActivity);
}
return null;
}
public HashMap<Integer, Integer> getGroupMap(){
return mGroupMap;
}
}
Activity:
ExpandableListView expandablePayeeListView = (ExpandableListView) findViewById(R.id.payee_exp_list);
mAdapter = new PayeeCursorAdapter(
this,
R.layout.list_group_payee,
R.layout.list_item_payee_tx,
new String[] {BillMeContract.PayeeEntry.COL_NAME},
new int[] {R.id.payee_list_header},
new String[] {BillMeContract.TransactionEntry.COL_DATE,
BillMeContract.TransactionEntry.COL_PAYMENT,
BillMeContract.TransactionEntry.COL_TYPE},
new int[] {R.id.payee_list_item_date,
R.id.payee_list_item_amount,
R.id.payee_list_item_type});
mAdapter.setViewBinder(new SimpleCursorTreeAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(columnIndex == 4) {
int type = cursor.getInt(columnIndex);
TextView textView = (TextView) view;
if(type == BillMeContract.TransactionEntry.TYPE_CASH) {
textView.setText(R.string.tx_spinner_type_cash);
} else if (type == BillMeContract.TransactionEntry.TYPE_CHEQUE) {
textView.setText(R.string.tx_spinner_type_cheque);
} else if (type == BillMeContract.TransactionEntry.TYPE_E_TRANSFER) {
textView.setText(R.string.tx_spinner_type_e_transfer);
}
return true;
} else if(columnIndex == 3){
String cost = String.format(Locale.CANADA, "%.2f", cursor.getDouble(columnIndex));
cost = "$" + cost;
TextView textView = (TextView) view;
textView.setText(cost);
return true;
}
return false;
}
});
expandablePayeeListView.setAdapter(mAdapter);

ListItems ArrayList ListView

Guys I'm trying to make the below code store multiple items in exampleArray but it's only grabbing the first SectionOutageListItem. Do I need to create another listItem Array to loop through it again?
SectionOutageListItem[] exampleArray = new SectionOutageListItem[outnums.size()];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i)),
new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
UPDATE:
I have a custom adapter which adds sections to a listview, the SectionOutageListItem determines how many rows are in that section. The outnums.get(i) creates multiple sections which should add the impact and status as rows for each section. It is only adding the first new SectionOutageListItem as a row and not the second one.
Custom List Adapter code
public class CustomOutageDetailListAdapter extends ArrayAdapter<SectionOutageListItem> {
private Activity context;
private SectionOutageListItem[] items;
//private final ArrayList<String> itemname;
public CustomOutageDetailListAdapter(Activity context, SectionOutageListItem[] items) {
super(context, R.layout.mylistoutagedetails, items);
this.items= items;
this.context = context;
}
#Override
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.mylistoutagedetails, null,true);
final SectionOutageListItem currentItem = items[position];
if (currentItem != null) {
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
TextView txtName = (TextView) rowView.findViewById(R.id.name);
if (txtTitle != null) {
txtTitle.setText(currentItem.item.toString());
}
if (txtName != null) {
txtName.setText(currentItem.name.toString());
}
}
return rowView;
};
As #Trobbins points out ,
You may need to change the code as follows,
SectionOutageListItem[][] exampleArray = new SectionOutageListItem[outnums.size()][2];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i][0] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i));
exampleArray[i][1] = new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
You can also go with a Map specifically LinkedHashMap if you want to maintain the insertion order or else HashMap

How to view data in database on fragment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to view data in database on fragment and I use TableRow to view data.
my code Setting database :
public class SqliteManager extends Activity {
public static final int VERSI_DATABASE= 1;
public static final String NAMA_DATABASE = "dbCrudSqlite";
public static final String NAMA_TABEL = "tbAgenda";
public static final String FIELD_ID = "_id";
public static final int POSISI_ID = 0;
public static final String FIELD_JUDUL = "judul";
public static final int POSISI_JUDUL = 1;
public static final String FIELD_DESKRIPSI = "deskripsi";
public static final int POSISI_DESKRIPSI = 2;
public static final String FIELD_WAKTU = "waktu";
public static final int POSISI_WAKTU = 3;
public static final String[] FIELD_TABEL ={ SqliteManager.FIELD_ID, SqliteManager.FIELD_JUDUL, SqliteManager.FIELD_DESKRIPSI, SqliteManager.FIELD_WAKTU };
private Context crudContext;
private SQLiteDatabase crudDatabase;
private SqliteManagerHelper crudHelper;
private static class SqliteManagerHelper extends SQLiteOpenHelper {
private static final String BUAT_TABEL =
"create table " + NAMA_TABEL + " (" +
SqliteManager.FIELD_ID + " integer primary key autoincrement, " +
SqliteManager.FIELD_JUDUL + " text not null, " +
SqliteManager.FIELD_DESKRIPSI + " text not null," +
SqliteManager.FIELD_WAKTU + " text not null " +
");";
public SqliteManagerHelper(Context context) {
super(context, NAMA_DATABASE, null, VERSI_DATABASE);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(BUAT_TABEL);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
public void generateData(SQLiteDatabase database){
ContentValues cv=new ContentValues();
cv.put(FIELD_ID, "3");
cv.put(FIELD_JUDUL, "Abang");
cv.put(FIELD_DESKRIPSI, "Abang");
cv.put(FIELD_WAKTU, "Merah");
database.insert(NAMA_TABEL,null,cv);
cv.put(FIELD_ID, "2");
cv.put(FIELD_JUDUL, "Opo");
cv.put(FIELD_DESKRIPSI, "Opo");
cv.put(FIELD_WAKTU, "Apa");
database.insert(NAMA_TABEL,null,cv);
}
public SqliteManager(Context context) {
crudContext = context;
}
public void bukaKoneksi() throws SQLException {
crudHelper = new SqliteManagerHelper(crudContext);
crudDatabase = crudHelper.getWritableDatabase();
generateData(crudDatabase);
}
public void tutupKoneksi() {
crudHelper.close();
crudHelper = null;
crudDatabase = null;
}
public long insertData(ContentValues values) {
return crudDatabase.insert(NAMA_TABEL, null, values);
}
public boolean updateData(long rowId, ContentValues values) {
return crudDatabase.update(NAMA_TABEL, values,
SqliteManager.FIELD_ID + "=" + rowId, null) > 0;
}
public boolean hapusData(long rowId) {
return crudDatabase.delete(NAMA_TABEL,
SqliteManager.FIELD_ID + "=" + rowId, null) > 0;
}
public Cursor bacaData() {
return crudDatabase.query(NAMA_TABEL,FIELD_TABEL,null, null, null, null,SqliteManager.FIELD_JUDUL + " DESC");
}
public Cursor bacaDataTerseleksi(long rowId) throws SQLException {
Cursor cursor = crudDatabase.query(true, NAMA_TABEL,FIELD_TABEL,FIELD_ID + "=" + rowId,null, null, null, null, null);
cursor.moveToFirst();
return cursor;
}
public ContentValues ambilData(String tempat, String lat, String lng) {
ContentValues values = new ContentValues();
values.put(SqliteManager.FIELD_JUDUL, tempat);
values.put(SqliteManager.FIELD_DESKRIPSI, lat);
values.put(SqliteManager.FIELD_WAKTU, lng);
return values;
}
public ArrayList<ArrayList<Object>> ambilSemuaBaris(){
ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try
{
cur = crudDatabase.query(NAMA_TABEL, new String[]{FIELD_ID,FIELD_JUDUL,FIELD_DESKRIPSI}, null, null, null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast())
{
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataArray.add(dataList);
}while (cur.moveToNext());
}
}catch (Exception e)
{
e.printStackTrace();
Log.e("DB ERROR",e.toString());
}
return dataArray;
}
}
I want to view data on fragment:
public class JawaIndo extends Fragment {
private SqliteManager sqliteDB;
private Activity activity;
TextView bhsjawa,bhsindo;
Button addBtn;
TableLayout tabel4data;
public JawaIndo(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jawaindo, container, false);
sqliteDB = new SqliteManager(getActivity());
sqliteDB.bukaKoneksi();
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
return rootView;
}
protected void updateTable() {
while (tabel4data.getChildCount()>1){
tabel4data.removeViewAt(1);
}
ArrayList<ArrayList<Object>> data = sqliteDB.ambilSemuaBaris();
for (int posisi = 0; posisi < data.size(); posisi++) {
TableRow tabelBaris = new TableRow(getActivity());
ArrayList<Object> baris = data.get(posisi);
TextView idTxt = new TextView(getActivity());
idTxt.setText(baris.get(0).toString());
tabelBaris.addView(idTxt);
TextView namaTxt = new TextView(getActivity());
namaTxt.setText(baris.get(1).toString());
tabelBaris.addView(namaTxt);
TextView hobiTxt = new TextView(getActivity());
hobiTxt.setText(baris.get(2).toString());
tabelBaris.addView(hobiTxt);
tabel4data.addView(tabelBaris);
}
}
}
Error when I write this code on class JawaIndo :
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
You have just change some in your onCreateView() method:
And it should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jawaindo, container, false);
sqliteDB = new SqliteManager(getActivity());
sqliteDB.bukaKoneksi();
//activity = new Activity();
// Update Here
tabel4data = (TableLayout) rootView .findViewById(R.id.tabel_data);
bhsjawa = (TextView) rootView .findViewById(R.id.nama_id);
bhsindo = (TextView) rootView .findViewById(R.id.hobi_id);
updateTable();
return rootView;
}
In this passed your View's object named rootView as referenced to find the id of your UI element.
Didn't read all the code, just the snippet you highlighted and the logcat and even there spotted multiple problems:
The constraint failed comes when you're trying to call generateData() from onCreateView(). When running the code again, the very same data is re-inserted, causing the constraint failed failure.
Then, in here:
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
You should never instantiate activities with new. Now all those findViewById()s will return null and get you a NullPointerException later on in updateTable().
You can not get reference of your from your activity instance. It will always get from the View only. The View class is responsible to initialize and find the views in your screen. So always find your views by layout only.
Here is your code:
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
Change it as below. Change your reference of activity to rootView
activity = new Activity();
tabel4data = (TableLayout) rootView .findViewById(R.id.tabel_data);
bhsjawa = (TextView) rootView .findViewById(R.id.nama_id);
bhsindo = (TextView) rootView .findViewById(R.id.hobi_id);
updateTable();

Android Gallery App Force Close issue for Micromax funbook P300 tab

I am Developing an android application, where in i am trying to access the android built-in Gallery app. I am using the below code for it.
public void initialize()
{
images.clear();
final String[] columns = { MediaStore.Images.Thumbnails._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if(imagecursor != null)
{
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++)
{
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.id = id;
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
images.add(imageItem);
}
imagecursor.close();
}
notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ImageItem item = images.get(position);
holder.imageview.setId(position);
holder.imageview.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
int id = v.getId();
ImageItem item = images.get(id);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
final String[] columns = { MediaStore.Images.Media.DATA };
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
MediaStore.Images.Media._ID + " = " + item.id, null, MediaStore.Images.Media._ID);
if (imagecursor != null && imagecursor.getCount() > 0)
{
Log.e("image cursor","image cursor");
imagecursor.moveToPosition(0);
String path = imagecursor.getString(imagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
File file = new File(path);
Log.e("image cursor","image cursor"+imagecursor);
imagecursor.close();
intent.setDataAndType(
Uri.fromFile(file),
"image/*");
startActivityForResult(intent, VIEW_IMAGE);
}
}
});
holder.imageview.setImageBitmap(item.img);
return convertView;
}
The Code Works just fine for all the devices, except for micromax funbook p300 tab. and the Error Log Looks like this
http://textuploader.com/?p=6&id=AkS9T
Not Getting Where iam going wrong! Please Help! Thanks!
It is throwing the following exception:
android.database.StaleDataException: Attempted to access a cursor
after it has been closed.
Consider moving imagecursor.close() into the onDestroy() method of your Activity.
Other related tips in this post.

Categories