How to save sqlite database firebase notification android - java

I need to save the title, post id message in firebase in sqlite database. I have tried many times but I don't get any answer. If you know please let me know.For me notification title, post_id, link these three are coming as array. If you send firebase notification, it should be automatic or save
`public class MyFirebaseMessageService extends FirebaseMessagingService {
#Override
public void onNewToken(#NonNull String token) {
super.onNewToken(token);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
Log.d("onMessageFirebase: ", remoteMessage.getData().toString());
if (data.get("post_id") != null) {
String _unique_id = data.get("unique_id");
String title = data.get("title");
String message = data.get("message");
String big_image = data.get("big_image");
String link = data.get("link");
String _post_id = data.get("post_id");
assert _unique_id != null;
long unique_id = Long.parseLong(_unique_id);
assert _post_id != null;
long post_id = Long.parseLong(_post_id);
createNotification(unique_id, title, message, big_image, link, post_id);
}
}
}
private void createNotification(long unique_id, String title, String message, String image_url, String link, long post_id) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("unique_id", unique_id);
intent.putExtra("post_id", post_id);
intent.putExtra("title", title);
intent.putExtra("link", link);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = getApplicationContext().getString(R.string.app_name);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(getNotificationIcon(notificationBuilder))
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification_large_icon))
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
} else {
notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
}
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setSound(alarmSound).setVibrate(new long[]{100, 200, 300, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.shouldShowLights();
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(false);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
if (image_url != null && !image_url.isEmpty()) {
Bitmap image = fetchBitmap(image_url);
if (image != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image));
}
}
//assert notificationManager != null;
notificationManager.notify((int) post_id, notificationBuilder.build());
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
return R.drawable.ic_stat_onesignal_default;
}
private Bitmap fetchBitmap(String src) {
try {
if (src != null) {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setConnectTimeout(1200000);
connection.setReadTimeout(1200000);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
}``
DBHELPER
public class DbHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "db_recipes_favorite";
private static final String TABLE_NAME = "tbl_recipes_favorite";
private static final String notification = "tbl_notification";
private static final String KEY_ID = "id";
private static final String KEY_CAT_NAME = "category_name";
private static final String KEY_RECIPE_ID = "recipe_id";
private static final String KEY_RECIPE_TITLE = "recipes_title";
private static final String KEY_calories = "calories";
private static final String KEY_servings = "servings";
private static final String KEY_RECIPE_TIME = "recipe_time";
private static final String KEY_RECIPE_IMAGE = "recipe_image";
private static final String KEY_RECIPE_DESCRIPTION = "recipe_description";
private static final String KEY_RECIPE_DESCRIPTION2 = "recipe_description2";
private static final String KEY_RECIPE_DESCRIPTION3 = "recipe_description3";
private static final String KEY_VIDEO_URL = "video_url";
private static final String KEY_VIDEO_ID = "video_id";
private static final String KEY_CONTENT_TYPE = "content_type";
private static final String KEY_FEATURED = "featured";
private static final String KEY_TAGS = "tags";
private static final String KEY_TOTAL_VIEWS = "total_views";
public DbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_CAT_NAME + " TEXT,"
+ KEY_RECIPE_ID + " TEXT,"
+ KEY_RECIPE_TITLE + " TEXT,"
+ KEY_calories + " TEXT,"
+ KEY_servings + " TEXT,"
+ KEY_RECIPE_TIME + " TEXT,"
+ KEY_RECIPE_IMAGE + " TEXT,"
+ KEY_RECIPE_DESCRIPTION + " TEXT,"
+ KEY_RECIPE_DESCRIPTION2 + " TEXT,"
+ KEY_RECIPE_DESCRIPTION3 + " TEXT,"
+ KEY_VIDEO_URL + " TEXT,"
+ KEY_VIDEO_ID + " TEXT,"
+ KEY_CONTENT_TYPE + " TEXT,"
+ KEY_FEATURED + " TEXT,"
+ KEY_TAGS + " TEXT,"
+ KEY_TOTAL_VIEWS + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
//Adding Record in Database
public void AddtoFavorite(Recipe p) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CAT_NAME, p.getCategory_name());
values.put(KEY_RECIPE_ID, p.getRecipe_id());
values.put(KEY_RECIPE_TITLE, p.getRecipe_title());
values.put(KEY_calories, p.getcalories());
values.put(KEY_servings, p.getservings());
values.put(KEY_RECIPE_TIME, p.getRecipe_time());
values.put(KEY_RECIPE_IMAGE, p.getRecipe_image());
values.put(KEY_RECIPE_DESCRIPTION, p.getRecipe_description());
values.put(KEY_RECIPE_DESCRIPTION2, p.getRecipe_description());
values.put(KEY_RECIPE_DESCRIPTION3, p.getRecipe_description());
values.put(KEY_VIDEO_URL, p.getVideo_url());
values.put(KEY_VIDEO_ID, p.getVideo_id());
values.put(KEY_CONTENT_TYPE, p.getContent_type());
values.put(KEY_FEATURED, p.getFeatured());
values.put(KEY_TAGS, p.getTags());
values.put(KEY_TOTAL_VIEWS, p.getTotal_views());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
public void notification(Recipe p) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RECIPE_ID, p.getRecipe_id());
values.put(KEY_RECIPE_TITLE, p.getRecipe_title());
values.put(KEY_RECIPE_IMAGE, p.getRecipe_image());
// Inserting Row
db.insert(notification, null, values);
db.close(); // Closing database connection
}
// Getting All Data
public List<Recipe> getAllData() {
List<Recipe> dataList = new ArrayList<Recipe>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Recipe values = new Recipe();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setCategory_name(cursor.getString(1));
values.setRecipe_id(cursor.getString(2));
values.setRecipe_title(cursor.getString(3));
values.setcalories(cursor.getString(4));
values.setservings(cursor.getString(5));
values.setRecipe_time(cursor.getString(6));
values.setRecipe_image(cursor.getString(7));
values.setRecipe_description(cursor.getString(8));
values.setRecipe_description2(cursor.getString(9));
values.setRecipe_description3(cursor.getString(10));
values.setVideo_url(cursor.getString(11));
values.setVideo_id(cursor.getString(12));
values.setContent_type(cursor.getString(13));
values.setFeatured(cursor.getString(14));
values.setTags(cursor.getString(15));
values.setTotal_views(cursor.getLong(16));
// Adding contact to list
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
//getting single row
public List<Recipe> getFavRow(String id) {
List<Recipe> dataList = new ArrayList<Recipe>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE recipe_id=" + id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Recipe values = new Recipe();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setCategory_name(cursor.getString(1));
values.setRecipe_id(cursor.getString(2));
values.setRecipe_title(cursor.getString(3));
values.setcalories(cursor.getString(4));
values.setservings(cursor.getString(5));
values.setRecipe_time(cursor.getString(6));
values.setRecipe_image(cursor.getString(7));
values.setRecipe_description(cursor.getString(8));
values.setRecipe_description2(cursor.getString(9));
values.setRecipe_description3(cursor.getString(10));
values.setVideo_url(cursor.getString(11));
values.setVideo_id(cursor.getString(12));
values.setContent_type(cursor.getString(13));
values.setFeatured(cursor.getString(14));
values.setTags(cursor.getString(15));
values.setTotal_views(cursor.getLong(16));
// Adding contact to list
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
//for remove favorite
public void RemoveFav(Recipe contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_RECIPE_ID + " = ?",
new String[]{String.valueOf(contact.getRecipe_id())});
db.close();
}
public enum DatabaseManager {
INSTANCE;
private SQLiteDatabase db;
private boolean isDbClosed = true;
DbHandler dbHelper;
public void init(Context context) {
dbHelper = new DbHandler(context);
if (isDbClosed) {
isDbClosed = false;
this.db = dbHelper.getWritableDatabase();
}
}
public boolean isDatabaseClosed() {
return isDbClosed;
}
public void closeDatabase() {
if (!isDbClosed && db != null) {
isDbClosed = true;
db.close();
dbHelper.close();
}
}
}
}`
How to save sqlite database firebase notification android

Related

sqlite database return on a null object reference

I am new in android. I have an app and when I click on the send button I get an error in the app:
SQLiteDatabase.execSQL(java.lang.String,java.lang.object)on a null object reference.
This is my Database code :
public class MyDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "contact_db" ;
public static final String TABLE_NAME = "contact_msg" ;
public static final String COL_1 = "id" ;
public static final String COL_2 = "phoneNumber" ;
public static final String COL_3 = "text" ;
static SQLiteDatabase mDatabase;
public MyDatabase(#Nullable Context context) {
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase mDatabase) {
mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " ( " +COL_1+ " INTEGEER PRIMARY KEY AUTOINCREMENT ," + COL_2 + "VARCHAR, "
+COL_3+ "VARCHAR )");
// mDatabase = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
}
#Override
public void onUpgrade(SQLiteDatabase mDatabase, int i, int i1) {
mDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(mDatabase);
}
public static void addContacts(String phoneNumber, String text, Context context){
if (phoneNumber.isEmpty()){
// phoneEditText.setError("phoneNumber can not be empty...");
// phoneEditText.requestFocus();
return;
}
String sql = " INSERT INTO contact_msg(phoneNumber, text)" +
"VALUES (?, ?)";
mDatabase.execSQL(sql, new String []{phoneNumber, text});
Toast.makeText(context,"contacts addedddddd",Toast.LENGTH_SHORT).show();
}
}
and this is my SendActivity code :
public class SendActivity extends AppCompatActivity {
// define channel
private static final String ChANNEL_ID = "simplified_coding";
private static final String CHANNEL_NAME = "Simplified Coding";
private static final String ChANNEL_DESC = "Simplified Coding Notification";
Button sendBtn;
Button sendBtn2;
EditText phoneEditText;
EditText plainEditText;
MyDatabase MyDb;
// static TextView cipherTextView;
// static TextView receivedTextview;
static String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJoBRPFYZb19vXqpiHzo2gPTq0" +
"D1Ey++4PohVNboTBfsscUYA8SMPX4/Jz0NmhDbtk1PL3rqOVKubcEyJumxA+l46B" +
"gNoQsnOBqXfE5Voo0GTbgP4AeN6MnkJ8mhawj3vu2TGmQqtlFYRyYbp6MZ6Q7ops" +
"kZBKULJJJSwC9qSpewIDAQAB";
static String privKey="MIICXAIBAAKBgQCJoBRPFYZb19vXqpiHzo2gPTq0D1Ey++4PohVNboTBfsscUYA8" +
"SMPX4/Jz0NmhDbtk1PL3rqOVKubcEyJumxA+l46BgNoQsnOBqXfE5Voo0GTbgP4A" +
"eN6MnkJ8mhawj3vu2TGmQqtlFYRyYbp6MZ6Q7opskZBKULJJJSwC9qSpewIDAQAB" +
"AoGATMqdimMgTS7s5DG0WlLOg5KmpsHFNQWNl/uAl2wLd0wgWPTA8OJJJLV0G1t1" +
"k3/uCB0qVTmE3T7LAhFLLRwou2wZbw3w48jF4uTXQJex6cf1xHVkXy6jBUVLlddW" +
"74MQv3pfBRs/s0NsYML4J713r55JNmTU26WDwLA2xPNiosECQQDxAQQb7i1ZmSnr" +
"9h0J6Ss3SGqpqDr/RRvUjSmCaCZtP/YFyNEd1aseQ8Wc31PpouwFgJbFYPEOAw+n" +
"h2UECEiHAkEAkjBUvSFOFNnQIeiq1TUN/piEehSa8inLdU1psroVr09GprpS6nGZ" +
"df66Nv0DhMCw6N1VjywnLNi8ru5zpg34bQJBAIXZWJzihRFT/XJtd+c/Np83evXK" +
"1ylbCn/b/ofMrDrU4SCJTYrSVn0yipf7eLEzqP3NUu9ATeDIVnNmwPWiXBUCQGCL" +
"PJs+8IMCqdqK/q8Zf6mA7hR1oTKGeZB5VHGtRP7m+wDHElU0OqXbWP1RsM4uN2dC" +
"LOwFu8V5SXq5jXS/yy0CQCpkkZ6YEHxcKJGptVyAtC5iYNCun0pYNjrJHflu6ia8" +
"pvX7FcJBo2l2Kmld6gXDlYnlJpyOSTapMDjSEs/DNr8=";
// public static final String DATABASE_NAME = "contact_db" ;
static SQLiteDatabase mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send );
getWindow().getDecorView().setBackgroundColor(Color.rgb(249, 247, 209));
MyDb = new MyDatabase(this);
// Database Code
mDatabase = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
// CREATE_TABLE();
// handel android8 for channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(ChANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(ChANNEL_DESC);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/BRoya.ttf");
phoneEditText = (EditText) findViewById(R.id.editTextPhoneNumber);
plainEditText = (EditText) findViewById(R.id.editTextContent);
// cipherTextView = (TextView) findViewById(R.id.textViewCipherText);
// receivedTextview = (TextView) findViewById(R.id.textViewReceivedText);
sendBtn = (Button) findViewById(R.id.buttonSendSMS);
sendBtn2 = (Button) findViewById(R.id.buttonSendContacts);
phoneEditText.setTypeface(face);
plainEditText.setTypeface(face);
// receivedTextview.setTypeface(face);
// sendBtn.setTypeface(face);
}
public void gotoMessage(View view){
switch (view.getId()) {
case R.id.buttonSendContacts:
startActivity(new Intent(this, MessageActivity .class));
break;
}
}
public void sendSMS(View V){
try {
String phoneNumber = phoneEditText.getText().toString();
String plainText = plainEditText.getText().toString();
String cipherText = encryptBeforeSend(plainText);
// String decodedText = decryptAfterReceive(cipherText);
// decodedText += "!!";
// cipherTextView.setText(cipherText);
// receivedTextview.setText(decodedText);
if (ContextCompat.checkSelfPermission(SendActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1);
} else {
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> msgArray = smsManager.divideMessage(cipherText);
smsManager.sendMultipartTextMessage(phoneNumber, null, msgArray, null, null);
Toast.makeText(getApplicationContext(),
"SMS sent!",
Toast.LENGTH_LONG).show();
MyDb.addContacts(phoneNumber, plainText, this);
}
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!"+e.toString(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public String encryptBeforeSend(String inputString) {
// encrypt
byte[] userData = inputString.getBytes();
try {
byte[] encodeData = myRSA.encryptByPublicKey(userData, pubKey);
// String encodeStr = new BigInteger(1, encodeData).toString(16);
String encodeStr = Base64.encodeToString(encodeData, Base64.DEFAULT);
return encodeStr;
}
catch (Exception ex){
ex.printStackTrace();
return ex.toString();
}
}
}
When I call the sendSMS function I get the database null object reference error and when I call the gotoMessage function the app does crash and I know that the cause of the crash is the database.
Can anybody help me?
First of all, the string passed in your mDatabase.execSQL() inside onCreate() is not a valid db query due to typo (INTEGEER) and wrong spacing during string concatenation. It should be:
#Override
public void onCreate(SQLiteDatabase mDatabase) {
mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY, " + COL_2 + " VARCHAR, " + COL_3 + " VARCHAR)");
}
Possibly the database table won't be created otherwise.
Next, as stated in the official documentation,
getWritableDatabase() is used to create and/or open a database that will be used for reading and writing.
Also, according to the documentation,
execSQL() executes a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. For INSERT statements, use any of the following instead.
insert(java.lang.String, java.lang.String, android.content.ContentValues)
insertOrThrow(java.lang.String, java.lang.String, android.content.ContentValues)
insertWithOnConflict(java.lang.String, java.lang.String, android.content.ContentValues, int)
So, your addContacts() method should be like this:
public void addContacts(String phoneNumber, String text, Context context) {
if (phoneNumber.isEmpty())
return;
SQLiteDatabase mDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("phoneNumber", phoneNumber);
values.put("text", text);
mDatabase.insert("contact_msg", null, values);
mDatabase.close();
Toast.makeText(context, "contacts added", Toast.LENGTH_SHORT).show();
}

Having trouble on username it says null

i got toast null null, it supposed to toast: "Welcome Angelo(username) Dionisio(userSurname)" after logging in but it says "Welcome null null"
after checking the user existance, it supposed to get the name from the database and display to the toast and switch activities...
what is my error?
and i want to store the username, id, usersurname to the shared prefs after displaying the toast in the future..
myLoginActivity.java
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmailPhone;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
Parent_DatabaseHelper mydb;
SQLiteDatabase sqLiteDatabase;
ParentModel parentModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmailPhone = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_login).setOnClickListener(Login.this);
progressDialog = new ProgressDialog(this);
mydb = new Parent_DatabaseHelper(this);
sqLiteDatabase = mydb.getReadableDatabase();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_login: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmailPhone.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmailPhone.setError("Email or Phone Number is required");
editTextEmailPhone.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
else{
progressDialog.setMessage("Please Wait...");
progressDialog.show();
boolean exists = mydb.userExistance(email, password);
if(exists){
progressDialog.dismiss();
SharedPrefs.saveSharedSetting(this, "NoAccount", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
ArrayList<ParentModel> arrayList = new ArrayList<>();
parentModel = new ParentModel();
String s_parentID;
String s_parentName;
String s_parentSurname;
s_parentID = parentModel.getID();
s_parentName = parentModel.getName();
s_parentSurname = parentModel.getSurname();
Toast.makeText(this, "Welcome " + s_parentName + s_parentSurname, Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
else {
Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
return;
}
}
}
public void Login_AdminParent(View view) {
startActivity(new Intent(this, Login_AdminTeacher.class));
}
}
DatabaseHelper.java (incase you need it)
package edu.angelo.parentsportal;
public class Parent_DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public Parent_DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String email_address, String phone_number, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,surname);
contentValues.put(COL_3,email_address);
contentValues.put(COL_4,phone_number);
contentValues.put(COL_5,password);
long result = db.insert(TABLE_NAME, null , contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public ArrayList<ParentModel> getAllParentsData(){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
public void updateData(int id, String name , String surname , String email , String phone_number , String password){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
public void deleteParent(int id){
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.delete(TABLE_NAME, COL_0 + "=" + id, null);
mydb.close();
}
public boolean userExistance(String emailOrPhone, String pwd) {
String sql = "select * from " + TABLE_NAME + " where (" + COL_3 + " = '" + emailOrPhone + "' OR " + COL_4 + " = '" + emailOrPhone + "') AND " + COL_5 + " = " + pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
ArrayList<ParentModel> list = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return true;
}
else{
return false;
}
}
}
This code here creates ParentModel instance but does not set its members.
parentModel = new ParentModel();
String s_parentID;
String s_parentName;
String s_parentSurname;
s_parentID = parentModel.getID();
s_parentName = parentModel.getName();
s_parentSurname = parentModel.getSurname();
So s_parentName and s_parentSurname are null.
To fix your problem you should create ParentModel instance before calling userExistance and pass it to userExistance. For example:
. . .
parentModel = new ParentModel();
boolean exists = mydb.userExistance(email, password, parentModel);
. . .
And change userExistance. Add ParentModel parameter and remove parentModel = new ParentModel();
like this:
public boolean userExistance(String emailOrPhone, String pwd, ParentModel parentModel)
{
String sql = "select * from " + TABLE_NAME + " where (" + COL_3 + " = '" + emailOrPhone + "' OR " + COL_4 + " = '" + emailOrPhone + "') AND " + COL_5 + " = " + pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
ArrayList<ParentModel> list = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return true;
}
return false;
}

Null pointer exception SQLite Alarm database

Hey devs I am new to android development I am facing a problem I m creating a alarm app which timings I myself insert into the database and I want the alarm to trigger at that time.
Here is my code for MainActivity
public class MainActivity extends Activity {
final String PREF_NAME = "Preferences";
Context context;
static PendingIntent pendingIntent;
static AlarmManager alarmManager;
Switch switch1;
Intent intentAlarm;
DatabaseHandler dhb = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Calendar cal = Calendar.getInstance();
intentAlarm = new Intent(context, AlarmReciver.class);
// setting Time!
Log.d("Insert: ", "Inserting...");
dhb.createAlarm(new AlarmModel(1, 1, 21, 5));
context = MainActivity.this;
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
switch1 = (Switch) findViewById(R.id.tgButton);
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (seherBtn.isChecked()) {
List<AlarmModel> alarms = dhb.getAlarms();
for (AlarmModel al : alarms) {
pendingIntent = PendingIntent.getBroadcast(context,
al.getId(), intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
cal.set(Calendar.MONTH, 6);
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_MONTH, al.getDay());
cal.set(Calendar.HOUR_OF_DAY, al.getTimeHour());
cal.set(Calendar.MINUTE, al.getTimeMinute());
cal.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pendingIntent);
}
} else {
alarmManager.cancel(pendingIntent);
}
}
});
}
And my DatabaseHelper class
Please help me if I m going wrong somewhere and please suggest me the possible solution
Thanks...
public class DatabaseHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "alarmClock.db";
public static final String TABLE_NAME = "alarm";
public static final String COLUMN_NAME_ALARM_NAME = "name";
public static final String COLUMN_NAME_ALARM_TIME_HOUR = "hour";
public static final String COLUMN_NAME_ALARM_TIME_MINUTE = "minute";
public static final String COLUMN_NAME_ALARM_DAYS = "days";
public static final String ID = "id";
private static final String SQL_CREATE_ALARM = "CREATE TABLE " + TABLE_NAME
+ " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME_ALARM_NAME + " TEXT," + COLUMN_NAME_ALARM_TIME_HOUR
+ " INTEGER," + COLUMN_NAME_ALARM_TIME_MINUTE + " INTEGER,"
+ COLUMN_NAME_ALARM_DAYS + " INTEGER," + " )";
private static final String SQL_DELETE_ALARM = "DROP TABLE IF EXISTS "
+ TABLE_NAME;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ALARM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ALARM);
}
private AlarmModel populateModel(Cursor c) {
AlarmModel model = new AlarmModel();
model.id = c.getInt(c.getColumnIndex(ID));
model.timeHour = c
.getInt(c.getColumnIndex(COLUMN_NAME_ALARM_TIME_HOUR));
model.timeMinute = c.getInt(c
.getColumnIndex(COLUMN_NAME_ALARM_TIME_MINUTE));
model.day = c.getInt(c.getColumnIndex(COLUMN_NAME_ALARM_DAYS));
return model;
}
private ContentValues populateContent(AlarmModel model) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_ALARM_TIME_HOUR, model.timeHour);
values.put(COLUMN_NAME_ALARM_TIME_MINUTE, model.timeMinute);
values.put(COLUMN_NAME_ALARM_DAYS, model.day);
return values;
}
public long createAlarm(AlarmModel model) {
ContentValues values = populateContent(model);
return getWritableDatabase().insert(TABLE_NAME, null, values);
}
public AlarmModel getAlarm(long id) {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM " + TABLE_NAME + " WHERE " + ID + " = "
+ id;
Cursor c = db.rawQuery(select, null);
if (c.moveToNext()) {
return populateModel(c);
}
return null;
}
public long updateAlarm(AlarmModel model) {
ContentValues values = populateContent(model);
return getWritableDatabase().update(TABLE_NAME, values, ID + " = ?",
new String[] { String.valueOf(model.id) });
}
public int deleteAlarm(long id) {
return getWritableDatabase().delete(TABLE_NAME, ID + " = ?",
new String[] { String.valueOf(id) });
}
public List<AlarmModel> getAlarms() {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT * FROM " + TABLE_NAME;
Cursor c = db.rawQuery(select, null);
List<AlarmModel> alarmList = new ArrayList<AlarmModel>();
while (c.moveToNext()) {
alarmList.add(populateModel(c));
}
if (!alarmList.isEmpty()) {
return alarmList;
}
return null;
}
}

Can't add more than one record, ID not autoincrimenting

I'm trying to add site details to a database and then after I insert a row, output the result to a TextView. The record is being inserted into the database because it's being shown in a TextView, however I can only insert one record and I'm not sure why. I'm been using the tutorial here and modifying it to meet my needs.
Here is my DBAdapter:
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String username,
String password, int port) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_PORT, port);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, String port) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
// newValues.put(KEY_PASSWORD, password);
// newValues.put(KEY_PORT, port);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I'm querying the database here:
public class FTPConnector extends Activity {
DBAdapter myDb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.ftp);
status = (TextView) findViewById(R.id.status);
editAddress = (EditText) findViewById(R.id.editAddress);
editUser = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
addsiteBtn = (Button) findViewById(R.id.addsiteBtn);
addsiteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
//Where the insertRecord() happens
public void siteManager() {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.site_manager, null);
final EditText tmpname = (EditText) view
.findViewById(R.id.dialogsitename);
final EditText tmpaddress = (EditText) view
.findViewById(R.id.dialogaddress);
final EditText tmpuser = (EditText) view
.findViewById(R.id.dialogusername);
final EditText tmppass = (EditText) view
.findViewById(R.id.dialogpassword);
final EditText tmpport = (EditText) view.findViewById(R.id.dialogport);
final TextView tmpsites = (TextView) view.findViewById(R.id.textView6);
final CheckBox tmppassive = (CheckBox) view
.findViewById(R.id.dialogpassive);
final Button tmpclose = (Button) view.findViewById(R.id.closeBtn);
final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn);
final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite);
customDialog.setView(tmpclose);
customDialog.setView(tmptestBtn);
customDialog.setView(tmpname);
customDialog.setView(tmpaddress);
customDialog.setView(tmpuser);
customDialog.setView(tmppass);
customDialog.setView(tmpport);
customDialog.setView(tmppassive);
customDialog.setView(tmpsavetsite);
customDialog.setView(tmpsites);
tmpclose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
tmptestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
_passive = false;
if (tmppassive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _user, _pass, _port);
if (status == true) {
Toast.makeText(FTPConnector.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(FTPConnector.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
tmpsavetsite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tmpsites.setText("");
String msg = "!";
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
long newId = myDb.insertRow(_name, _address, _user, _pass, 21);
Cursor c = myDb.getAllRows();
if (c.moveToFirst()) {
int id = c.getInt(0);
String _name = c.getString(1);
String _address = c.getString(2);
String _user = c.getString(3);
String _pass = c.getString(4);
int _port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _user + "\n";
msg += ", password=" + _pass + "\n";
msg += ", port=" + _port + "\n";
while (c.moveToNext());
}
c.close();
// displayText(msg);
tmpsites.setText(msg);
}
});
customDialog.setView(view);
customDialog.show();
}
Why can't I add more than one record?
In here :
while (c.moveToNext()); //<<<
currently you are not using any loop like do-while for iterating through cursor(you forget to add do block with while). get all data from cursor as using for loop:
//more to the first row
c.moveToFirst();
//iterate over rows
for (int i = 0; i < c.getCount(); i++) {
// get all data here from current row..
//move to the next row
c.moveToNext();
}
//close the cursor
c.close();
and using do-while you can get all values from current row as:
c.moveToFirst(); //more to the first row
do {
// get all data here from current row..
} while (c.moveToNext());

Populate Android Listview from SQLite database

I've been trying to populate an Android Listview from a SQLite database using the code below. I have successfully done this from an array inside the same class. But in this case I'm attempting to populate it from a String array I have returned from another class. I'm new to this so am possibly doing this completely wrong. If anyone could look at the code and advise to what I'm doing wrong that'd be brilliant.
Any help would be really appreciated with this as I'm under serious pressure to get it finished, Thanks!
LoginActivity Class
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try{
if(username.length() > 0 && password.length() >0)
{
DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this);
dbUser.open();
int UID = dbUser.Login(username, password);
if(UID != -1)
{
// TEST
//int UID = dbUser.getUserID(username, password);
//getSitesByClientname(UID);
// END TEST
// MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES
Intent myIntent = new Intent(LoginActivity.this, ClientSites.class);
//Intent myIntent = new Intent(getApplicationContext(), ClientSites.class);
myIntent.putExtra("userID", UID);
startActivity(myIntent);
//finish();
// END MY TEST CODE
//Cursor UserID = dbUser.getUserID();
Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e)
{
Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Method from DBHelper Class to return String Array
public String[] getSitesByClientname(String id) {
String[] args={id};
//return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
// loop through all rows and adding to array
int count;
count = myCursor.getCount();
final String[] results = new String[count];
results[0] = new String();
int i = 0;
try{
if (myCursor.moveToFirst()) {
do {
results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename"));
} while (myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
// return results array
return results;
ClientSites Class
public class ClientSites extends ListActivity {
public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
//private Cursor ourCursor = null;
private ArrayAdapter<String> adapter=null;
//#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
Any help with this would be great, Thanks!
Create own project with few activities. Start working with sqlite database
Create new application. Create login activity and DB helper. Trying to upload dada from DB. Reseach and development
Here is an example how to work with SQLite DB.
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
private static final String DATABASE_NAME = "UserClientBase";
private static final int DATABASE_VERSION = 1;
public static interface USER extends BaseColumns {
String TABLE_NAME = "userTable";
String NAME = "userName";
String PASSWORD = "userPassword";
}
public static interface CLIENT extends BaseColumns {
String TABLE_NAME = "clientTable";
String NAME = "clientName";
String USER_ID = "userId";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID
+ " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);";
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID
+ " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);";
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_CLIENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE + USER.TABLE_NAME);
db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME);
onCreate(db);
}
public long createUser(String newUserName, String newUserPassword) {
ContentValues values = new ContentValues();
values.put(USER.NAME, newUserName);
values.put(USER.PASSWORD, newUserPassword);
return getWritableDatabase().insert(USER.TABLE_NAME, null, values);
}
public long createClient(long userId, String newClientName) {
ContentValues values = new ContentValues();
values.put(CLIENT.USER_ID, userId);
values.put(CLIENT.NAME, newClientName);
return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values);
}
public boolean isCorrectLoginPassword(String login, String password) {
Cursor userListCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD
+ " =?", new String[] { login, password });
if ((userListCursor != null) && (userListCursor.getCount() > 0)) {
return true;
} else {
return false;
}
}
public Cursor getUserClientList(String userName) {
Cursor userClientList = getReadableDatabase().rawQuery(
"SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME
+ " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE "
+ USER.NAME + " =?", new String[] { userName });
return userClientList;
}
}
Example of login button click listener.
String login = loginEdt.getText().toString();
String password = passwordEdt.getText().toString();
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password);
if(loginSuccess) {
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class);
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login);
startActivity(clientListIntent);
} else {
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show();
}
And example of listview with data from sql:
clientLv= (ListView)findViewById(R.id.listClient);
login = getIntent().getExtras().getString(EXTRAS_LOGIN);
dbHelper = DBHelper.getInstance(this);
Cursor clientList = dbHelper.getUserClientList(login);
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
clientLv.setAdapter(adapter);

Categories