Refreshing a Fragment after the tab has been selected - android

When my fragment is built, I build the View from information in my local Database. Other tabs can modify this information, and when the user selects the tab, I would like the new information to be reflected.
public class RunningTotal extends SherlockFragment {
public static final String TAG = "Running Total";
private LinearLayout lv;
public View onCreateView(LayoutInflater li, ViewGroup vg,
Bundle savedInstanceState) {
SalesDataSource sds = BarcodeSaleTracker.SDS;
ArrayList<Item> items = sds.getAllItems();
String[] totals = sds.getPersonValues();
int totalsPosition = 0;
Log.v(TAG, "Items Length: " + items.size());
lv = new LinearLayout(this.getActivity());
String lastPerson = "";
if (items.size() > 0) {
for (Item i : items) {
if (lastPerson.equalsIgnoreCase(i.getPerson()) == false) {
lastPerson = i.getPerson();
TextView tv = (TextView) li.inflate(R.layout.list_title,
lv, false);
tv.setText(totals[totalsPosition]);
totalsPosition++;
lv.addView(tv);
}
TextView listItem = (TextView) li.inflate(R.layout.list_item,
lv, false);
listItem.setText(i.toString());
lv.addView(listItem);
}
} else {
TextView noItems = (TextView) li.inflate(R.layout.list_title, lv,
false);
noItems.setText(R.string.no_items);
lv.addView(noItems);
}
return lv;
}
}
It's a tabbed format, nearly identical to the Sherlock example:
public class BarcodeSaleTracker extends SherlockFragmentActivity {
TabHost mTabHost;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
public static SalesDataSource SDS;
public BarcodeSaleTracker() {
}
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Sherlock___Theme);
super.onCreate(savedInstanceState);
SDS = new SalesDataSource(this);
SDS.open();
if (savedInstanceState == null) {
setContentView(R.layout.fragment_tabs_pager);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (ViewPager) findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
mTabsAdapter.addTab(mTabHost.newTabSpec("current_sale")
.setIndicator("Current Sale"), Current_Sale.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("running_total")
.setIndicator("Running Total"), RunningTotal.class, null);
mTabsAdapter.addTab(
mTabHost.newTabSpec("stats").setIndicator("Stats"),
CountingFragment.class, null);
} else {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
I just don't know how to communicate to RunningTotal that it needs to update itself.
EDIT Added the source of all the data I ask from the database
public class SalesDataSource {
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
private String[] allColumns = { DatabaseHelper.COLUMN_ID,
DatabaseHelper.COLUMN_PERSON, DatabaseHelper.COLUMN_COST,
DatabaseHelper.COLUMN_ITEM };
public SalesDataSource(Context context) {
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
/**
* Creates an entry in the Database. Both a person and a cost are required.
* Item is not required. If one is not needed, simply pass null.
*
* #param person
* Who this sale belongs to.
* #param cost
* The amount (in pennies) that the sale was.
* #param item
* An optional description of the sold item
* #return The newly created Item.
*/
public Item addItem(String person, int cost, String item) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_PERSON, person);
values.put(DatabaseHelper.COLUMN_COST, cost);
values.put(DatabaseHelper.COLUMN_ITEM, item);
long insertId = database.insert(DatabaseHelper.TABLE_SALES, null,
values);
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES, allColumns,
DatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null,
null);
cursor.moveToFirst();
Item rv = cursorToItem(cursor);
cursor.close();
return rv;
}
public void addItems(List<Item> items) {
for (Item i : items) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_PERSON, i.getPerson());
values.put(DatabaseHelper.COLUMN_COST, i.getAmount());
values.put(DatabaseHelper.COLUMN_ITEM, i.getItem());
database.insert(DatabaseHelper.TABLE_SALES, null, values);
}
}
public ArrayList<Item> getAllItems() {
ArrayList<Item> items = new ArrayList<Item>();
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES, allColumns,
null, null, null, null, DatabaseHelper.COLUMN_PERSON);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Item item = cursorToItem(cursor);
items.add(item);
cursor.moveToNext();
}
cursor.close();
return items;
}
public String[] getPersonValues() {
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES,
new String[] { "SUM(" + DatabaseHelper.COLUMN_COST + ") AS " + DatabaseHelper.PERSON_SUM,
DatabaseHelper.COLUMN_PERSON }, null, null,
DatabaseHelper.COLUMN_PERSON, null, null);
String[] rv = new String[cursor.getCount()];
cursor.moveToFirst();
int pos = 0;
while (!cursor.isAfterLast()) {
String person = cursor.getString(1);
String money = Item.format(cursor.getInt(0));
rv[pos++] = person + ": " + money;
cursor.moveToNext();
}
cursor.close();
return rv;
}
public Item getMaxSale() {
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES,
new String[] { "MAX(" + DatabaseHelper.COLUMN_COST + ") AS " + DatabaseHelper.MAX_SALE,
DatabaseHelper.COLUMN_PERSON }, null, null, null, null,
null);
cursor.moveToFirst();
Item rv = cursorToItem(cursor);
cursor.close();
return rv;
}
public Item getMinSale() {
Cursor cursor = database.query(DatabaseHelper.TABLE_SALES,
new String[] { "MIN(" + DatabaseHelper.COLUMN_COST + ") AS " + DatabaseHelper.MIN_SALE,
DatabaseHelper.COLUMN_PERSON }, null, null, null, null,
null);
cursor.moveToFirst();
Item rv = cursorToItem(cursor);
cursor.close();
return rv;
}
private Item cursorToItem(Cursor cursor) {
Item item = new Item();
item.setId(cursor.getLong(0));
item.setPerson(cursor.getString(1));
item.setAmount(cursor.getInt(2));
item.setItem(cursor.getString(3));
return item;
}
}

Why not use a listfragment and loadermanager to manage the cursor object so that the list is automatically updated whenever the underlying data changes?

Related

Android cursor return empty contacts

I need to get all contacts that have at least a phone number. Android contacts may be picked from many accounts like gmail,skype,vibe etc. I made the classes i need to get the contacts i need. My problem that it gets anyway contacts that don't have at least 1 phone number and shows just their name and avatar. Can any1 say what I am doing wrong in my code? My code source is shared below.
ContactsActivity.class
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
selectionString = edtSearch.getText().toString();
String[] selectionArgs = {"%" + selectionString + "%", selectionString + "%", "%" + selectionString};
String selection = ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=='1'";
return new CursorLoader(this,
ContactsContract.Contacts.CONTENT_URI, // URI
null, // projection fields
selection, // the selection criteria
selectionArgs, // the selection args
ContactsContract.Contacts.DISPLAY_NAME + " ASC" // the sort order
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ContactsAdapter.createCheckedContacts(data.getCount());
contactsAdapter.setCursor(data);
contactsAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
contactsAdapter.swapCursor(null);
}
ContactsAdapter.class
public class ContactsAdapter extends CursorAdapter {
static boolean status = true;
private static boolean[] checkedContacts;
private static Context context;
private static Cursor cursor;
public ContactsAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
public static void setCursor(Cursor cursor) {
ContactsAdapter.cursor = cursor;
}
public static void createCheckedContacts(int count) {
checkedContacts = new boolean[count];
}
public static void saveSelectedContacts(ClientDao contactDao) {
for (int i = 0; i < checkedContacts.length; i++) {
if (checkedContacts[i]) {
cursor.moveToPosition(i);
DatabaseHelper.getInstance().saveClient(ContactUtils.cursorToContact(cursor, context), status);
status = !status;
}
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.contact_item, parent, false);
ViewHolder holder = new ViewHolder(convertView);
convertView.setTag(holder);
return convertView;
}
#Override
public void bindView(View convertView, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) convertView.getTag();
final Contact contact = ContactUtils.cursorToContact(cursor, context);
holder.tvName.setText(contact.getDisplayName());
if (isFirst(cursor)) {
holder.tvLetter.setVisibility(View.VISIBLE);
String letter = String.valueOf(Character.toUpperCase(contact.getDisplayName().charAt(0)));
holder.tvLetter.setText(letter);
} else {
holder.tvLetter.setVisibility(View.INVISIBLE);
}
convertView.setTag(convertView.getId(), contact);
if (!TextUtils.isEmpty(contact.getPhotoUri())) {
new ImageLoaderUtils.ContactImage(contact, convertView, holder.ivUserImage, context).execute();
} else {
holder.ivUserImage.setImageResource(R.drawable.ic_profile);
}
holder.inviteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ContactInvitationActivity_.class);
intent.putExtra("contact", contact);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
});
}
private boolean isFirst(Cursor cursor) {
Contact c1 = ContactUtils.cursorToContact(cursor, context);
if (cursor.getPosition() == 0)
return true;
cursor.moveToPrevious();
Contact c2 = ContactUtils.cursorToContact(cursor, context);
if (c1.getDisplayName() == null || c2.getDisplayName() == null)
return false;
if (Character.toUpperCase(c1.getDisplayName().charAt(0)) != Character.toUpperCase(c2.getDisplayName().charAt(0)))
return true;
return false;
}
private static class ViewHolder {
TextView tvName;
TextView tvLetter;
ImageView ivUserImage;
Button inviteBtn;
RelativeLayout rlContact;
private ViewHolder(View convertView) {
tvName = (TextView) convertView.findViewById(R.id.tvContactsName);
tvLetter = (TextView) convertView.findViewById(R.id.tvLetter);
ivUserImage = (ImageView) convertView.findViewById(R.id.ivUserIcon);
inviteBtn = (Button) convertView.findViewById(R.id.inviteBtn);
rlContact = (RelativeLayout) convertView.findViewById(R.id.rlContact);
}
}
}
ContactUtil.class
public class ContactUtils {
public static Contact cursorToContact(Cursor c, Context context) {
if (c == null || c.getPosition() < 0) return null;
Contact contactObj = new Contact();
try {
contactObj.setID(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
contactObj.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contactObj.setPhotoUri(c.getString(c.getColumnIndex(ContactsContract.Contacts.PHOTO_URI)));
contactObj.setPhoneNumber("");
contactObj.setEmail("");
setPhoneNumber(c, contactObj, context);
setEmail(contactObj, context);
} catch (Exception e) {
e.printStackTrace();
}
return contactObj;
}
public static void setPhoneNumber(Cursor c, Contact contactObj, Context context) {
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactObj.getID(), null, null);
phones.moveToFirst();
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
contactObj.setPhoneNumber(phoneNumber);
phones.close();
}
}
public static void setEmail(Contact contactObj, Context context) {
Cursor emailCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactObj.getID()}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contactObj.setEmail(email);
}
emailCur.close();
}
}

How to delete a row in SQLiteDatabase - Android Content Provider

I’m struggling to write a method that deletes a row from the SQLiteDatabase. I have a list of songs in a gridview where when a user clicks one of the items from the list the app will take them to my SongDetailFragment activity which contains more information about the song and a star button where if a song in in the database the star button is “switched on”, conversely if the item is NOT in the database the star button is “switched-off”
When a user click the star button I'm able to add a song successfully in the database and my star button is “switched-on”. Now I want to press the same button again and call deleteFromDB() to delete the song that was added to the database. So I have the following code in my onClick:
public void onClick(View v)
{
if (mIsFavourite) {
deleteFromDB();
}
else {
insertData();
mIsFavourite = true;
}
The problem is deleteFromDB() method is not working correctly as I can see that the song is not deleting from the database. I’m not sure what is the correct syntax to fix it.
Here is my method:
private void deleteFromDB() {
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.SongEntry.CONTENT_URI,
SongContract.SongEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
//switch off button
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
Here is my delete method snippet from my ContentProvider class:
#Override
public int delete(Uri uri, String selection, String[] selectionArgs){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int numDeleted;
switch(match){
case SONG:
numDeleted = db.delete(
SongContract.SongEntry.TABLE_NAME, selection, selectionArgs);
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
SongContract.SongEntry.TABLE_NAME + "'");
break;
case SONG_WITH_ID:
numDeleted = db.delete(SongContract.SongEntry.TABLE_NAME,
SongContract.SongEntry._ID + " = ?",
new String[]{String.valueOf(ContentUris.parseId(uri))});
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
SongContract.SongEntry.TABLE_NAME + "'");
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
return numDeleted;
}
Here is my SongDetailFragment:
public class SongDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private Song song;
private static final int CURSOR_LOADER_ID = 0;
ImageButton imgViewFavButton;
Boolean mIsFavourite = false;
// private final Context mContext;
public SongDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.song_fragment_detail, container, false);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra("song")) {
song = intent.getParcelableExtra("song");
//display title
((TextView) rootView.findViewById(R.id.detail_title_textview))
.setText(song.getTitle());
((TextView)rootView.findViewById(R.id.detail_description_textview))
.setText(song.getDescription());
((TextView)rootView.findViewById(R.id.song_releasedate_textview))
.setText(song.getReleaseDate());
double dRating = song.getVoteAverage();
String sRating = String.valueOf(dRating);
((TextView)rootView.findViewById(R.id.song_rating_textview))
.setText(sRating + "/10 ");
//show song poster
ImageView imageView = (ImageView) rootView.findViewById(R.id.song_detail_poster_imageview);
Picasso.with(getActivity()).load(song.getPoster()).into(imageView);
}
imgViewFavButton = (ImageButton) rootView.findViewById(R.id.imgFavBtn);
checkFavourites();
imgViewFavButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (mIsFavourite) {
deleteFromDB();
}
else {
insertData();
mIsFavourite = true;
}
}
});
return rootView;
}
// insert data into database
public void insertData(){
ContentValues songValues = new ContentValues();
songValues.put(SongContract.SongEntry.COLUMN_ID, song.getsong_id());
songValues.put(SongContract.SongEntry.COLUMN_IMAGE, song.getPoster());
songValues.put(SongContract.SongEntry.COLUMN_TITLE, song.getTitle());
songValues.put(SongContract.SongEntry.COLUMN_OVERVIEW, song.getDescription());
songValues.put(SongContract.SongEntry.COLUMN_RELEASEDATE, song.getReleaseDate());
songValues.put(SongContract.SongEntry.COLUMN_RATING, song.getVoteAverage().toString());
//Insert our ContentValues
getActivity().getContentResolver().insert(SongContract.SongEntry.CONTENT_URI,
songValues);
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
}
private void deleteFromDB() {
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.SongEntry.CONTENT_URI,
SongContract.SongEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
private void checkFavourites() {
Cursor c =
getActivity().getContentResolver().query(SongContract.SongEntry.CONTENT_URI,
null,
SongContract.SongEntry.COLUMN_ID + " = ?",
new String[]{song.getsong_id()},
null);
if (c != null) {
c.moveToFirst();
int index = c.getColumnIndex(SongContract.SongEntry.COLUMN_ID);
if (c.getCount() > 0 && c.getString(index).equals(song.getsong_id())) {
mIsFavourite = true;
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
}
else{
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
c.close();
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args){
return new CursorLoader(getActivity(),
SongContract.songEntry.CONTENT_URI,
null,
null,
null,
null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
// Set the cursor in our CursorAdapter once the Cursor is loaded
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
// reset CursorAdapter on Loader Reset
#Override
public void onLoaderReset(Loader<Cursor> loader){
}
}
Notice this line right here:
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.songEntry.CONTENT_URI,
SongContract.songEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
You set songValues to an empty ContentValues object, and later call getAsString() which will return null since it doesn't contain any key for song.getTitle().
Just change your array to have the song title, you don't need ContentValues here:
new String[]{song.getTitle()});

update two tables on click inside a listview and passing parameters for the update

Goodyear to everyone.
well, this is the question, i would like to understand the logic of the listview, and how to retrieve informations on the item clicked in it.
i have done and customized a bunch of tutorials to do this app, and now i'm trying to figure out what i'm doing in this ugly and dirty code.
i have a activity where it lists a series of questions, after you select a category, selecting a question, brings you to the next activity, where some answers are listed and the user could select one. I would like to list ONLY those questions that the user has to answer, instead of all, so i've added a new column to the categories table called "fatta" - "done" in english that i would like to change to 1 when the user clicks the answer of that question.
so the idea was to pass the id of the question, so in the activity where i list al the answers, i could update both the answers and the questions tables, to set to 1 the "done field".
but something goes wrong. here's the code:
The Activity:
public class sondaggioActivity extends ListActivity{
private static final String strdomanda = null;
private pollDataSource datasource;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindomanda);
long domanda = getIntent().getExtras().getLong("domanda");
TextView text = (TextView) findViewById(R.id.domanda);
String strdomanda = Long.toString(domanda);
// text.setText(strcategory);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getTestoRisposte(strdomanda);
// data? if (values.moveToFirst())
// System.out.println(values.getString(values.getColumnIndex("sondid")));
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_RISPOSTA // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
//values.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
datasource.setRispostaSelezionata(Long.toString(id));
datasource.setDomandaFatta(strdomanda);
datasource.close();
finish();
}
}
as you can see here at the end there is the onListItemClick where i use the strdomanda that i have defined at the top as private static final String strdomanda = null; the datasource is like this:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID,MySQLiteHelper.COLUMN_WEBID,MySQLiteHelper.COLUMN_FATTA, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID,MySQLiteHelper.COLUMN_WEBID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid, int webid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
values.put(MySQLiteHelper.COLUMN_WEBID, webid);
values.put(MySQLiteHelper.COLUMN_FATTA, "0");
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
public Cursor getDomanda(String id) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_ID + "=?",
new String[] { id }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
sondaggi.setwebid(cursor.getLong(3));
return sondaggi;
}
public Cursor getAllDomandeCategoria(String catid) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_CATID + "=?",
new String[] { catid }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
public Cursor getTestoRisposte(String strdomanda) {
List<testo_risposte> domande = new ArrayList<testo_risposte>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_TESTORISPOSTE,
allRisposteColumns,
MySQLiteHelper.COLUMN_SONDID + "=?",
new String[] { strdomanda }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
testo_risposte sondaggio = cursorToTestoRisposte(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private testo_risposte cursorToTestoRisposte(Cursor cursor) {
testo_risposte testo_risposte = new testo_risposte();
testo_risposte.setId(cursor.getLong(0));
testo_risposte.setCatid(cursor.getLong(1));
testo_risposte.setWebid(cursor.getLong(4));
testo_risposte.Setselezionata(cursor.getLong(2));
testo_risposte.setDomanda(cursor.getString(3));
return testo_risposte;
}
public void setRispostaSelezionata(String id) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_SELEZIONATA, "1");
database.update(MySQLiteHelper.TABLE_TESTORISPOSTE,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { id });
}
public void setDomandaFatta(String strdomanda) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_FATTA, "1");
database.update(MySQLiteHelper.TABLE_SONDAGGI,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { strdomanda });
}
}
but as i run the activity, only the first updadate gone good, the other one, the one with which i would like to "deactivate" the question... does nothing... i suppose that the way i pass the strdomanda is not the good way. Any help? Advice? thanks in advance.
SOLVED:
i have mistaken this line:
private static String strdomanda = null;
I have deleted the Final property and i have deleted the other declaration of the same variable...
now it works.

retrieve the ID (in the database) of the element the user have clicked on a listview

this is what i have done, to retrieve the id but it says that getIndexColumn is not defined in the cursor... what i'm doing wrong?
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor data = (Cursor)l.getItemAtPosition(position);
String cat = Cursor.getString(Cursor.getIndexColumn(MySQLiteHelper.COLUMN_ID));
Intent myIntent = new Intent(MainActivity.this, sondaggioActivity.class);
myIntent.putExtra("categoriaId", cat);
MainActivity.this.startActivity(myIntent);
}
this is the category class:
public class categorie {
private long id;
private String nome;
private long preferita;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public long getPreferita() {
return preferita;
}
public void setPreferita(long preferita) {
this.preferita = preferita;
}
// Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return nome;
}
}
and this is the datasource:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
return sondaggi;
}
}
the main activity:
public class MainActivity extends ListActivity {
private pollDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getAllCategorie();
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_NOME // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.add:
datasource.createCategoria("peppe");
break;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent myIntent = new Intent(MainActivity.this, sondaggioActivity.class);
myIntent.putExtra("categoriaId", id);
MainActivity.this.startActivity(myIntent);
//Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
I assume you have an activity with a list of categories, and onClick of a particular item you want to launch new activity with details of that Item.
I suggest you when you launch the listScreen, query all/some items and maintaine an arrayList of items and save that in some singleton class, then onClick of a particular item pass that index to detail screen via intent.putExtra("index", position) and on detail Screen get that index via getIntent().getIntExtra("index", -1) .now get details of that particular index from arraylist saved in singleton class.
This approach will reduce cost of querying every time from database and data will be available easily.
Change
Cursor data = (Cursor)l.getItemAtPosition(position);
String cat = Cursor.getString(Cursor.getIndexColumn(MySQLiteHelper.COLUMN_ID));
to
Cursor data = (Cursor)l.getItemAtPosition(position);
Long clid = data.getLong(data.getIndexColumn(MySQLiteHelper.COLUMN_ID));
String cat=Long.toString(clid);
those two lines:
Cursor data = (Cursor)l.getItemAtPosition(position);
String cat = Cursor.getString(Cursor.getIndexColumn(MySQLiteHelper.COLUMN_ID));
makes absolutely no sense at all! If you're using a CursorAdapter why are you creating an array of objects? If you're using a ArrayAdapter why are you getting data from cursor?
Also, Cursor don't have any static methods to be called like that. That shouldn't even compile.
If you're using a CursorAdater (or some class that extend it) you the id is passed to you long id here protected void onListItemClick(ListView l, View v, int position, long id)

update the listview after inserting a new record with simpleCursorAdapter - requery()

I understand the requery() mechanic, but i do not understand the implementation:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getAllCategorie();
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_NOME // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
}
public void onClick(View view) {
categorie categoria = null;
switch (view.getId()) {
case R.id.add:
categoria = datasource.createCategoria("pluto") ;
break;
case R.id.categoria_label:
break;
}
}
after the categoria = datasource.createCategoria("pluto"); i have to define another:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
PollDataSource:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
return sondaggi;
}
}
with the same inputs?? so basically I will have the same exact code in two different places of the same class... May I define a... "procedure" or a class? I'm sorry if I'm too naive, I'm a real noob at this :D
the requery cursor method is deprecated. but you're right you have to reload the cursor and then make sure that your new cursor is being presented to your ListView. for a quick 'n dirty solution, I suggest you make your adapter a field. and then use the following method:
private void requery() {
Cursor values = datasource.getAllCategorie();
adapter.changeCursor(values);
}
What it does is remake a cursor. then by calling changeCursor you swap the old cursor for the new one and the old one is closed automatically. at the very least, you save yourself from making a new adapter. The more sophicated approach with all the trim and fixes i suppose would be to implement a CursorLoader which would perform the process automatically when the database content has been changed.

Categories

Resources