statement and method to update sqlite database - android-sqlite

I need your help please. I've spent way too much time on this and I can only update the database if I specify the id number.
Click listview item and send data to new activity for editing
Edit data and return to listview activity. Simple right. hmmm.
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
Cursor cursor = (Cursor)listView.getItemAtPosition(position);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_TITLE));
String barcode = cursor.getString(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_BARCODE));
String rowId = cursor.getString(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_ROWID));
Intent movieEdit = new Intent(getBaseContext(), MovieEdit.class);
Bundle bundle = new Bundle();
bundle.putString("rowId", rowId);
bundle.putString("title", title);
bundle.putString("barcode", barcode);
movieEdit.putExtras(bundle);
startActivity(movieEdit);
Receive the intent from the listview activity:
if (this.getIntent().getExtras() != null) {
Bundle bundle = this.getIntent().getExtras();
editTitle.setText(bundle.getString("title"));
editBarcode.setText(bundle.getString("barcode"));
editId.setText(bundle.getString("rowId"));
}
The statement activated by a button:
case R.id.buttonSave:
mDb.open();
ContentValues values = new ContentValues();
values.put(MoviesDbAdapter.KEY_TITLE, title);
values.put(MoviesDbAdapter.KEY_BARCODE, barcode);
mDb.updateTitle("=?", title, barcode);
mDb.close();
The method in the MovieDbAdapter:
public boolean updateTitle(long rowId, String title, String barcode)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BARCODE, barcode);
return mDb.update(SQLITE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
I know this has been done to death but no matter what I try I just can't update the database with the new data.
Hope you can help guys.

change your code to the following
case R.id.buttonSave:
mDb.open();
mDb.updateTitle(rowId, title, barcode);
mDb.close();

Related

Espresso and Android contact picker

I try to add a contact with an Android contact picker by Espresso, but this does not work.
This is the command to invoke the contact picker:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, RC_PICK_CONTACT);
The contact picker is shown, when I run Espresso test. OK, now I try to select a specific contact entry by display name (e.g. "Jake"). Unfortunately I don't know how to accomplish this. I've tried the following:
onData(withItemContent("Jake")).inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))).perform(click());
I also tried this variation:
onView(withText("Jake")).inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))).perform(click());
No success with both approaches. As already mentioned the contact picker is shown, but nothing is selected.
Any idea?
What you're experiencing is normal behavior, since the contact picker belongs to an external activity, whose user interface cannot be manipulated. Trying to assert anything will result in the tests stalling for some time and ending up with a
android.support.test.espresso.NoActivityResumedException: No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?
However, say hello to the new born Espresso-Intents, which is here to save my reputation:
Using the intending API (cousin of Mockito.when), you can provide a
response for activities that are launched with startActivityForResult
UPDATE
Below is my current solution which works fine but would need some decent code clean up:
#Test
public void testContactPickerResult(){
Intent resultData = new Intent();
resultData.setData(getContactUriByName("Joah"));
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(toPackage("com.google.android.contacts")).respondWith(result);
onView(withId(R.id.contactPickerLauncher))
.check(matches(isDisplayed()))
.perform(click());
onView(withId(R.id.pickedContact))
.check(matches(withText(getContactNumberByName("Joah"))));
}
In the launching activity, I would handle the incoming intent with the contact Uri and do whatever is necessary with it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextView result = (TextView) findViewById(R.id.pickedContact);
if (requestCode == 42 && resultCode == RESULT_OK){
Uri contactUri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
cursor.moveToFirst();
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
result.setText(number);
}
}
Also, the helper methods, to be modified accordingly:
public Uri getContactUriByName(String contactName) {
Cursor cursor = mActivityRule.getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name.equals(contactName)) {
return Uri.withAppendedPath(ContactsContract.Data.CONTENT_URI, id);
}
}
}
return null;
}

Google Web Toolkit - How to prevent duplication of the records?

I am new in GWT. I am trying to use the cell table to do this. Here is my questions:
Name Gender
Ali M
Abu M
Siti F
page 1
Name Gender
Siti F
Noor F
Ahmad F
page 2
I use simple pager to do the paging function. Everything is ok except next page.
When i click next page, siti record appear 2 times.
How to prevent the name Siti not appear in page 2? Below are my code:
private static class Contact{
private final String name;
private final String gender;
public Contact(String name, String gender){
this.name = name;
this.gender = gender;
}
}
private static final List<Contact> CONTACTS = Arrays.asList(
new Contact("Ali","M"),
new Contact("Abu","M"),
new Contact("Siti","F"),
new Contact("Noor","F"),
new Contact("Ahmad","M")
);
public void onModuleLoad(){
final CellTable<Contact> table = new CellTable<Contact>();
table.setPageSize(3);
TextColumn<Contact> nameColumn = new TextColumn<Contact>(){
#Override
public String getValue(Contact object) {
return object.name;
}
};
TextColumn<Contact> genderColumn = new TextColumn<Contact>(){
#Override
public String getValue(Contact object) {
return object.gender;
}
};
table.addColumn(nameColumn, "Name");
table.addColumn(genderColumn, "Gender");
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>(){
#Override
protected void onRangeChanged(HasData<Contact> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
end = end >= CONTACTS.size() ? CONTACTS.size() : end;
List<Contact> sub = CONTACTS.subList(start,end);
updateRowData(start,sub);
}
};
provider.addDataDisplay(table);
provider.updateRowCount(CONTACTS.size(), true);
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
SimplePager pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true);
pager.setDisplay(table);
Please help me to solve this problem. Thanks.
You have faced most probably the gwt last page problem, described in the linked questions:
GWT - celltable with simple pager issue
SimplePager row count is working incorrectly
The solution here is to set:
setRangeLimited(false)
and the last page is paged correctly, ie. it contains only Noor and Ahmad.
So in conclusion: actually no duplication is present here, but a bug on pagination in case of the last page. You will observe the same behavior with also other amounts of data, but on my view point it would be always a last page issue only.

Is there a way to fill a listview in activity2 with info from a listview in activity1?

Activity 1 sends the info I want to Activity 2:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id)
{
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
final int item_id = cursor.getInt(cursor.getColumnIndex(GamesDbAdapter.KEY_ROWID));
String item_cursus = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_CURSUS));
String item_onderdeel = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_ONDERDEEL));
String item_tijd = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_TIJD));
String item_game = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_GAME));
String item_web = cursor.getString(cursor.getColumnIndex(GamesDbAdapter.KEY_WEB));
Intent intent = new Intent(actGames_FRONT_ListViewCursorAdaptorActivity.this, actGames_ALL_ListViewCursorAdaptorActivity.class);
intent.putExtra("cursus", item_cursus);
intent.putExtra("id", item_id);
intent.putExtra("game", item_game);
startActivity(intent);
Toast done =
Toast.makeText(getApplicationContext(), item_game, Toast.LENGTH_LONG);
done.show();
}
});
In Activity2 I want to display "game" in another listview, but setText doesn't work with Listview.
game = (TextView)findViewById(R.id.game);
Intent iin= getIntent();
Bundle c = iin.getExtras();
if(c!=null)
{
String item_game =(String) c.get("game");
game.setText(item_game);
}
String game_list = getIntent().getExtras().getString("game");
This is the simplecursoradapter in activity2:
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCursus();
// The desired columns to be bound
String[] cursus = new String[] {
GamesDbAdapter.KEY_CURSUS,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.front,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.games_row_front,
cursor,
cursus,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
And this is in my DBadapter:
public Cursor fetchGames(){
String[] args = {"********************" };
Cursor mCursor = mDb.query(SQLITE_TABLE, null,
"cursus = ?" , args, KEY_GAME, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
When I replace the *** with a static item from the database it works but I can't get it to work with the intent from the first activity. Is there a way to fill a listview with info from another listview in another activity?

trying to add some link cell in my GWT cellTable

I am trying to add a Link in my cell table (I just want the item to be underlined and mouse symbol change on hover)
and on click I just want to give a window Alert .
for that i have tried these Options : ( but no luck )
1)
final Hyperlink hyp = new Hyperlink("test", "test");
Column<EmployerJobs, Hyperlink> test = new Column<EmployerJobs, Hyperlink>(new HyperLinkCell())
{
#Override
public Hyperlink getValue(EmployerJobs object)
{
return hyp;
}
};
Problem with option 1 is , it takes me to navigation page "test", whereas I dont want to go any other page i just want a window alert.
2)
Column<EmployerJobs, SafeHtml> test = new Column<EmployerJobs, SafeHtml>(new SafeHtmlCell())
{
#Override
public SafeHtml getValue(EmployerJobs object)
{
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendEscaped("test");
return sb.toSafeHtml();
}
};
problem with option 2 is I dont know what exactly to return here and its not getting underlined.
3) at last i am trying to add anchor in my celltable with a compositecell(as ideally i want three different anchors in my ONE cell)
final Anchor anc = new Anchor();
ArrayList list = new ArrayList();
list.add(anc);
CompositeCell ancCell = new CompositeCell(list);
Column testColumn1 = new Column<EmployerJobs, Anchor>(ancCell) {
#Override
public Anchor getValue(EmployerJobs object) {
return anc;
}
};
Option 3 is giving some exception .
If you can help me get working any of the above option, I'll be grateful
Thanks
You are doing it totally wrong. You need to use ActionCell for stuff like this or create your own cell. Example code:
ActionCell.Delegate<String> delegate = new ActionCell.Delegate<String>(){
public void execute(String value) { //this method will be executed as soon as someone clicks the cell
Window.alert(value);
}
};
ActionCell<String> cell = new ActionCell<String>(safeHtmlTitle,delegate){
#Override
public void render(com.google.gwt.cell.client.Cell.Context context, //we need to render link instead of default button
String value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<a href='#'>");
sb.appendEscaped(value);
sb.appendHtmlConstant("</a>");
}
};
Column testColumn1 = new Column<EmployerJobs, String>(cell) {
#Override
public String getValue(EmployerJobs object) {
//we have to return a value which will be passed into the actioncell
return object.name;
}
};
I recommend to read official documentation for Cell Widgets, since it is pretty much everything what you need to know about cell widgets.

Setting ListGrid selection in SmartGWT with method "selectRecords(Record record)"

I'm trying to set the selected records of a ListGrid table object in SmartGWT using records, but I can't find any way of doing it. I want to select with record, not index. I want to use selectRecord(Record record) method.
As an example;
public void onModuleLoad()
{
VLayout main = new VLayout();
final ListGrid grid = new ListGrid();
grid.setHeight(500);
grid.setWidth(400);
grid.setFields(new ListGridField("name", "Name"));
grid.setData(createRecords());
final IButton button = new IButton("Select some");
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event)
{
grid.selectRecord(createRecord("orange"));
}
});
main.addMember(grid);
main.addMember(button);
RootPanel.get().add(main);
}
private ListGridRecord[] createRecords()
{
return new ListGridRecord[]{
createRecord("monkey"),
createRecord("banana"),
createRecord("orange"),
createRecord("sun")
};
}
private ListGridRecord createRecord(String name)
{
ListGridRecord record = new ListGridRecord();
record.setAttribute("name", name);
return record;
}
In this case I want to select orange, But this code select anything.
Is it posible? If possible how?
Thanks in advance.
Found this solution;
selectRecord(grid.getRecordList().find("name", "orange"));
There's a problem with your code:
When you write
grid.selectRecord(record);
it goes to search the same record instance that the grid has. If both instances of record are equal, only then & then it selects the record. Otherwise nothing happens as you're facing right now. Here what you need to do is:
ListGridRecord[] records = countryGrid.getRecords();
int i;
for (i = 0; i < records.length; i++)
{
if (records[i].getAttribute("name").equalsIgnoreCase("orange"))
{
break;
}
}
countryGrid.selectRecord(i);