Android ListView with Sqlite access - android

I build a activity with a listview.
Populate it by use of sqlite.
But, when I write a few records into the DB and than show the result in the listView.
He doesn't show all the records.
Thank a lot for you help.
debug screen
D/DstNote: Find all arrow info.
D/DstNote: Records : 3
D/DstNote: 454554
D/DstNote: 45545454
D/DstNote: Find all arrow info.
D/DstNote: Records : 3
D/DstNote: position : 0
D/DstNote: position : 1
Méthode to read the data into DB
public ArrayList<ArrowInfo> getAllArrowInfo() {
Log.d("DstNote", "Find all arrow info.");
ArrayList<ArrowInfo> allArrowInfo = new ArrayList<>();
String[] selectedColomns = new String[] {
COLOMN_ID, COLOMN_ARROW_REF, COLOMN_TYPE_ARC, COLOMN_FIELD_IN, COLOMN_FIELD_OUT
};
Cursor c = db.query(TABLE_NAME, selectedColomns, null, null, null, null, null);
c.moveToFirst();
Log.d("DstNote", ""+c.getCount());
while (c.moveToNext()) {
Log.d("DstNote", cursorToArrow(c).getArrowRef());
allArrowInfo.add(cursorToArrow(c));
}
return allArrowInfo;
}
the adapter
class ArrowInfoAdapter extends BaseAdapter {
private Context ctx;
private ArrayList<ArrowInfo> allArrayInfo;
public ArrowInfoAdapter(Context context, ArrayList<ArrowInfo> allArrayInfo) {
ctx = context;
this.allArrayInfo = allArrayInfo;
}
#Override
public int getCount() {
return (allArrayInfo != null) ? allArrowInfo.size() : 0;
}
#Override
public long getItemId(int position) {
return position;
}
#Nullable
#Override
public ArrowInfo getItem(int position) {
return allArrowInfo.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ArrowInfo currentArrowInfo = allArrowInfo.get(position);
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.simple_listview_arraw_info_item, parent, false);
}
Log.d("DstNote", "position : " + position);
TextView refArrow = (TextView) itemView.findViewById(R.id.refArrow);
TextView arcType = (TextView) itemView.findViewById(R.id.arctype_TextView);
TextView field = (TextView) itemView.findViewById(R.id.field_textview);
refArrow.setText(currentArrowInfo.getArrowRef());
arcType.setText(currentArrowInfo.getTypeArc().name());
field.setText((currentArrowInfo.getIndoor() == 0) ? "IN" : "OUT");
itemView.setTag(currentArrowInfo);
return itemView;
}
public void refresh() {
/*allArrowInfo.clear();
allArrowInfo.addAll(model.getAllArrowInfo());*/
notifyDataSetChanged();
}
}
and the create méthod
allArrowInfo = model.getAllArrowInfo();
for (ArrowInfo item : allArrowInfo) {
Log.d("DstNote", item.getArrowRef());
}
adapter = new ArrowInfoAdapter(getBaseContext(), allArrowInfo);
registerForContextMenu(arrowInfoListView);
arrowInfoListView.setAdapter(adapter);

Related

custom listview repeat last row

hi i want to get values from database and show in listview
i get 6 value from database and send it to adapter but all 6 row is last item to send to adapter
when i add
ViewHolder holder;
android studio after alt + enter change to
RecyclerView.ViewHolder holder;
i read this post's but can not fix problem
Rows being repeated in ListView
Duplicated entries in ListView
Android Listview row repeating item
List item repeating in android customized listview
I know this question is duplicate but can not fix it
Thanks in advance
my adapter :
public class lim_sms_adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<lim_sms> lim_smsItems;
public lim_sms_adapter (Activity activity, List<lim_sms> lim_smsItems) {
this.activity = activity;
this.lim_smsItems = lim_smsItems;
}
#Override
public int getCount() {
return lim_smsItems.size();
}
#Override
public Object getItem(int location) {
return lim_smsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#SuppressLint("SetTextI18n")
#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.row_lim_sms, null);
TextView number = (TextView) convertView.findViewById(R.id.row_lim_sms_txt_number);
lim_sms m = lim_smsItems.get(position);
number.setText(m.getSms_number());
return convertView;
}
}
my class seter and geter :
public class lim_sms {
String sms_number;
public lim_sms(String sms_number) {
this.sms_number = sms_number;
}
public lim_sms() {
}
public String getSms_number() {
return sms_number;
}
public void setSms_number(String sms_number) {
this.sms_number = sms_number;
}
}
my activity :
public class list_limit_sms extends AppCompatActivity {
private List<lim_sms> limit_sms = new ArrayList<lim_sms>();
private lim_sms_adapter adapter;
private sms_database sms_db = new sms_database(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_limit_sms);
ListView listView = (ListView) findViewById(R.id.list_lim_sms);
adapter = new lim_sms_adapter(this, limit_sms);
listView.setAdapter(adapter);
lim_sms cy = new lim_sms();
List<sms_class> sms_list = sms_db.getAllContacts();
for (sms_class ss : sms_list) {
//String log = "Id: "+ss.getId()+" ,num: " + ss.getNum() + " ,type: " + ss.getType();
//Toast.makeText(this, ""+log, Toast.LENGTH_LONG).show();
cy.setSms_number(ss.getNum());
Toast.makeText(this, ""+ss.getNum(), Toast.LENGTH_SHORT).show();
limit_sms.add(cy);
adapter.notifyDataSetChanged();
}
}
}

Trying to manually add item in a ListView tied to a custom cursor adapter

I need a little help for the redaction of a class. I want to add some item in my listView, and to do that I use a custom adapter found in this forum, but modified for my use :
public class AdvertisingAdapter extends cCursorAdapter {
private static final String ADMOB_PUBLISHER_ID = "YOUR_ADMOB_ID_HERE";
private final Activity activity;
private final cCursorAdapter delegate;
Context context;
static int rec = 15;
public AdvertisingAdapter(Activity activity, cCursorAdapter delegate, Context context, Cursor cursor)
{
super(context, cursor, 0);
this.activity = activity;
this.delegate = delegate;
this.context = context;
delegate.registerDataSetObserver(new DataSetObserver()
{
#Override
public void onChanged()
{
notifyDataSetChanged();
}
#Override
public void onInvalidated()
{
notifyDataSetInvalidated();
}
});
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (position == 0 || position % rec == 0)
{
j = j + 1 ;
if (convertView instanceof AdView)
{
notifyDataSetChanged();
return convertView;
}
else
{
AdView adView = new AdView(context);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Default layout params have to be converted to ListView compatible
// params otherwise there will be a ClassCastException.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params
= new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder().build();
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setAdSize(com.google.android.gms.ads.AdSize.BANNER);
adView.loadAd(adRequest);
notifyDataSetChanged();
return adView;
}
}
else
{
Log.i ("TEST AD ADAPTER", String.valueOf(j)
+ " " + String.valueOf(position)
+ " " + String.valueOf(getNbreAd())
+ " " + String.valueOf(getNbrePos(position))
+ " " + String.valueOf(getCount()));
return delegate.getView(position - getNbrePos(position), convertView, parent);
}
}
public int getNbreAd(){
int l = delegate.getCount();
return (l / rec) + 1;
}
public int getNbrePos(int position){
int k = (position/rec) + 1;
return k;
}
#Override
public int getCount()
{
return delegate.getCount() + getNbreAd();
}
#Override
public Object getItem(int i)
{
return delegate.getItem(i - 1);
}
#Override
public long getItemId(int i)
{
return delegate.getItemId(i - 1);
}
#Override
public int getViewTypeCount()
{
return delegate.getViewTypeCount() + 1;
}
#Override
public int getItemViewType(int position)
{
return position == 0 ? delegate.getViewTypeCount()
: delegate.getItemViewType(position - 1);
}
#Override
public boolean areAllItemsEnabled()
{
return false;
}
#Override
public boolean isEnabled(int position)
{
return position != 0 && delegate.isEnabled(position - 1);
}
}
My cCursorAdapter :
public class cCursorAdapter extends android.widget.CursorAdapter {
DataHelper mDBHelper;
public cCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_result2, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor){
// Find fields to populate in inflated template
TextView nameResult = (TextView) view.findViewById(R.id.nameResult2);
TextView ageG = (TextView) view.findViewById(R.id.ageG2);
TextView nbreJoueur = (TextView) view.findViewById(R.id.nbreJoueur2);
TextView timeResult = (TextView) view.findViewById(R.id.time2);
ImageView placeGD = (ImageView) view.findViewById(R.id.placeD2);
TextView IDR2 = (TextView) view.findViewById(R.id.IDR2);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String place = cursor.getString(cursor.getColumnIndexOrThrow("place"));
int ageMin = cursor.getInt(cursor.getColumnIndexOrThrow("agemin"));
int ageMax = cursor.getInt(cursor.getColumnIndexOrThrow("agemax"));
int nbreMin = cursor.getInt(cursor.getColumnIndexOrThrow("nbremin"));
int nbreMax = cursor.getInt(cursor.getColumnIndexOrThrow("nbremax"));
int time = cursor.getInt(cursor.getColumnIndexOrThrow("time"));
final int ID = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
// Populate fields with extracted properties
nameResult.setText(name);
ageG.setText(String.valueOf(ageMin) + " - " + String.valueOf(ageMax));
nbreJoueur.setText(String.valueOf(nbreMin) + " - " + String.valueOf(nbreMax));
timeResult.setText(String.valueOf(time));
IDR2.setText(String.valueOf(ID));
if (place.equals("extérieur")) {
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_wb_sunny_black_24dp);
placeGD.setImageDrawable(placeD);
} else if (place.equals("intérieur")){
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_event_seat_black_24dp);
placeGD.setImageDrawable(placeD);
} else if (place.equals("partout")) {
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_explore_black_24dp);
placeGD.setImageDrawable(placeD);
}
//Cacher l'ID (c'est pas joli)
IDR2.setVisibility(View.INVISIBLE);
}
//Override the convert to string sequence
#Override
public CharSequence convertToString(Cursor cursor){
final int colIndex = cursor.getColumnIndexOrThrow("name");
return cursor.getString(colIndex);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint)
{
Cursor currentCursor = null;
if (getFilterQueryProvider() != null)
{
return getFilterQueryProvider().runQuery(constraint);
}
String args = "";
if (constraint != null)
{
args = constraint.toString();
}
//Initialize that shit
mDBHelper = new DataHelper(MainActivity.mContext);
currentCursor = mDBHelper.getNameCursor(args);
return currentCursor;
}
}
In a certain way, it works. But when I swipe the listView too fast, I have this error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.tanoshi.traveler.doctorgamesfree.cCursorAdapter.bindView(cCursorAdapter.java:57)
at android.widget.CursorAdapter.getView(CursorAdapter.java:254)
at com.tanoshi.traveler.doctorgamesfree.AdvertisingAdapter.getView(AdvertisingAdapter.java:102)
I think it is becausemy listView try to load an item in a view which is not loaded.
How can I do to fix this ?
Thank you for your time.

Trying to get the _id when an item in gridview is clicked getting a cast exception

I am trying to get the _id field from the cursor when an item in my Grid View is clicked, the same code is working fine in a listview but does not seem to work here:
Class level:
CurAdapter Cur;
GridView grid;
onCreate:
Cursor mCur = dbHelper.contactsQuery();
grid = (GridView)rootView.findViewById(R.id.gridview);
Cur = new CurAdapter(getActivity(), mCur,0);
grid.setAdapter(Cur);
grid.setTextFilterEnabled(true);
onCLick:
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
System.out.println(id);
Cursor cursor = (Cursor) grid.getItemAtPosition(position);
}
});
My CustomAdapter:
private class CurAdapter extends CursorAdapter{
public CurAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.item_text);
tv.setTypeface(helv_light);
final RoundedImageView iv = (RoundedImageView) view.findViewById(R.id.item_image);
String name = (cursor.getString(cursor.getColumnIndexOrThrow("Name")));
image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
String isAdhoc = (cursor.getString(cursor.getColumnIndexOrThrow("isAdhoc")));
if(isAdhoc.equals("1")){
boolean check = false;
String frName = null;
Cursor mCur = dbHelper.friendsName(name);
if(mCur != null && mCur.moveToFirst()){
do{
frName = mCur.getString(mCur.getColumnIndex("FriendsName"));
if(frName != null){
if(frName.equalsIgnoreCase(selfName)){
check = false;
}else {
check = true;
}
}
}while (mCur.moveToNext());
}
if(check){
name = name+" "+"("+frName+"'s"+" pet)";
}
}
tv.setText(name);
if((image.contains("jpg") || image.contains("png")) && image.contains("adhoc") != true){
image = "file://"+image;
}
final DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.icon_default)
.showImageForEmptyUri(R.drawable.icon_default)
.showImageOnFail(R.drawable.icon_default)
.resetViewBeforeLoading(true)
.cacheInMemory(true) // default
.cacheOnDisk(true) // default
.build();
ImageLoader.getInstance().displayImage(image, iv, options);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.grid_layout, null);
return view;
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return position;
}
}
My Problem:
11-10 14:51:47.989: E/AndroidRuntime(11194): java.lang.ClassCastException: java.lang.Integer cannot be cast to android.database.Cursor
11-10 14:51:47.989: E/AndroidRuntime(11194): at com.example.FragmentTab3$1.onItemClick(FragmentTab3.java:125)
you are getting the ClassCastException because you are overriding getItem
public Object getItem(int position) {
return position;
}
and in your case it is returning an int not the cursor. You can delete it and use the parent implementation of getItem (which should return the Cursor at position)
Exception is due to return int from getItem(..) as mentioned by blackbelt
This may also help you to get ID of the record - change getItemId(..) this way:
public long getItemId(int position) {
mCur.moveToPosition(position);
return mCur.getLong(mCur.getColumnIndex(BaseColumns._ID));
}

Android listview with header layout

I am rephrasing my question. Please bear with me.
I have a Cursor, which has carNum and tasks needs to be done on that. So carNum repeats in table. Right now I am using SimpleCursorAdapter and displaying all the info as a listitem. What I would like to do is set carNum as a header of a list and tasks need to be done as listitems. In addition to this, I would like to make header it's own layout so that I can display carNum and some info about it. So now where should I start ?
How should I get distinct carNum from Cursor and make that as header ? And then get listitem for that ?
Here is the .java
public class MyTask extends Activity{
String empid;
ListView list;
Cursor cursor = null;
TextView text;
private DbAdapter_Assignment assignment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
empid = getIntent().getExtras().getString("EmpID");
getData(empid);
}
public void getData(final String empid)
{
assignment = new DbAdapter_Assignment(getBaseContext());
assignment.open();
cursor = assignment.getAcceptedTasks(empid);
startManagingCursor(cursor);
text = (TextView) findViewById(R.id.employeename);
text.setText(getEmployeeName(empid) + " has "+ Integer.toString (cursor.getCount()) + " tasks assigned." );
list = (ListView) findViewById(R.id.mytasklist);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int arg2,
long arg3) {
}
});
SimpleCursorAdapter adapter = new SimpleCursorAdapter (this, R.layout.mytaskslayout, cursor, new String[] {"A","B", "C", "D", "E", "F"}, new int[] {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e, R.id.f});
list.setAdapter(adapter);
extend SimpleCursorAdapter
Build list of header indexes in the constructor
c.moveToFirst();
int headerIndex = -1;
String headerValue = null;
do {
headerIndex++;
String header = c.getString(getColumnClass());
if (!header.equalsIgnoreCase(headerValue)) {
mHeaderIndexes.add(headerIndex);
headerValue = header;
headerIndex++;
}
}while (c.moveToNext());
c.moveToFirst();
mDataCount = c.getCount()+mHeaderIndexes.size();
Override methods
#Override
public int getCount() {
return mDataCount;
}
#Override
public int getItemViewType(int position) {
if (mHeaderIndexes.contains(position)) {
return TYPE_HEADER_ROW;
}
return TYPE_ROW;
}
#Override
public Object getItem(int position) {
if (mHeaderIndexes.contains(position)) {
// for header row need return first row with data for this group
getCursor().moveToPosition(position-mHeaderIndexes.indexOf(position));
}
else {
for (int i = 0; i < mHeaderIndexes.size(); i++) {
if (mHeaderIndexes.get(i) > position) {
// need move back by number of headers before position
getCursor().moveToPosition(position - i);
break;
}
}
if (position>mHeaderIndexes.get(mHeaderIndexes.size()-1)) {
// if position is in the last group (position >last group header position)
// move back by number of headers
getCursor().moveToPosition(position - mHeaderIndexes.size());
}
}
return getCursor();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public boolean isEnabled(int position) {
return !mHeaderIndexes.contains(position);
}
Implement getView()
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
Cursor cursor = (Cursor) getItem(position);
View view = convertView;
if (type==TYPE_HEADER_ROW) {
boolean isHeader = view!=null && view.findViewById(R.id.title)!=null;
if (!isHeader) {
view = mInflater.inflate(R.layout.row_my_header, null);
}
TextView header = view.findViewById(R.id.title);
header.setText(...);
}
else {
if (view==null) {
view = mInflater.inflate(R.layout.row_my_data, null);
}
// fill data row
}
return view;
}

Android - How to make an activity to load faster?

I am currently working on an SMS app which will be quite similar to stock sms app.
But the problem is my app is loading much slower than the stock(inbuilt) app.
Here is my app's code :-
public class ThreadData extends ListActivity
{
private static final Uri SMS_URI = Uri.parse("content://sms");
ArrayList<String> bodies = new ArrayList<String>();
MySMSAdapter adapter;
String name;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.threadlist);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
name = extras.getString("address");
}
Cursor cursor = getContentResolver().query(SMS_URI, null, null, null, "date ASC");
startManagingCursor(cursor);
while (cursor.moveToNext())
{
String Id = cursor.getString(cursor.getColumnIndex("_id"));
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
String personName = getPersonName(Id, address);
if(personName.equals(name))
{
bodies.add(body);
}
}
//adapter = new MySMSAdapter(this, bodies);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.sms_inbox, R.id.row, bodies);
ListView listView = getListView();
listView.setAdapter(adapter);
}
public String getPersonName(String id, String address)
{
if(id==null)
{
if(address != null)
{
return PhoneNumberUtils.formatNumber(address);
}
else
{
return null;
}
}
Cursor c = this.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address),
new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
if(c != null)
{
try
{
if(c.getCount() > 0)
{
c.moveToFirst();
return c.getString(0);
}
}
finally
{
c.close();
}
}
if(address != null)
{
return PhoneNumberUtils.formatNumber(address);
}
return null;
}
}
My custom adapter :-
public class MySMSAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<String> data;
LayoutInflater inflater;
public MySMSAdapter(Activity a, ArrayList<String> arrayList)
{
activity = a;
data = arrayList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return data.size(); //To change body of implemented methods use File | Settings | File Templates.
}
public Object getItem(int i)
{
return data.get(i); //To change body of implemented methods use File | Settings | File Templates.
}
public long getItemId(int i)
{
return i;
}
public static class ViewHolder
{
public TextView textView;
}
public View getView(final int i, View view, ViewGroup viewGroup)
{
View row = view;
final ViewHolder holder;
if(view==null)
{
row = inflater.inflate(R.layout.sms_inbox, viewGroup, false);
holder = new ViewHolder();
holder.textView = (TextView)row.findViewById(R.id.row);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
holder.textView.setText(data.get(i));
return row;
}
}
In my class i tried loading List with both the options(custom adapter as well as ArrayAdapter) But in both case my app is loading very slow. How to load it faster? I may prefer solution for my custom adapter as in future i may need few things to add in my layout like photos and other stuff.
Thanks. Please Help!!
You can use http://developer.android.com/guide/developing/tools/traceview.html profiler to localize performance issues. My guess the problem is you are doing disk operations (Cursor cursor = getContentResolver().query(...)) synchronously. Try to make this assync using AssyncTask i.e.

Categories

Resources