Index 2 requested with size of 2 - android

I am newbie to android development and here is my first project of gridview database.
it show error "index 2 requested with size of 2"
I am using sqlite database db file
here is my code
Please help me!!!!!
public class MainActivity extends Activity {
SQLiteDatabase mydb;
GridView data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (GridView) findViewById(R.id.gridView1);
List<String> li = new ArrayList<String>();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,
li);
dataAdapter.setDropDownViewResource(R.layout.activity_main);
try {
mydb = openOrCreateDatabase(getString(R.string._sdcard_sales_db), MODE_PRIVATE, null);
Cursor cr = mydb.rawQuery("SELECT * FROM users", null);
if (cr != null) {
if (cr.moveToFirst()) {
do {
String desc = cr.getString(cr.getColumnIndex("user"));
li.add(desc);
} while (cr.moveToNext());
Toast.makeText(getApplicationContext(), cr.getString(cr.getColumnIndex("user")),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "no data",
Toast.LENGTH_LONG).show();
}
}
cr.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "ERROR" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}}
thanks in advance

do {
String desc = cr.getString(cr.getColumnIndex("user"));
li.add(desc);
} while (cr.moveToNext());
Toast.makeText(getApplicationContext(), cr.getString(cr.getColumnIndex("user")),
Toast.LENGTH_LONG).show();
After the do-while loop, the cursor cr points to a row after the last valid row.
Remove the Toast where you call getString() with an invalid cursor index, or change it to toast the information you actually want.

Related

SQLiteLog no such table in android using Sqllite Database

By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.

Loading Garbage values from Database to Listview

I want to Load my database data to the arraylist and then from arraylist to listview on button click but when I clicked the button it loads Garbage data to the listview. This is my code. What am I doing wrong?
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(Bookmarks.this, android.R.layout.simple_list_item_1, list);
String query = "Insert into WEB values('" + title.getText().toString() + "','" + address.getText().toString() + "')";
db.execSQL(query);
Toast.makeText(getApplicationContext(), "Bookmark Inserted", Toast.LENGTH_LONG);
try {
Cursor c = db.rawQuery("SELECT Title FROM WEB", null);
c.moveToFirst();
do {
String check = c.getString(c.getColumnIndex("Title"));
list.add(check);
}
while (c.moveToNext());
lv.setAdapter(adapter);
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG);
}
}
});
This is the screenshot of Layout...

Adding database enteries to list view

I am creating a database within my android application that allows users to enter assignment information. At the moment the information is stored but not listed as I would like. I am looking to add function to the View Assignments button so that it returns to the AssignmentsManager page and lists the entered assignments.
I believe I will have to use something like;
listView=(ListView)findViewById(R.id.listView1); //initialise the listview
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0); //initialise an ArrayAdapter
listView.setAdapter(listAdapter); //set the adapter to the listview
And to add assignments to list;
listAdapter.add(c.getString(0)+c.getString(1)+c.getString(2)+c.getString(3)+c.getString(4));
I am unsure how to implement this though. Below is my class to add the assignments;
public class addassignment extends Activity {
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
}
public void addAssignment(View v) {
Log.d("test", "adding");
// get data from form
EditText nameTxt = (EditText) findViewById(R.id.editTitle);
EditText dateTxt = (EditText) findViewById(R.id.editDuedate);
EditText courseTxt = (EditText) findViewById(R.id.editCourse);
EditText notesTxt = (EditText) findViewById(R.id.editNotes);
db.open();
long id = db.insertRecord(nameTxt.getText().toString(), dateTxt
.getText().toString(), courseTxt.getText().toString(), notesTxt
.getText().toString());
db.close();
nameTxt.setText("");
dateTxt.setText("");
courseTxt.setText("");
notesTxt.setText("");
Toast.makeText(addassignment.this, "Assignment Added",
Toast.LENGTH_LONG).show();
}
public void viewAssignments(View v) {
Intent i = new Intent(this, AssignmentManager.class);
startActivity(i);
}
}
Here is the Assignments Class where the list should be displayed;
public class AssignmentManager extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignmentmanager);
Button addBtn = (Button) findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AssignmentManager.this,
addassignment.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
// ---add an assignment---
db.open();
long id = db.insertRecord("Android App", "14/02/2015", "Networks",
"First Android Project");
id = db.insertRecord("Java Development", "5/02/2015", "Java",
"Complete Assignment");
db.close();
// ---get all Records---
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
/*
* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if
* (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this,
* "No Assignments found", Toast.LENGTH_LONG).show(); db.close();
*/
// ---update Record---
/*
* db.open(); if (db.updateRecord(1, "Android App", "29/02/2015",
* "Networks", "First Android Project")) Toast.makeText(this,
* "Update successful.", Toast.LENGTH_LONG).show(); else
* Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
* db.close();
*/
/*
* //---delete a Record--- db.open(); if (db.deleteRecord(1))
* Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
* else Toast.makeText(this, "Delete failed.",
* Toast.LENGTH_LONG).show(); db.close();
*/
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void DisplayRecord(Cursor c) {
Toast.makeText(
this,
"id: " + c.getString(0) + "\n" + "Title: " + c.getString(1)
+ "\n" + "Due Date: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
public void addAssignment(View view) {
Intent i = new Intent("addassignment");
startActivity(i);
Log.d("TAG", "Clicked");
}
}
Can anyone show me where I should implement the lists to add the functionality?
You're on the right track. I'd simplify the process if I were you, instead of initially adding assignments individually, add an ArrayList of assignments when you're creating your adapter:
listAdapter= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, assignmentArrayList);
// now set the adapter to the ListView
listView.setAdapter(listAdapter); //set the adapter to the listview
Once your adapter is set and you make any changes to it (add, remove, etc) make sure you call .notifyDataSetChanged() so it knows to refresh the list.
listAdapter.notifyDataSetChanged(); // notify the list adapter

deleting sqlite row using listview

I have a listview which connect to an sqlite database. at first it shows my sqlite fields. but my problem is,I can't delete row by setOnLongClickDelete().
error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1510)
codes:
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList() {
// setListAdapter(new ArrayAdapter<String>(this,R.layout.cartformat,results));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " +title+ ",Quantity: "+qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
try{ String currentString = results.get(position);
String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);
if(resultRegexMatcher.find()){
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3)));
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
database.delete("CART", whereClause, null);
database.close();
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
results.remove(position);
}
return true;
} catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;
}
}
} );
displayResultList();
}
}
following Toast works:
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
If you are able to successfully remove the data from the SQLite database then you simply make your listAdapter global and then adding the code
listAdapter.notifyDataSetChanged();
after
results.remove(position);
in your onItemLongClick. After this you can remove calling displayResultList(); in setOnLongClickDelete().

avoid that SQLite table is added in listview everytime the activity is launched

I'm trying to display the content of my SQLite table using SimpleAdapter and TableView.
It works just fine at first launch, but when i relaunch the Activity it adds the table one more time in the listView.
This happens everytime i launch the intent from my front menu.
It seems to me that the SimpleAdapter is stored from the last time, and added again when the intent is opend from the menu?
Maybe there is a way to reset the adapter everytime it is launched?
I'm new to programming and hope someone can help me:)
Some code:
static final ArrayList<HashMap<String,String>> results = new ArrayList<HashMap<String,String>>();
private String tableName = DBAdapter.tableName;
private SQLiteDatabase newDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
ListAdapter adapter = new SimpleAdapter(
this,
results,
R.layout.liste,
new String[] {"Name","LastName","Age"},
new int[] {R.id.item_id,R.id.item_name,R.id.item_tid}
);
setListAdapter(adapter);
}
private void openAndQueryDatabase() {
try {
DBAdapter dbHelper = new DBAdapter(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT Startnr, Navn, Tid FROM " +
tableName + " ORDER BY Startnr ASC" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
HashMap<String,String> list = new HashMap<String,String>();
String firstName = c.getString(c.getColumnIndex("Startnr"));
String lastName = c.getString(c.getColumnIndex("Navn"));
String age = c.getString(c.getColumnIndex("Tid"));
list.put("Name", "" + firstName);
list.put("LastName", "" + lastName);
list.put("Age", "" + age);
results.add(list);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.close();
}
}
Its because you have declared the "results" array list as a "static" variable.

Categories

Resources