multiple variables, cursor or stringarray dilemma - android

i want to populate my userinterface elements with data from my database
reading the database happens over my according database class (AbezoeAdapter)
populating my userinterface is done by my mainclass (Bezoekrapporten)
now i am struggling with following code to get my idea working
package com.example.deceunincktechniekers;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.res.*;
import android.database.Cursor;
#SuppressLint("SimpleDateFormat") public class bezoekrapporten extends Activity
{
TextView controlelijn;
EditText scanzonedata;
String scanzonestring;
String sScan;
String Bezoeknummer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bezoekrapporten);
//////////////////////// here is some code missing///////////////////////////
private void vulbezoekrapportboxin(String bezoeknummer) {
ABezoeAdapter bezoe = new ABezoeAdapter(this);
TextView bezoekrapportnummer;
bezoekrapportnummer = (TextView) findViewById(R.id.boxbrBrnum);
TextView servicenummer;
servicenummer = (TextView) findViewById(R.id.boxbrServicenum);
TextView datum;
datum = (TextView) findViewById(R.id.boxbrBrdatum);
TextView klantnaam;
klantnaam = (TextView) findViewById(R.id.boxbrKlant);
TextView straatnaam;
straatnaam = (TextView) findViewById(R.id.boxbrAdres);
TextView gemeente;
gemeente = (TextView) findViewById(R.id.boxbrGemeente);
TextView machinenummer;
machinenummer = (TextView) findViewById(R.id.boxbrMachinenr);
TextView merk;
merk = (TextView) findViewById(R.id.boxbrMerk);
TextView serienummer;
serienummer = (TextView) findViewById(R.id.boxbrSerial);
if(bezoeknummer == null)
{
bezoekrapportnummer.setText("-----");
}
else
{
Cursor c =bezoe.leesgegevens(bezoeknummer);
if (c.moveToFirst()){
while(!c.isAfterLast()){
String data = c.getString(c.getColumnIndex("bezoekrapportdatum"));
controlelijn.setText(data);
c.moveToNext();
}
}
c.close();
bezoekrapportnummer.setText(bezoeknummer);
}
return;
}
and the code snippet from AbezoeAdapter
package com.example.deceunincktechniekers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;
import android.util.Log;
public class ABezoeAdapter extends ADbAdapter {
public static final String recordnummer = "RECNUM";
public static final String bezoekrapportnummer = "Z01";
public static final String bezoekrapportdatum = "Z02";
public static final String herstellingsoort = "Z03";
//////////////////here is some code missing///////////////////////////:
public static final String basisservicenummer = "Z27";
public static final String verzonden = "Z28";
public static final String[] allekolommen = new String[] {bezoekrapportnummer + " AS _id", bezoekrapportdatum,
herstellingsoort, totaleduur, servicenummer, ONBEKEND, klantnaam, adres, machinenummer, omschrijving,
duur, postcode, gemeente, merk, model, serienummer, opmerkingen, werkgereed, extratijd, urenstand, gecontroleerdbureel,
onderhoudsfiche, uitsplitsen, opmerkingbureel, ONBEKEND2, orderverwerkdatum, ordernummer, basisservicenummer, verzonden};
//////////////////////////////here is some code missing/////////////////////////////////////////////
public Cursor leesgegevens(String bezoeknummer) {
open();
Cursor c = onzedatabase.query(true, databasetabel, allekolommen,
"_id" + "=?", new String[] { bezoeknummer }, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
Log.i("cursor leesgegevens", c.toString());
sluit();
return c;
/////////////////////////////////////here is some code missing//////////////////
can anybody inform me with the best way of working to get the data from the database to my UI?
if i am already able to compile my code i get an error in my logcat that looks as follows:
11-24 15:58:34.089: E/AndroidRuntime(785): FATAL EXCEPTION: main
11-24 15:58:34.089: E/AndroidRuntime(785): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.deceunincktechniekers/com.example.deceunincktechniekers.bezoekrapporten}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

Here's how I did one of my adapters. First, here's the code that does the query:
private void query (long uuid)
{
// Fill list using adapter
String cols[] = { Instances.TITLE }; // dummy field; we will set all fields together in ViewBinder
int fields[] = { R.id.node_text };
cursorAdapter = new CursorAdapter (this,
R.layout.row_view,
null, // no cursor yet
cols,
fields,
Adapter.NO_SELECTION);
cursorAdapter.setViewBinder (new MyViewBinder(this));
// Setup the adapter filter - this does the query work.
cursorAdapter.setFilterQueryProvider (new FilterQueryProvider()
{
#Override
public Cursor runQuery (CharSequence constraint)
{
Cursor cursor = getContentResolver().query (...your params...);
return cursor;
}
});
listView.setAdapter (cursorAdapter);
listView.setTextFilterEnabled (true);
// Force initial query - notice we setup an adapter with a null cursor.
cursorAdapter.getFilter().filter (null);
}
Notice I did not subclass the adapter. Instead, I subclassed ViewBinder. Normally one lets each call to ViewBinder set one view at a time. I thought it would be more efficient to do all the views together. Here's how I did it:
private class MyViewBinder implements ViewBinder
{
#Override
public boolean setViewValue (View view, Cursor cursor, int column)
{
// Do all columns in one pass.
if (column != SelectAndroidEvent.instancesTitleCol)
throw new IllegalStateException ("viewbinder should only be called for title; " +
"col: " + column);
// Find encompassing layout.
ViewGroup parentView = (ViewGroup)view.getParent();
// Get fields from parentView.
TextView titleView = (TextView)view;
TextView field2 = (TextView)parentView.findViewById (R.id.field2);
...
// set all fields together - easier.
view.setText (cursor.getString (column);
field2.setText (cursor.getString (FIELD2_COL);
...
return true;
}
}
Hope this helps.

Related

Call list view lag while scrolling

I am working on sample of calls log application. In this application my fragment displays Dialed Type calls in a list. here in each list item it shows photo from contacts, Number, name and time. It is working fine but it lags while scrolling.
fragment code:
package com.example.vl.calllogs;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by vl on 12/29/2015.
*/
public class TabDialedFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
CursorAdapter mAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No Dialed Numbers");
mAdapter = new MyCursorAdapter(getActivity(), R.layout.fragment_tab_dialed, null, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
private static final String[] PROJECTION = {
CallLog.Calls._ID,
CallLog.Calls.DATE,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.CACHED_PHOTO_ID,
CallLog.Calls.NUMBER,
CallLog.Calls.DURATION
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri baseUri = CallLog.Calls.CONTENT_URI;
String selection = CallLog.Calls.TYPE + "= 2";
return new CursorLoader(getActivity(), baseUri, PROJECTION,selection, null, CallLog.Calls.DATE + " DESC" );
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
class MyCursorAdapter extends ResourceCursorAdapter{
MyCursorAdapter(Context context, int layout, Cursor cursor, int flags ){
super(context, layout,cursor,flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
String nameString = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
if(nameString == null || "".equals(nameString.trim())){
name.setText("Unknown");
}else{
name.setText(nameString);
}
TextView time = (TextView) view.findViewById(R.id.time);
String timeS = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
Date callDayTime = new Date(Long.valueOf(timeS));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
String str = simpleDateFormat.format(callDayTime);
String durationS = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
time.setText(String.format(getActivity().getResources().getString(R.string.thirdLine), str, durationS));
TextView number = (TextView) view.findViewById(R.id.number);
String numberS = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
number.setText(numberS);
int contactID = getContactIDFromNumber(numberS);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setImageBitmap(getPhoto(contactID+""));
}
public int getContactIDFromNumber(String contactNumber)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = -1;
Cursor contactLookupCursor = getActivity().getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext()){
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
private Bitmap getPhoto(String id){
Bitmap photo = null;
try{
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(
getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id).longValue()));
if(inputStream != null)
photo= BitmapFactory.decodeStream(inputStream);
}catch (Exception e){
}
return photo;
}
}
}
I feel it might be the problem of in efficient way of getting photo from Contacts. here I first get the contact_id and then I queried for the photo using contact ID. Is this the correct way?
Last queries are not working asynchronously. To make async what should I do?
There're three main performance issues on your bindView you should fix.
Most serious issue:
The call to private Bitmap getPhoto that is a SQLite operation followed by a disk loading operation. that takes several milliseconds to happen and is definitely lagging the UI.
Bad news is that background thread image loading and caching is a very complex topic and very difficult to code properly.
Good news is that nowadays we have loads of great libraries that does the work for you. Below is the code to load it using Picasso library
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
Picasso.with(getActivity()).load(uri).into(imageView);
Pretty bad issue:
The call public int getContactIDFromNumber is also doing an SQLite query and that's also pretty slow.
Unfortunately I don't have any major suggestion on how you should fix it. It's a slow operation and you should do in a background thread. It will be a major refactor to make it work from inside the adapter.
My suggestion is to extend CursorLoader and make it after it finishes load the cursor (but still on the background thread) to perform all those queries and keep it in some HashMap
Minor issues:
Use a Holder Pattern to avoid all those calls to findViewById(int).
Also avoid creating new objects inside bindView. For example, you should have only 1 private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm"); for the whole class and use this same instance all the time. Also have just 1 Date object for the Adapter and just call callDayTime.setTime(Long.valueOf(timeS));
Hope it helps.

In android, How can i display selected data from databse in list view??? i am using sqlite database

I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking

Android list view current position doesn't work properly

I'm Getting data from my database and pushing them into ListView to view all the data.
Inside my ListView I also have a TextView with the text "Like" in it. Now when I click the like text it will change to "Liked" and I'm updating my like status in my database.
Now my problem is that when i click the "Like" text, the text changes to "Liked" and also it is updated in DB. But also when I scroll through the List View, I can notice other lists' Like text is also changed to Liked. I'm not sure what's going wrong.
I've been trying to get around this problem for quite some days but had no success.
This is my adapter code. At the bottom you can see my onClickListener for the textview
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ForumAdapter extends ArrayAdapter<DiscussionList> {
private static List<DiscussionList> items = null;
public ForumAdapter(Context context, List<DiscussionList> items) {
super(context, R.layout.custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
public static DiscussionList getModelPosition(int position) {
return items.get(position);
}
public void refill(List<DiscussionList> items) {
items.clear();
items.addAll(items);
notifyDataSetChanged();
}
public static class ViewHolder {
WebView mywebviewholder;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.custom_list, null);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscussionList app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.dscTitle);
TextView categoryText = (TextView) v.findViewById(R.id.dscCategory);
TextView descriptionText = (TextView) v
.findViewById(R.id.dscDescription);
TextView timeText = (TextView) v.findViewById(R.id.dscTime);
TextView idText = (TextView) v.findViewById(R.id.dscDiscId);
final TextView likeText = (TextView) v.findViewById(R.id.likeText1);
String like_Status = app.getLikeStatus();
titleText.setText(app.getTitle());
categoryText.setText(app.getCategory());
descriptionText.setText(app.getDescription());
timeText.setText(app.getTime());
idText.setText(app.getDiscId());
if (like_Status == "null") {
likeText.setText("Like");
} else {
likeText.setText("Liked");
}
final String dId = app.getDiscId();
// onClick for image button inside list view
likeText.setTag(new Integer(position));
likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Integer myposition = (Integer) view.getTag();
// Toast.makeText(getContext(), "" + dId,
// Toast.LENGTH_SHORT)
// .show();
likeText.setText("Liked");
MainActivity val = new MainActivity();
val.updateLikeTable(dId);
}
});
}
return v;
}
}
And also this is my MainActivity.java file where i update the likes in database
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener {
public static String strTitle = "0", strCategory = "0",
strDescription = "0", strTime = "0", strDid = "0";
Collegemate_DB db = new Collegemate_DB(this);
int likeStatus = 1;
private ProgressDialog dialog;
public static String usId=null;
ImageButton imgButton;
List<DiscussionList> items = new ArrayList<DiscussionList>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_forum_topics);
usId = db.getCurrentuserId();
initView();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*
* On click listener to get values from DiscussionList class and send it
* to another activity when clicking on the list item
*/
ListView forumList = getListView();
forumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Get position of the clicked list item from adapter
String dTitle, dCategory, dDescription, dTime, dDid;
DiscussionList accessVar = ForumAdapter
.getModelPosition(position);
dTitle = accessVar.getTitle();
dCategory = accessVar.getCategory();
dDescription = accessVar.getDescription();
dTime = accessVar.getTime();
dDid = accessVar.getDiscId();
/*
* Storing the forum values in string and passing it to another
* activity
*/
String values[] = { dTitle, dCategory, dDescription, dTime,
dDid };
Intent i = new Intent(MainActivity.this, ForumFullView.class);
i.putExtra("sendData", values);
startActivity(i);
}
});
}
private void initView() {
// show progress dialog
Log.i("j","Inside Init");
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://example.com/mypath/listData.php?currentUser_id="
+ usId;
Log.i("Fetch Url : ", url);
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<DiscussionList> data) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// create new adapter
ListView forumList = getListView();
// set the adapter to list
ForumAdapter adapter = new ForumAdapter(this, data);
if (forumList.getAdapter() == null) {
//final ForumAdapter adapter = new ForumAdapter(this, data);
forumList.setAdapter(adapter);
} else {
((ForumAdapter) forumList.getAdapter()).refill(items);
}
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void updateLikeTable(String dId,List<DiscussionList> items) {
try {
String likeUrl = "http://example.com/mypath/createlike.php?discId="
+ dId + "&userId=" + usId + "&like_status=" + likeStatus;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(likeUrl));
client.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any help is appreciated.
Thanks in advance
The problem you're having is that the ListView widget recycles its views if it can. Once a view is off the screen from scrolling, it goes onto a garbage heap so that when a new view scrolls into place it can be reused, rather than requiring a fresh one to be inflated from scratch. That recycled view is the convertView parameter in the getView() method. When your ListView is first populating, convertView will always be null, since the garbage pile has nothing in it, so you're forced to inflate new views, but subsequent calls will likely have that parameter as non-null.
The practical result of this is that when a clicked view that's been set to "Liked" gets recycled, the TextView is still there and still populated with "Liked" rather than the presumed default of "Like". So if you click a view, then scroll down so it goes off the screen, it'll come back around and cause the bug you're seeing.
What you'll probably want to do to fix this is to set the text of likeText within getView() every time, based on what it is in your database. If the post has been liked, set it to "Liked", and if it hasn't, set it to "Like". It should just be one more line, assuming you have easy access to whether or not the post is liked from your DiscussionList object.
P.S. As a side note, hard-coded strings are typically frowned upon in Android, so you may want to move your "Liked" string into the resource files. It's not really necessary unless you're planning to do translations, but it's still good practice.

Column chart with sqllite Db values based on Spinner value chnage?

I am very new to this API.I have knowledge on doing samples with this API.after that my requirement is display the Column graph based on Spinner Values selection .the query table data is coming correctly the problem is not appending the latest values to the chart .
In My App i have one spinner name it as Customer Name:
when i change the spinner-value i am sending the Customer name to input parameter to sqllite and display the graph for that i write the following code.
package com.appulento.salestracking;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import com.appulento.salestrackingdb.DBAdapter;
import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartAxis;
import com.artfulbits.aiCharts.Base.ChartCollection;
import com.artfulbits.aiCharts.Base.ChartCollection.IChangeListener;
import com.artfulbits.aiCharts.Base.ChartNamedCollection;
import com.artfulbits.aiCharts.Base.ChartPalette;
import com.artfulbits.aiCharts.Base.ChartPoint;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Types.ChartTypes;
public class SalesTrackingByCustomer extends Activity {
private DBAdapter db;
private Spinner spinner1, spinner2;
private String[] prodctnames;
private String[] prodctnames1;
private double[] product_1;
private double[] product_2;
public int count;
public String custid;
public Sample customerdetails;
public ChartCollection<String> collection;
ChartArea area;
ChartArea area1;
private SimpleAdapter mSchedule;
Vector<String> vec_custid=new Vector<String>();
Vector<String> vec_oldno=new Vector<String>();
Vector<String> vec_productid=new Vector<String>();
Vector<String> vec_qty=new Vector<String>();
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bycustomers);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mListView=(ListView)findViewById(R.id.listView1);
prodctnames=new String[10];
product_1=new double[10];
prodctnames1=new String[10];
product_2=new double[10];
db=new DBAdapter(this);
final ChartView chartView = (ChartView) findViewById(R.id.chartView);
ChartPalette palette = new ChartPalette(0xffffd7e8);
chartView.setPalette(palette);
final ChartSeries product1 = new ChartSeries("P1", ChartTypes.Column);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int position=spinner1.getSelectedItemPosition();
System.out.println("=====ITEM POSITION======"+position);
final String selected=arg0.getItemAtPosition(arg2).toString();
System.out.println("=====IN SELECTED======"+selected);
//finish();
db.open();
Cursor customer=db.fetchorderCustomername(selected);
custid=customer.getString(0);
System.out.println("=====CUSTOMER NAME ID======"+custid);
Cursor cursor=db.fetchorderDetails(custid);
count=cursor.getCount();
System.out.println("=====COUNT======"+count);
int i=0;
while (i<count)
{
String productid=cursor.getString(1);
prodctnames[i]=productid;
String qty=cursor.getString(2);
product_1[i]=Double.parseDouble(qty);
System.out.println("=====PROID======"+prodctnames[i]+"=====QUANTITY======"+product_1[i]);
cursor.moveToNext();
i++;
}
for (int j = 0; j < count; j++)
{
ChartPoint point = product1.getPoints().addXY(j, product_1[j]);
point.setAxisLabel(prodctnames[j]);
}
if(position==0)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area = chartView.getAreas().get(0);
area.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
if(position==1)
{
chartView.refreshDrawableState();
chartView.getSeries().add(product1);
area1 = chartView.getAreas().get(0);
area1.getDefaultXAxis().setLabelsMode(ChartAxis.LabelsMode.SeriesLabels);
}
//area.refresh();
db.close();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
My problem is at first time Application Launch the graph is Displaying successfully when i change the Spinner value selection the app got closed and display the fallowing exception in my log cat:
java.security.InvalidParameterException: This name already presents at com.artfulbits.aiCharts.Base.ChartNamedCollection.validateName(SourceFile:128 ) at com.artfulbits.aiCharts.Base.ChartNamedCollection.validate
please see once and let me know where i am doing Mistake in my code.The dynamic vlaues is not appending to that chart in the above code.
Thanks in Advance....
The problem is that you're trying to add new area with the same name. I'm not exactly well versed in the API enough, but i'd imagine that the issue comes when you try this line a second time:
chartView.getSeries().add(product1);
I also noticed that you never used the following:
prodctnames1=new String[10];
product_2=new double[10];
If i could make a suggestion, perhaps it isn't best to have all your code in a click listener. maybe you can fill your datasets at the beginning and then only show the graphs upon using the spinner. Because if one clicks the spinner more than once, you have to go to the database to get the same information.

Android ListView problems

I can't get my ListView work. When i run emulator it doesn't display ListView with data from databse wihich I created.
I would like to insert data to database through EditText and then display data
Main Program
package test.test;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private ListView listview;
private TextView textview;
private Button button;
private EditText edittext;
SQLiteDatabase databas;
//private String[] test = {"abc","abc","abc", "abc", "abc", "abc"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> test2 = new ArrayList<String>();
listview = (ListView)findViewById(R.id.test);
textview = (TextView)findViewById(R.id.mm);
button = (Button)findViewById(R.id.kanp);
edittext = (EditText)findViewById(R.id.textetid);
databas = (new dbHelper(this)).getWritableDatabase();
final ContentValues values = new ContentValues();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable ord = edittext.getText();
String ordDb = ord.toString();
//String sql = "INSERT INTO ordlista (ord) " +
//"VALUES (" + ordDb + ")";
//databas.rawQuery(sql, null);
values.put("ord", ordDb);
long varde = databas.insert("ordlista", null, values);
String varde2 = Long.toString(varde);
textview.setText(varde2);
}
});
//#############################TORSDAG###############################
Cursor c = databas.rawQuery( "select ord from ordlista", null);
startManagingCursor(c);
int n = 1;
while(c.isBeforeFirst() == false){
String dbVarde = c.getString(n);
test2.add(dbVarde);
c.moveToNext();
n++;
}
ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test2);
listview.setAdapter(aa);
//listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, test));
}
}
You could try using a SimpleCursorAdapter and save the overhead of maintaining an ArrayAdapter. Rather than having to populate an ArrayList all the time, you can just create a Cursor against the query when you need it updated and set the ListView's adapter. A SimpleCursorAdapter also has the added benefit of handling the list item's population for you based on the columns you provide.
For example:
String[] fieldsFromDB = new String[] {"ord"};
int[] fieldsOnListItem = new int[] {android.R.id.text1};
Cursor c = databas.rawQuery("select ord from ordlista", null);
listview.setAdapter(new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fieldsFromDB,fieldsOnListItem));

Categories

Resources