Android: databasehandler return null - android

i have this method in my database class as shown below:
public HashMap<String, String> getUser() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + user;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("userid", cursor.getString(3));
}
cursor.close();
db.close();
return user;
}
and in my homeActivity I am able to fetch the value as shown below:
db = new DatabaseHandler(this);
HashMap<String, String> userdetails = db.getUser();
String name = userdetails.get("name");
userID = userdetails.get("userid");
username.setText(userID + " " + name );
and when a continue button is clicked, it will go to the next activity and i want to pass the userid value to the next activity
buttonContinue.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent afterhome = new Intent(getApplicationContext(),
SecondActivity.class);
afterhome.putExtra("userid", userid);
startActivity(afterhome);
}
});
However, the value i got from the secondActivity is always 0.
my second Activity codes are as follows:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent intent = getIntent();
userid = intent.getStringExtra("userid");
}
Why is that so? Please advice. Thank you

Related

listview-SQLite updating the wrong row

When I update the selected row it updates the wrong row for example if I select second row, it will update the first row.
Here is my code inside db controller
Public boolean updateContact (String id, String category, String code, String description, String unit, String quantity) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.Col_2 , category);
values.put(FeedReaderContract.FeedEntry.Col_3 , code);
values.put(FeedReaderContract.FeedEntry.Col_4 , description);
values.put(FeedReaderContract.FeedEntry.Col_5 , unit);
values.put(FeedReaderContract.FeedEntry.Col_6 , quantity);
// updating row
database.update(TABLE_NAME ,values , FeedReaderContract.FeedEntry.Col_1 + " = ?" , new String[]{id} );
return true;
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM Countsheet";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Category", cursor.getString(1));
map.put("Code", cursor.getString(2));
map.put("Description", cursor.getString(3));
map.put("Unit", cursor.getString(4));
map.put("Quantity", cursor.getString(5));
proList.add(map);
} while (cursor.moveToNext());
cursor.close();
}
return proList;
}
Here is my button onclick to update the listview:
Public void adddata(){
btnadddata.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
boolean i = myDb.updateContact(passid , passedVar , passcode, passdesc, passunit , quantitys.getText().toString());
if (i == true)
Toast.makeText(Main2Activity.this , "Data Inserted" , Toast.LENGTH_SHORT).show();
else
Toast.makeText(Main2Activity.this , "Data Not Inserted" , Toast.LENGTH_SHORT).show();
}
}
);
}
I think you are missing 'passid' .
put 'passid' in your HashMap while fetching from database and then retrieve.
HEY GUYSSSS THANK YOU FOR ANSWERING I APPRECIATE YOU ALL , I JUST SUDDENLY GOT THE ANSWER WICH IS I JUST ADD 1 TO THE STRING.VALUEOF(ID) AND IT JUST WORKED OUT THANKS YOU GUYSSS!
//here is my code
intent.putExtra(ID_EXTRA1 , String.valueOf(id + 1));
startActivity(intent);

Retrive my database values from my database and then using them on a programmatic SMS message?

I'm confused and cannot figure out how I can send an SMS message using values stored on my database.
The SMS would appear like this: ('NAME'... Message content, etc..), the message would then be sent using the contact numbers entered by the user on the sqlite database.
Here's the code I've used to get the data during signup.
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text, PASSWORD text, NAME text, C1 integer, C2 integer); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context) {
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException {
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password, String name, String cn1, String cn2) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("NAME",name);
newValues.put("C1", cn1);
newValues.put("C2", cn2);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
// Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName) {
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSingleEntry(String userName) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) { // username doesn't exist
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public boolean isExist (String userName) {
boolean exists;
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if (cursor.getCount()>0) { // username exists
exists = true;
cursor.close();
return exists;
}
return false;
}
public void updateEntry(String userName,String password) {
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD", password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}}
And here is the SignUpActivity
public class SignUpActivity extends AppCompatActivity {
Button bSignup;
TextView tvSign;
EditText etUN, etPW, etPW2, etFN, etC1, etC2;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
bSignup = (Button)findViewById(R.id.bSignup);
tvSign = (TextView)findViewById(R.id.tvSign);
etUN = (EditText)findViewById(R.id.etUN);
etPW = (EditText)findViewById(R.id.etPW);
etPW2 = (EditText)findViewById(R.id.etPW2);
etFN = (EditText)findViewById(R.id.etFN);
etC1 = (EditText)findViewById(R.id.etC1);
etC2 = (EditText)findViewById(R.id.etC2);
bSignup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUN.getText().toString();
String password = etPW.getText().toString();
String password2 = etPW2.getText().toString();
String name = etFN.getText().toString();
String c1 = etC1.getText().toString();
String c2 = etC2.getText().toString();
// check if fields are vacant
if (username.equals("") || password.equals("") || password2.equals("") || name.equals("")
|| c1.equals("")|| c2.equals("")) {
Toast.makeText(getApplicationContext(), "Incomplete Data", Toast.LENGTH_SHORT).show();
return;
}
// check if passwords 1 and 2 match
if (!password.equals(password2)) {
Toast.makeText(getApplicationContext(), "Passwords don't match. Please try again.", Toast.LENGTH_LONG).show();
return;
}
//check is username is still available for use
if (loginDataBaseAdapter.isExist(username)){
Toast.makeText(getApplicationContext(),"Username already taken. Please try again.", Toast.LENGTH_LONG).show();
return;
}
else {
// allow data to be saved in the database
loginDataBaseAdapter.insertEntry(username, password, name, c1, c2);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
});
tvSign.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
Once I'm logged in, how can I get those values ("i.e. NAME, C1, and C2") and send an SMS by pushing a button?
Update
I've used this on my LoginDataBaseAdapter.
public HashMap<String, String> getUserDetails(){
HashMap <String,String> user = new HashMap <String,String> ();
String selectQuery = "SELECT * FROM " + "LOGIN";
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount()>0){
user.put("USERNAME", cursor.getString(1));
user.put("PASSWORD", cursor.getString(2));
user.put("NAME", cursor.getString(3));
user.put("C1", cursor.getString(4));
user.put("C2", cursor.getString(5));
}
cursor.close();
db.close();
// return user
return user;
}
Then this code at my HomeActivity:
tvHello = (TextView)findViewById(R.id.tvHello);
HashMap <String, String> details = loginDataBaseAdapter.getUserDetails();
String name_text = details.get("NAME");
tvHello.setText("Welcome " + name_text);
It seems that it can only get the first entry and not the current entry for the current user. Any ideas to fix this issue? Thank you very much.
Managed to get it right. So I'll answer my own question.
Create a editText area wherein you'll enter your name to retrieve. Then use this code to retrieve it
public String getData(String verif) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{verif}, null, null, null);
if(cursor.getCount()<1) {
cursor.close();
return "No records exist";
}
cursor.moveToFirst();
String get_name = cursor.getString(cursor.getColumnIndex("NAME"));
cursor.close();
return get_name;
}
Once retrieved, set the name in a TextView. Then convert it to string like so:
String myName = myTextView.getText().toString();
Then:
smsManager.sendTextMessage(number, null, "My name is "+ myName ,null,
null);
'number' is a String containing the contact number where you want to send your SMS

Is it possible to get both Interger and String value from one HashMap method?

I want to merge my two Hashmap methods. One method is for getting user ID and the other is for getting user String information. But I want to get all information from one hashmap method. Is it possible? If it is, how can I do this in my getuserdetails hashmap method?
Method 1:
public HashMap<String, Integer> getUid() {
HashMap<String, Integer> uid = new HashMap<String,Integer>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
Log.d("database", "before uid put");
if (cursor.getCount() > 0) {
uid.put("uid",cursor.getInt(0));
}
cursor.close();
// return user
return uid;
}
Method 2:
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("created_at", cursor.getString(3));
}
cursor.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
The cleanest approach here would be to create a User object with fields for id, name, email and created_at, something like this:
public class User {
private int id;
private String name;
private String email;
private Date createdAt; // Or use string here, whichever you want
// create or generate getters and setters for above fields
}
You can then get the data from the database using your query and create a user:
public User getUserDetails() {
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
User user = new User();
if (cursor.getCount() > 0) {
user.setId(cursor.getInt(0));
user.setName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setCreatedAt(cursor.getString(3));
}
else {
cursor.close();
return null; // There wasn't a user to be found
}
cursor.close();
return user;
}
Now your method creates a User object, containing all required information.
Make a class with uid and name veriable And Create a hashmap method as a return type of this class. Hope this will work.
you can wrap together in a class like
public class Info {
public int uid;
public String name;
}
and have a HashMap<String, Info>

Android - SQLite delete and update data not working well

I created database with few tables, got 1 table called friend. A friend has few expenses, some expenses might share with another friend. Now i am trying to delete a friend, what i am trying to do is when the friend share expenses with another friend, the expense of the friend that shared with another friend will then added to another friend and the expense will not deleted. Then, the expenses that are not shared with another friend is directly deleted and will not added to any friend since the friend has many expenses. Now the problem is when i trying to add the expense to another friend, its not working. And i am not getting any error.
Here is my code : i think the problem occur inside if(sharerList.size()>1)...., since the rest of the code works well.
public void deleteFriend(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM FriendsExpenses WHERE friendId='" + id + "'";
SQLiteDatabase databaseread = this.getReadableDatabase();
Cursor cursor = databaseread.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("expenseId", cursor.getString(0));
wordList.add(map);
} while (cursor.moveToNext());
}
for (int a=0; a<wordList.size();a++){
HashMap<String, String> ValexpenseId = wordList.get(a);
for (Entry<String, String> entry : ValexpenseId.entrySet()) {
String value = entry.getValue();
String selectQuery2 = "SELECT * FROM FriendsExpenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread2 = this.getReadableDatabase();
Cursor cursor2 = databaseread2.rawQuery(selectQuery2, null);
ArrayList<HashMap<String, String>> sharerList = new ArrayList<HashMap<String, String>>();
if (cursor2.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("friendId", cursor2.getString(0));
wordList.add(map);
} while (cursor2.moveToNext());
}
else{};
if (sharerList.size() > 1){
String selectQuery3 = "SELECT expenseTotal FROM expenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread3 = this.getReadableDatabase();
Cursor cursor3 = databaseread3.rawQuery(selectQuery3, null);
String expenseTotal = null;
if (cursor3.moveToFirst()) {
do {
expenseTotal = cursor3.getString(cursor3.getColumnIndex("expenseTotal"));
} while (cursor3.moveToNext());
}
for (int b=0; b<sharerList.size();b++){
HashMap<String, String> ValfriendId = sharerList.get(b);
for (Entry<String, String> entry2 : ValfriendId.entrySet()) {
String value2 = entry2.getValue();
String currentSpend = currentSpending(value2);
double currentSpending = (Double.parseDouble(currentSpend));
double expTotal = (Double.parseDouble(expenseTotal));
double newSpending = currentSpending + ((expTotal/sharerList.size()) /sharerList.size()-1);
updateSpending(value2, newSpending);
}
}
}
else
{
String deleteQuery = "DELETE FROM expenses where expenseId='" + value + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
}
}
String deleteQuery = "DELETE FROM friends where friendId='" + id + "'";
String deleteQuery2 = "DELETE FROM FriendsExpenses where friendId='" + id + "'";
Log.d("query", deleteQuery2);
Log.d("query", deleteQuery);
database.execSQL(deleteQuery2);
database.execSQL(deleteQuery);
}
sharerList is empty because you never add any entries.
There are likely to be other copy/paste errors, such as getString(0) with SELECT *.

Android Hashmap return value from other class

i will like to pass the value from DatabaseHandler.java lets say "name" to mainActivity and show it on textview.
DatabaseHandler.java
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
MainActivity.java
TextView lblid;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lblid = (TextView) findViewById(R.id.showid);
HashMap<string, string=""> details = getUserDetails();
String nametext = details.getString("name");
lblid.setText(nametext);
}
I am having trouble writing correct code to make it works, i keep getting "Syntax error on token". Please help me out.
Thanks.
this line cause problem
HashMap<string, string=""> details = getUserDetails();
replace it with
HashMap<string, string> details = getUserDetails();
Usage exaple
Main.java
public class MainActivity extends Activity {
...
private DatabaseHandler dbh;
...
public void onCreate(Bundle) {
dbh = new DatabaseHandler(...);
...
}
...
HashMap<String, String> details = dbh.getUserDetails();
...
String nametext = details.get("name");

Categories

Resources