I am trying to retrieve the values from the edit text input boxes and store them in a database. I am getting a null pointer exception and I am not sure why. Thanks in advance for the help :)
This is my code where I am retrieving the values and passing them as parameters to be stored in the database:
public class MyPage extends Activity {
final Context context = this;
public String stringName;
public int intAge;
public int intWeight;
public int intHeight;
public String stringGoal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_page);
final Button button = (Button) findViewById(R.id.btn_addInfo);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialogue_userinfo);
dialog.setTitle("Add Your Information");
Button dialogButton = (Button) dialog.findViewById(R.id.btnDone);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText textName = (EditText)findViewById(R.id.txtName);
stringName = textName.getText().toString();
EditText textAge = (EditText)findViewById(R.id.txtAge);
intAge = Integer.parseInt(textAge.getText().toString());
EditText textWeight = (EditText)findViewById(R.id.txtWeight);
intWeight = Integer.parseInt(textWeight.getText().toString());
EditText textHeight = (EditText)findViewById(R.id.txtHeight);
intHeight = Integer.parseInt(textHeight.getText().toString());
EditText textGoal = (EditText)findViewById(R.id.txtGoal);
stringGoal = textGoal.getText().toString();
DatabaseAccess();
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
}
});
}
private void DatabaseAccess(){
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting User
Log.d("Insert: ", "Inserting ..");
db.addUser(new User(stringName, intAge, intWeight, intHeight, stringGoal));
//db.addUser(new User("Peter Parker", 23, 50, 150, "Hi"));
// Reading all users
Log.d("Reading: ", "Reading all contacts..");
List<User> users = db.getAllUsers();
for (User us : users) {
String log = "Id: "+us.getId()+" ,Name: " + us.getName() + " ,Age: " + us.getAge()
+ " ,Weight: " + us.getWeight() + " ,Height: " + us.getHeight()
+ " ,Goal: " + us.getGoal()
+ " ,BMI: " + us.getBmi();
Log.d("Name: ", log);
}
}
}
if All EditText's inside Dialog dialogue_userinfo layout then use Dialog instance for initializing EditText's instances on Button click. do it as:
EditText textName = (EditText)dialog.findViewById(R.id.txtName);
stringName = textName.getText().toString();
EditText textAge = (EditText)dialog.findViewById(R.id.txtAge);
intAge = Integer.parseInt(textAge.getText().toString());
//....same for others...
getText will return Editable Object. If your edittext has no any characters, it maybe return the null Object. So you have to check whether getText() return a null object.
if(youreditView.getText() != null ) {
String content = youreditView.getText().toString();
}
Related
I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,
Error in this line
if (c1 != null & c1.getCount() != 0) {
MAinActivity.java
public class MainActivity extends Activity {
private ListView upcominglist;
private ListView todays;
private ListView eventhistory;
private ImageView addnewevent;
public ArrayList<ContactListItems> contactList;
public ContactListItems contactListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upcominglist=(ListView)findViewById(R.id.listview_upcoming);
todays=(ListView)findViewById(R.id.listview_todays);
eventhistory=(ListView)findViewById(R.id.listview_eventhistory);
addnewevent=(ImageView)findViewById(R.id.addneweventbutton);
addnewevent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
startActivity(intent);
}
});
contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
else
{
c1.close();
}
c1.close();
String first=contactListItems.getSlno();
System.out.println("First" + first);
String second=contactListItems.getNameofevent();
System.out.println("SEcond"+second);
String third=contactListItems.getDtofevent();
System.out.println("Third"+third);
String fourth=contactListItems.getTimeofevent();
System.out.println("Fourth"+fourth);
String fifth=contactListItems.getDuration();
System.out.println("Fifth"+fifth);
}
Addnewevent.java
public class AddNewEvent extends Activity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
static final int TIME_PICKER_ID = 11111;
int flag = 0;
private ImageView addnewdata;
private LinearLayout lnr;
private Button submit;
private EditText edtnmofevent;
private EditText edtdtofevent;
private EditText edttmofevent;
private EditText edtdurationofevent;
SqlHandler sqlHandler;
private ImageView datepicks;
private ImageView timepicks;
private Calendar cal;
private int hour;
private int min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_event);
sqlHandler = new SqlHandler(getApplicationContext());
addnewdata = (ImageView) findViewById(R.id.addnewdata);
submit = (Button) findViewById(R.id.btnsubmit);
edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);
datepicks = (ImageView) findViewById(R.id.calndrdat);
timepicks = (ImageView) findViewById(R.id.timepickrs);
cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(TIME_PICKER_ID);
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
.append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
try {
testDate1 = sdf123.parse(abs1);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
edtdtofevent.setText(DateFormat);
edtdtofevent.setFocusable(false);
edtdtofevent.setInputType(InputType.TYPE_NULL);
datepicks.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
addnewdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AddNewEvent.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
lnr = (LinearLayout) findViewById(R.id.addnewlinear);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(25, 0, 0, 0);
TextView valueTV = new TextView(AddNewEvent.this);
// valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
valueTV.setText(userInput.getText());
valueTV.setLayoutParams(lp);
valueTV.setTextSize(18);
valueTV.setTextColor(Color.parseColor("#2d6cae"));
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(25, 0, 25, 0);
lp1.height = 50;
EditText edtvalues = new EditText(AddNewEvent.this);
edtvalues.setBackgroundResource(R.drawable.rect_edt);
edtvalues.setLayoutParams(lp1);
lnr.addView(valueTV);
lnr.addView(edtvalues);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
startActivity(intent);
String nameofevent = edtnmofevent.getText().toString();
String dtofevent = edtdtofevent.getText().toString();
String timeofevent = edttmofevent.getText().toString();
String duration = edtdurationofevent.getText().toString();
String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
+ nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
sqlHandler.executeQuery(query);
System.out.println("Querys" + query);
}
});
}
SQL
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "nameofevent";
public static final String COLUMN3 = "dtofevent";
public static final String COLUMN4 = "timeofevent";
public static final String COLUMN5 = "duration";
/* public static final String COLUMN6 = "dlabl";
public static final String COLUMN7 = "dedt";*/
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + COLUMN1
+ " integer primary key autoincrement, " + COLUMN2
+ " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:
if (c1 != null & c1.getCount() != 0)
You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.
There is too much here to explain it all, so I will give you the flaws causing a null pointer exception.
I can see your method of programming is coming from worrying too much about closing things and clearing up
resources to a point, it's causing problems.
contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
// Move to the first entry.
c1.moveToFirst();
//if (c1.moveToNext()) {
// do {
// Continue while it has not passed the last entry.
while (!cursor.isAfterLast())
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
// Move the cursor along to the next entry.
cursor.moveToNext();
}
}
// Close cursor after while and within if (so you know it is not null).
c1.close();
}
else
{
// You can't close c1 if it is Null. This will throw and error. Lose the else.
c1.close();
}
// Move this to within your if statment.
c1.close();
From your code you provided in the chat.
Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.
public static Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (sqlDatabase.isOpen()) {
// You are closing the database.
sqlDatabase.close();
}
sqlDatabase = dbHelper.getWritableDatabase();
c1 = sqlDatabase.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.
In this userdetails.java i am creating creating a table by name userdetails and inserting values
public class userdetails extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userdetails);
Button dbsave = (Button)findViewById(R.id.save);
dbsave.setOnClickListener(this);
SQLiteDatabase db;
db = openOrCreateDatabase( "Student.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
try {
final String UserDetails = "CREATE TABLE IF NOT EXISTS UserDetails ("
+ "NAME,"
+ "MOB_NO,"
+ "Q_NO,"
+ "Q_ANS,"
+ "MAIL_ID,"
+ "PASSWD);";
db.execSQL(UserDetails);
Toast.makeText(userdetails.this, "table created ", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(userdetails.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();
}
}
public void onClick(View view){
SQLiteDatabase db;
if(view.getId()==R.id.save)
{
EditText e1 = (EditText) findViewById(R.id.editText1);
String s1=e1.getText().toString();
EditText e2 = (EditText) findViewById(R.id.editText2);
EditText e3 = (EditText) findViewById(R.id.editText3);
String s3=e3.getText().toString();
EditText e4 = (EditText) findViewById(R.id.editText4);
String s4=e4.getText().toString();
EditText e5 = (EditText) findViewById(R.id.editText5);
String s5=e5.getText().toString();
EditText e6 = (EditText) findViewById(R.id.editText6);
String s6 =e6.getText().toString();
// Toast.makeText(Databasedb.this, "table created ", Toast.LENGTH_LONG).show();
String sql =
"INSERT or replace INTO UserDetails (" +
"Name, " +
"Mob_no, " +
"Q_no, " +
"Q_ans,"+
"Mail_id,"+
"Passwd) " +
"VALUES('"+s1+"','"+e2+"','"+s6+"','"+s3+"','"+s4+"','"+s5+"')" ;
db = openOrCreateDatabase( "Student.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
db.execSQL(sql);
AlertDialog alertDialog = new AlertDialog.Builder(userdetails.this).create();
// alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("uservalues are successfully added/updated to the database");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(userdetails.this, Login.class);
userdetails.this.startActivity(intent);
}
});
alertDialog.show();
}}
}
and here is my login.java file from where i need to access the userdetails table
public class Login extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
Button exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(this);
TextView txt = (TextView) findViewById(R.id.sub);
txt.setOnClickListener(this);
TextView forgot = (TextView) findViewById(R.id.code);
forgot.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.login)
{
EditText p1 = (EditText)findViewById(R.id.inputpasswd);
String s = p1.getText().toString();
Intent intent1= new Intent(this,homepage.class);
startActivity(intent1);
}
else
if(view.getId()==R.id.sub)
{
Intent intent2 = new Intent(this, userdetails.class);
startActivity(intent2);
}
else
{
Intent intent3 = new Intent(this, Forgotpassword.class);
startActivity(intent3);
}
}
}
please any one help me to retrieve values(from login.java) from the database`and comapare that value from the user entered value
thanx in advance....
You don't.
You execute a query of the general form
SELECT COUNT(*) FROM USERS WHERE USERNAME = ? AND PASSWORD = ?
and see whether the count returned is 1 or 0.
That way it's the database that does the comparing.
Also you don't have to deal with details of the password hashing in your code, as you would if you received and compared yourself.
Also there is much less data movement.
Also this procedure means that you can't leak to the user whether his username or his password was incorrect in the event of a failure, which conforms with good security design practice.
To check whether user have entered the proper credentials or not. Use this following code.
String username="";
String password="";
Cursor c = mydb.rawQuery("select * from Users where Username="+username+ " and Password="+password);
if(c.getCount()>0){
Toast.makeText(getApplicationContext(), "Login Succesful",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_LONG).show();
}
The app i'm making displays user input before saving it. One of the spinners gets data from a database. When i press the "review" button my app crashes (something about a NullPointException) on this line
final String estStatus = estType[row];
Here is the code.
private void displayReviewDetails() {
// Get what the user entered
Spinner estSpinner = (Spinner) findViewById (R.id.est_spinner);
Spinner spinner = (Spinner) findViewById (R.id.ratingSpinner);
EditText mealCost = (EditText) findViewById (R.id.editTextMealCost);
EditText mealType = (EditText) findViewById (R.id.editTextMealType);
EditText comments = (EditText) findViewById (R.id.editTextComments);
DatePicker rDate = (DatePicker) findViewById (R.id.datePicker1);
// final so we can reference them in the anonymous inner class below
int row = estSpinner.getSelectedItemPosition();
final String estStatus = estType[row];
int row1 = spinner.getSelectedItemPosition();
final String ratingStatus = estRating[row1];
final String strMealCost = mealCost.getText().toString();
final String strMealType = mealType.getText().toString();
final String strComments = comments.getText().toString();
final String rateDate = rDate.getDayOfMonth() + "/"
+ (rDate.getMonth() + 1) + "/" + rDate.getYear();
// Create and display the Alert dialog
new AlertDialog.Builder(this)
.setTitle("Details entered")
.setMessage(
"\n " + estStatus +
"\n " + ratingStatus +
"\n " + strMealCost +
"\n " + strMealType +
"\n " + strComments +
"\n " + rateDate )
.setNeutralButton("Back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing - it will just close when clicked
}
})
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// save the details entered if "Save" button clicked
saveReviews(estStatus, ratingStatus, strMealCost, strMealType,
strComments, rateDate);
}
}).show();
You can also use getSelectedItem().toString();
When I try to retrieve some data from SQLite in android, the emulator stops working during the execution. This is my code:
public class StartTest extends Activity {
// Objects And Variables
public HtTester _testclass;
private CommentsDataSource datasource2;
private SQLiteDatabase db;
private String _select;
// User Information Variables
String _c1;
String _c2;
String _c3;
String _c4;
String _c5;
String _c6;
String _pregnant;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starttest);
// Casting Controls To variables
Button _strattest = (Button) findViewById(R.id.btnsendtest);
final EditText _systolic = (EditText) findViewById(R.id.etsystolic);
final EditText _diastolic = (EditText) findViewById(R.id.etdiastolic);
//CheckBox _pregnant = (CheckBox) findViewById(R.id.cbpregnant);
final TextView _result = (TextView) findViewById(R.id.tvresult);
//Start Test Button Operation
_strattest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
datasource2 = new CommentsDataSource();
db = datasource2.SQLiteDatabaseget(StartTest.this);
_select = "SELECT * FROM USERSTABLE WHERE _id=" + getIntent().getExtras().getString("USERID");
Cursor c1 = db.rawQuery(_select, null);
_c1 = getString(c1.getColumnIndex("USERC1"));
_c2 = getString(c1.getColumnIndex("USERC2"));
_c3 = getString(c1.getColumnIndex("USERC3"));
_c4 = getString(c1.getColumnIndex("USERC4"));
_c5 = getString(c1.getColumnIndex("USERC5"));
_c6 = getString(c1.getColumnIndex("USERC6"));
_result.setText(_c1 + "," +_c2 + "," +_c3 + "," +_c4 + "," +_c5+ "," +_c6 );
}
});
}
}
The error is:
02-25 22:06:43.290: E/AndroidRuntime(850): android.content.res.Resources$NotFoundException: String resource ID #0x8
I'm having a issue where when I go to the next activity and pass then data with the intent it is only showing me the last entry off the DB and not the clicked items info.
.java
public class TimsFavs extends ListActivity implements OnItemClickListener {
/** Called when the activity is first created. */
ArrayList<String> results = new ArrayList<String>();
// Database results
String col0,col1,col2,col3,col4,col5,col6,col7;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.timsfavs);
DBAdapter db = new DBAdapter(this);
//---get all Locations---
db.open();
Cursor c = db.getAllLocation();
if (c.moveToFirst())
{
do {
col0 = c.getString(c.getColumnIndex(DBAdapter.KEY_ROWID));
col1 = c.getString(1);
col2 = c.getString(2);
col3 = c.getString(3);
col4 = c.getString(4);
col5 = c.getString(5);
col6 = c.getString(6);
col7 = c.getString(7);
results.add(col0);
} while (c.moveToNext());
}
db.close();
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
ListView lv;
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.rgb(83, 05, 14));
lv.setOnItemClickListener((OnItemClickListener) this);
}
public void onItemClick(AdapterView<?> TimsFavs, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), TimsFavsMore.class);
i.putExtra("ct_id_pass", col0);
i.putExtra("ct_storeid_pass", col1);
i.putExtra("ct_address_pass", col2);
i.putExtra("ct_city_pass", col3);
i.putExtra("ct_province_pass", col4);
i.putExtra("ct_country_pass", col5);
i.putExtra("ct_pcode_pass", col6);
i.putExtra("ct_phnum_pass", col7);
startActivity(i);
finish();
}
}
and my other activity is
`public class TimsFavsMore extends Activity {
DBAdapter db = new DBAdapter(this);
String rowId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timsfavsmore);
Intent i = getIntent();
Bundle b = i.getExtras();
final String rowId = b.getString("ct_id_pass");
final String phnum = b.getString("ct_phnum_pass");
final String storeid = b.getString("ct_storeid_pass");
final String address = b.getString("ct_address_pass");
final String city = b.getString("ct_city_pass");
final String province = b.getString("ct_province_pass");
final String country = b.getString("ct_country_pass");
final String pcode = b.getString("ct_pcode_pass");
TextView title = (TextView) findViewById(R.id.textview);
title.setText(Html.fromHtml("<br>Row ID: " + rowId + "<br><b><u>Location Address:</u></b><br><br>Store #" + storeid + "<br><br>" + address + "<br>" + city + ", " + province + "<br>" + country +"<br>" + pcode +"<br><br><b><u>Contact Info:</b></u><br><br>" + phnum +"<br>"));
// open to Nav
final Button button1 = (Button) findViewById(R.id.gohere);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String uri = "google.navigation:q=Tim%20Hortons,%20" + address + ",%20" + city + ",%20" + province + ",%20" + pcode + "";
Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i2);
}
});
// open to maps
final Button button2 = (Button) findViewById(R.id.showmap);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String uri2 = "geo:0,0?q=Tim%20Hortons,%20" + address + ",%20" + city + ",%20" + province + ",%20" + pcode + "";
Intent i3 = new Intent(Intent.ACTION_VIEW, Uri.parse(uri2));
startActivity(i3);
}
});
// Add to My Timmies List
final Button button3 = (Button) findViewById(R.id.removefav);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//---add 2 SQLite---
db.open();
if (db.deleteLocation(rowId))
Toast.makeText(getApplicationContext(), " Delete successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Delete failed.",
Toast.LENGTH_LONG).show();
db.close();
Intent i = new Intent(getApplicationContext(), MyTimmies.class);
startActivity(i);
finish();
}
});
final Button button4 = (Button) findViewById(R.id.favsdone);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i4 = new Intent(getApplicationContext(), MyTimmies.class);
startActivity(i4);
finish();
}
});
}
}`
Any Ideas?
You are iterating through your cursor and assigning the values to your strings. when it completes the iteration, your strings only contain the last value you assigned and then you pass that.
You should bind your list to a SimpleCursorAdapter instead of creating a whole different string array. Then in your onClickListener, you can just pass the key that identifies your row of data in the database.