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...
I couldn't get corresponds data from list view's item.
here i am using sms and email templates. when i click on sms or any email listviews item then it will open in edit text form db and then could update data and then store. corresponding with email or sms .i create fields into db for email and sms template such as
id, template_name, message, template_code(0,1) i.e. specifies which on i'm using either sms or email.
here is three activity ManageEmailTemplate, ManageSmsTemplate that intents to next activity i.e. SMSTemplateEdit
ManageEmailTemplate.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_email_template);
//-------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " +
Constants.KEY_ID_GREET + "," +
Constants.GREETING_NAME + "," +
Constants.GREETING_MESSAGE+ "," +
Constants.KEY_ID_SETUP_GREET +
" from " + Constants.TABLE_NAME_GREETINGS +
" where " + Constants.KEY_ID_SETUP_GREET + " = " + Constants.EMAIL_CODE;
c = dba.getResults( mQuery );
startManagingCursor(c);
String[] resultColumns;
if( c != null && c.moveToFirst()){
}
int[] textviews = new int[] {android.R.id.text1};
resultColumns = new String[] { Constants.GREETING_NAME};
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
//dba.close();
//-------------------------
// Create Email Templates
//setup Create Email Templates Listener
Button createEmailTemplatesButton = (Button) findViewById(R.id.create_email_template_button);
createEmailTemplatesButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
showCreateEmailTemplate();
}
});
}
private void showCreateEmailTemplate(){
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type","email");
//startActivity(i);
startActivityForResult(i, mRequestCode);
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter.getItem(position);
String name = c.getString(c.getColumnIndex( Constants.GREETING_NAME ));
final int template_id = c.getInt(c.getColumnIndex( Constants.KEY_ID_GREET ));
temp_id=String.valueOf(template_id);
goForEdit();
//confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageEmailTemplate.this,
EmailSMSTempEdit.class);
launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("Temp_id", temp_id);
editor.putString("template_type", "email");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
ManageSMSTemplate.java
public class ManageSMSTemplate extends
ActionBarListActivity {
private MyDB dba;
private Cursor c;
String temp_id;
private SimpleCursorAdapter mAdapter;
private int mRequestCode = 0000;
ListView lst;
private String mQuery;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
lst =(ListView)findViewById(android.R.id.list);
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_sms_template);
// -------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " + Constants.KEY_ID_GREET + ","
+ Constants.GREETING_NAME + ","
+ Constants.GREETING_MESSAGE + ","
+ Constants.KEY_ID_SETUP_GREET + " from "
+ Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.KEY_ID_SETUP_GREET
+ " = " + Constants.SMS_CODE;
c = dba.getResults(mQuery);
startManagingCursor(c);
String[] resultColumns;
if (c != null && c.moveToFirst()) {
}
int[] textviews = new int[] { android.R.id.text1 };
resultColumns = new String[] { Constants.GREETING_NAME };
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c,
resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
// -------------------------
// Create sms Templates
// setup Create SMS Templates Listener
Button createSMSTemplatesButton = (Button) findViewById(R.id.create_sms_template_button);
createSMSTemplatesButton
.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
showCreateSMSTemplate();
}
});
}
private void showCreateSMSTemplate()
{
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type", "sms");
startActivityForResult(i, mRequestCode);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode,
data);
Log.v("Crash",
"Returned from template creation in SMStemplate Manager");
if (mAdapter == null)
Log.d("Crash", "SMS-Manager - mAdapter is NULL");
else
Log.d("Crash",
"SMS-Manager - mAdapter is NOT Null");
if (requestCode == mRequestCode) {
if (resultCode == RESULT_OK) {
if (mAdapter.getCursor() != null)
mAdapter.getCursor().requery();
mAdapter.notifyDataSetChanged();
}
}
}
#Override
protected void onDestroy()
{
dba.close();
super.onDestroy();
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter
.getItem(position);
String name = c.getString(c
.getColumnIndex(Constants.GREETING_NAME));
final int template_id = c.getInt(c
.getColumnIndex(Constants.KEY_ID_GREET));
temp_id=String.valueOf(template_id);
goForEdit();
// confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageSMSTemplate.this,
EmailSMSTempEdit.class);
// Intent i = new Intent(ManageSMSTemplate.this, SMSTempEdit.class);
//i.putExtra("KeyId", temp_id.toString());
// startActivity(i);
// launchSMSTempEdit.putExtra("selection", temp_id.toString());
// Log.d("*** OUTBOUND INTENT: ", "" + launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", temp_id);
editor.putString("template_type", "sms");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
EmailSMSTempEdit.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_template);
// sms_key_id=getIntent().getStringExtra("id");
// String sms_key_id;
// if (savedInstanceState == null) {
// Bundle extras = getIntent().getExtras();
// if(extras == null) {
// sms_key_id= null;
// } else {
// sms_key_id= extras.getString("STRING_I_NEED");
// }
// } else {
// sms_key_id= (String) savedInstanceState.getSerializable("STRING_I_NEED");
// }
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sms_key_id = sharedPref.getString("userName", "Not Available");
mTemplateType=sharedPref.getString("template_type", "Not Available");
Toast.makeText(this, mTemplateType, Toast.LENGTH_LONG).show();
dba = new MyDB(this);
dba.open() ;
//array to hold values to show in spinner
nameTypeArr = new String[]{getString(R.string.insert_name_prompt),
getString(R.string.first_name),
getString(R.string.last_name)};
//get views from xml
mNameBox = (EditText) findViewById(R.id.template_name_box);
mSubjectBox = (EditText) findViewById(R.id.template_subject_box);
mMessageBox = (EditText) findViewById(R.id.template_message_box);
mInsertNameSpinner = (Spinner) findViewById(R.id.insert_name_here_spinner);
//create adapter for the spinner and set it
ArrayAdapter<String> mAdapter1=
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, nameTypeArr);
mAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mInsertNameSpinner.setAdapter(mAdapter1);
//listener for the spinner
mInsertNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//if the spinner has just been created, ignore this call to onItemSelected
if(spinnerBeingCreated == true){
spinnerBeingCreated = false;
return;
}
//what item did the user click in spinner
String typeOfName = parent.getItemAtPosition(pos).toString();
//based on user choice, insert corresponding placeholder in text
if(typeOfName.equals( getString(R.string.first_name) )){
insertAtCurrentLocation( getString(R.string.first_name_placeholder) );
}else if(typeOfName.equals( getString(R.string.last_name) )){
insertAtCurrentLocation( getString(R.string.last_name_placeholder) );
}
//reset the spinner item selection back to first one
mInsertNameSpinner.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
//if its a template for sms, hide the subject line
LinearLayout subjectarea = (LinearLayout) findViewById(R.id.template_subject_box_container);
if(mTemplateType.equals("sms")){
subjectarea.setVisibility(View.GONE);
} else if(mTemplateType.equals("email")){
subjectarea.setVisibility(View.VISIBLE);
}
fillData(sms_key_id);
//Save the template
//setup Save Template Listener
Button saveTemplateButton = (Button) findViewById(R.id.save_template_button);
saveTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// saveTemplate();
updateTemplate(sms_key_id);
}
});
//Cancel
//Cancel Listener
Button cancelTemplateButton = (Button) findViewById(R.id.cancel_template_button);
cancelTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
finish();
}
});
}
public void fillData(String sms_key_id) {
Toast.makeText(EmailSMSTempEdit.this, sms_key_id, Toast.LENGTH_LONG).show();
dba.open();
String queryStr =
"Select " +
"*" + " from " +
Constants.TABLE_NAME_GREETINGS +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
//Toast.makeText(this, queryStr, Toast.LENGTH_SHORT).show();
c = dba.getResults(queryStr);
startManagingCursor(c);
if(c.moveToFirst()){
do{
mNameBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
mMessageBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_GREET)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_SETUP_GREET)));
} while(c.moveToNext());
}
}
public void updateTemplate(String sms_key_id){
String subject = mSubjectBox.getText().toString();
String name = mNameBox.getText().toString();
String message = mMessageBox.getText().toString();
dba.open();
//if name is null or empty, don't save
if(name == null || name.equals("")){
Toast.makeText(this, R.string.empty_template_name_error, Toast.LENGTH_LONG).show();
return;
}
//whether its sms or email, requied fro db query
int messageTypeCode = -1; //for sms, it is 0. For email it is 1
if(mTemplateType.equals("email")){
message = subject + subjectMessageDelimiter + message; //|~| is the delimiter
messageTypeCode = Constants.EMAIL_CODE;
} else if(mTemplateType.equals("sms")){
messageTypeCode = Constants.SMS_CODE;
}
String Stmt = "update " +
Constants.TABLE_NAME_GREETINGS +
" set "+
Constants.GREETING_NAME+"='"+name + "',"+
Constants.GREETING_MESSAGE+"='"+message + "'," +
Constants.KEY_ID_SETUP_GREET+"='"+messageTypeCode +"'" +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
dba.execute(Stmt);
dba.close();
Toast.makeText(this, "Successfully updated Template: " + name, Toast.LENGTH_LONG).show();
//finish the activity
// setResult(RESULT_OK, null);
finish();
}
#Override
protected void onDestroy(){
//dba.close();
super.onDestroy();
}
//insert at currnet cursor location in subject or message field
private void insertAtCurrentLocation(String str){
int start, end;
if(mMessageBox.hasFocus()){
start = mMessageBox.getSelectionStart();
end = mMessageBox.getSelectionEnd();
mMessageBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
} else if(mSubjectBox.hasFocus()){
start = mSubjectBox.getSelectionStart();
end = mSubjectBox.getSelectionEnd();
mSubjectBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
}
}
private boolean alreadyExists(String templateName){
int type_code = -1;
if(mTemplateType.equals("sms")){
type_code = Constants.SMS_CODE;
} else if(mTemplateType.equals("email")){
type_code = Constants.EMAIL_CODE;
}
String query = "Select * from " + Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.GREETING_NAME + " = '" + templateName
+ "' AND " + Constants.KEY_ID_SETUP_GREET + "=" + type_code;
Cursor c = null;
Boolean exists = false;
dba.open();
try {
c = dba.getResults( query );
if (c != null) {
if (c.moveToFirst()) {
exists = (c.getCount() > 0);
} else {
exists = false;
}
}
} catch (Exception e) {
Log.e("CreateNewTemplate", "Error while checking if name already exists. Details: "+e.getMessage(), e);
e.printStackTrace();
} finally {
if (c != null)
c.close();
dba.close();
}
return exists;
}
}
move your cursor to the position of the list view item that you have clicked and then fetch the data from db using that cursor. Below is a small snippet:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(cursor!=null){
cursor.moveToPosition(position);
//do your stuff here....
cursor.close();
}
}
});
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.
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().
and good day. My project is having 2 activities, first one to insert data into the database which works well, but then I want to show a list view of the data within the database in another activity.
I've tried local data eg fred, george in an array and the list view works great however, when I try to use the database. The activity crashes. It seems that I am unable to use "database.open"
public class MyListActivity extends Activity{
DatabaseAdapter database;
//Creates item_details based on the ListItemDetails class
ListItemDetails item_details;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//Uses the arraylist and set the result
ArrayList<ListItemDetails> result = GetSearchResults();
ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new CustomListAdapter(getApplicationContext(),result));
}
private ArrayList<ListItemDetails> GetSearchResults() {
ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
item_details = new ListItemDetails();
/*
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
item_details.setFirstName(c.getString(1));
results.add(item_details);
} while (c.moveToNext());
}
*/
return results;
}
}
Here is the main activity. The database opens fine when I use the buttonShow, so I tried buttonTest and storing them into the list but it got a bit confusing for me.
public class FamousPersonActivity extends Activity {
EditText editFirstName, editLastName;
Button buttonAdd, buttonShow, buttonTest;
ListView lv;
ListItemDetails item_details;
DatabaseAdapter database;
int request_Code = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_famous_person);
database = new DatabaseAdapter(this);
lv = (ListView)findViewById(R.id.listView1);
//ArrayList<ListItemDetails> result = GetSearchResults();
//lv.setAdapter(new CustomListAdapter(getApplicationContext(),result));
editFirstName = (EditText)findViewById(R.id.editFirstName);
editLastName = (EditText)findViewById(R.id.editLastName);
buttonAdd = (Button)findViewById(R.id.buttonAdd);
buttonShow = (Button)findViewById(R.id.buttonShow);
buttonTest = (Button)findViewById(R.id.buttonTest);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "added to database", Toast.LENGTH_SHORT).show();
database.open();
long id = database.insertContact("Test Contact", "Test Email") ;
database.close();
}
});
buttonTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("com.id11020260.exercise6part2.MyListActivity");
startActivityForResult(i, request_Code);
}
});
buttonShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String destPath = "/data/data/" + getPackageName() +
"/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath + "/MyDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//---get all contacts---
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
database.close();
}
});
}
private ArrayList<ListItemDetails> GetSearchResults() {
ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
item_details = new ListItemDetails();
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
item_details.setFirstName(c.getString(1));
results.add(item_details);
} while (c.moveToNext());
database.close();
}
return results;
}
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();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.famous_person, menu);
return true;
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Email: " + c.getString(2),
Toast.LENGTH_LONG).show();
}
}
This is the stack trace, I'm not sure if this is entirely correct
Try this:-
lv.setListAdapter(new ArrayAdapter(MyListActivity.this,
android.R.layout.simple_list_item_1,result));