Error When Retrieving data from SQLite, Android - android

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

Related

Android Studio get data from sqlite

I had some problem about get data from sqlite different database.One database that save user's name and phone and they can update as they like. While another is house information but also contain user's name and phone.
My problem is i just realize that the phone that had been update in user database is not same with phone that previous store in house database. So i wanna call the user's phone from user database and use for phone call function and message function. But it does not work.And i trying to match the fullname that in user database with house database to call the phone data but still cant.
here is my call and message function
public class HouseDetail extends AppCompatActivity {
EditText etAddress,etDetail,etPhone;
TextView txType,txProperty,txPrice,txState,txTitle,txOther,txSize,txFullname;
ImageButton bPhone,bMessage;
String type,property,price,state,address,title,other,size,detail,fullnames,fullname,phone;
HousesDB db = new HousesDB(this);
Houses houses;
DatabaseOperations Udb = new DatabaseOperations(this);
PersonalData profileInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_house_detail);
txType = (TextView) findViewById(R.id.txTypes);
txProperty = (TextView) findViewById(R.id.txProperty);
txPrice = (TextView) findViewById(R.id.txPrice);
txState = (TextView) findViewById(R.id.txState);
etAddress = (EditText) findViewById(R.id.etAddress);
txTitle = (TextView) findViewById(R.id.txTitle);
txOther = (TextView) findViewById(R.id.txOther);
txSize = (TextView) findViewById(R.id.txSize);
txFullname = (TextView) findViewById(R.id.txFullname);
etPhone = (EditText) findViewById(R.id.etPhone);
etDetail = (EditText) findViewById(R.id.etDetail);
bPhone = (ImageButton) findViewById(R.id.bPhone);
bMessage = (ImageButton) findViewById(R.id.bMessage);
fullnames = txFullname.getText().toString();
type = txType.getText().toString();
property = txProperty.getText().toString();
price = txPrice.getText().toString();
state = txState.getText().toString();
address = etAddress.getText().toString();
title = txTitle.getText().toString();
other = txOther.getText().toString();
size = txSize.getText().toString();
detail = etDetail.getText().toString();
phone = etPhone.getText().toString();
Intent i = getIntent();
property = i.getStringExtra("house_property");
txProperty.setText(property);
houses = db.getInfo(property);
txType.setText(houses.getTypes());
txFullname.setText(houses.getFullname());
txPrice.setText(houses.getPrice());
txState.setText(houses.getState());
etAddress.setText(houses.getAddress());
txTitle.setText(houses.getTitle());
txOther.setText(houses.getOther());
txSize.setText(houses.getSize());
etDetail.setText(houses.getDetail());
this.fullnames = fullname;
profileInfo = Udb.getNumber(fullname);
etPhone.setText(profileInfo.get_phone());
bPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + etPhone));
startActivity(callIntent);
}
});
bMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + etPhone)));
}
});
}
Here is my user database that get the phone number
public PersonalData getNumber(String fullname)
{
SQLiteDatabase SQ = this.getWritableDatabase();
String query = "select FullName,Phone from "+ Table_NAME;
Cursor CR = SQ.rawQuery(query,null);
String a;
PersonalData info = new PersonalData();
if (CR.moveToFirst())
{
do {
a = CR.getString(0);
if (a.equals(fullname)) {
info._phone = CR.getString(1);
break;
}
}while (CR.moveToNext());
}
return info;
}
try this:
public PersonalData getNumber(String fullName) {
SQLiteDatabase database = this.getReadableDatabase();
String table = "YOUR TABLE NAME";
String[] columns = {
"FullName" ,
"Phone"
};
Cursor cursor = database.query(table , columns , null , null , null , null , null);
cursor.moveToPosition(-1);
PersonalData info = new PersonalData();
while (cursor.moveToNext()) {
String name = cursor.getString(0);
if (name.equals(fullName)) {
info._phone = cursor.getString(1);
break;
}
}
cursor.close();
return info;
}
Replace
a = CR.getString(0);
if (a.equals(fullname)) {
info._phone = CR.getString(1);
break;
}
with
a = CR.getString(CR.getColumnIndex("Fullname"));
if (a.equals("FullName")) {
info._phone = CR.getString(CR.getColumnIndex("Phone"));
break;
}
your data gotten by query maybe not be ordered as you want,in your case that is, the result maybe not in "Fullname,Phone",so you should use getColumnIndex() to get data for each column.

Nullpointer exception while using SQLite

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.

Android SQLite Database table - Created table.But error log says no such table

I am developing a shopping cart app.But got an error in adding item details to database, on
clicking ADD TO CART button. Error log says there is no such database table.and force me to SHUTTING DOWN VM. Please help me out.
I have two database in this activity.problem is with add2cart table in addcart database
Product_Detail.java
public class Product_Details extends Activity{
TextView name,price,specification,feature
String nme;
SQLiteDatabase mydb;
String pname;
String prprice;
String pspec;
String pfeature;
Button add2cart,by_nw;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
image=(ImageView)findViewById(R.id.pr_img);
name = (TextView) findViewById(R.id.txtPr_name);
price = (TextView) findViewById(R.id.txtprice);
specification=(TextView)findViewById(R.id.txtPr_spec);
feature=(TextView)findViewById(R.id.txtPr_feature);
add2cart=(Button)findViewById(R.id.add2cart);
by_nw=(Button)findViewById(R.id.buy_nw);
Intent in = getIntent();
Bundle bn = in.getExtras();
nme = bn.getString("key");
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS add2cart(img BLOB,pnme varchar,prate varchar,pqty varchar,ptotl vachar)");
mydb = Product_Details.this.openOrCreateDatabase("products", MODE_PRIVATE, null);
Cursor cr = mydb.rawQuery("SELECT * FROM product WHERE pname = '"+nme+"'", null);
while(cr.moveToNext())
{
String name = cr.getString(cr.getColumnIndex("pname"));
String pr1price = cr.getString(cr.getColumnIndex("pprice"));
String prspc=cr.getString(cr.getColumnIndex("pspec"));
String prfeature=cr.getString(cr.getColumnIndex("pfeature"));
pname = name;
prprice = pr1price;
pspec=prspc;
pfeature=prfeature;
}
name.setText(pname);
price.setText("Rs " +prprice + "/-");
specification.setText(pspec);
feature.setText(pfeature);
add2cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String nm=name.getText().toString();
String rate=price.getText().toString();
mydb.execSQL("INSERT INTO add2cart VALUES('"+nm+"','"+rate+"')");
Toast.makeText(getApplicationContext(),"add to cart",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Product_Details.this,add2cart.class);
startActivity(in);
}
});
by_nw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(Product_Details.this,buy_nw.class);
startActivity(in);
}
});
}
}
I opened my addcart database in setOnClickListner and my code worked.
Problem was the place where i opened the addcart database.It consider only the last opened database in Main.
Corrected code
public class Product_Details extends Activity{
TextView name,price,specification,feature;
String nme;
SQLiteDatabase mydb;
String pname;
String prprice;
String pspec;
String pfeature;
Button add2cart,by_nw;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
image=(ImageView)findViewById(R.id.pr_img);
name = (TextView) findViewById(R.id.txtPr_name);
price = (TextView) findViewById(R.id.txtprice);
specification=(TextView)findViewById(R.id.txtPr_spec);
feature=(TextView)findViewById(R.id.txtPr_feature);
add2cart=(Button)findViewById(R.id.add2cart);
by_nw=(Button)findViewById(R.id.buy_nw);
Intent in = getIntent();
Bundle bn = in.getExtras();
nme = bn.getString("key");
mydb = Product_Details.this.openOrCreateDatabase("products", MODE_PRIVATE, null);
Cursor cr = mydb.rawQuery("SELECT * FROM product WHERE pname = '"+nme+"'", null);
while(cr.moveToNext())
{
String name = cr.getString(cr.getColumnIndex("pname"));
String pr1price = cr.getString(cr.getColumnIndex("pprice"));
String prspc=cr.getString(cr.getColumnIndex("pspec"));
String prfeature=cr.getString(cr.getColumnIndex("pfeature"));
pname = name;
prprice = pr1price;
pspec=prspc;
pfeature=prfeature;
}
name.setText(pname);
price.setText("Rs " +prprice + "/-");
specification.setText(pspec);
feature.setText(pfeature);
add2cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String nm=name.getText().toString();
String rate=price.getText().toString();
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
mydb.execSQL("INSERT INTO add2cart (pnme,prate)VALUES('"+nm+"','"+rate+"')");
Toast.makeText(getApplicationContext(),"add to cart",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Product_Details.this,add2cart.class);
startActivity(in);
}
});
You use this line mydb = Product_Details.this.openOrCreateDatabase("products", MODE_PRIVATE, null); to reset the mydb,now the mydb is the batabase products

Retrieving values from input texts android

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();
}

Intent data not displaying right

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.

Categories

Resources