i want to display username in my project using SQLite? - java

in my project after user sign up , i want to display the username in next page
so, this line works but with only first user sign up if another user sign up it will display the first username.
displName =findViewById(R.id.displayName);
displName.setText(database.getAllNote().get(0).getUserName());
my database
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void openDatabase() {
db = this.getWritableDatabase();}
#SuppressLint("Range")
public List<UserTasks> getAllNote(){
List<UserTasks> listNote = new ArrayList<>();
Cursor cur = null;
db.beginTransaction();
try{
cur = db.query(TABLE_NAME, null, null, null, null, null, null, null);
if(cur != null){
if(cur.moveToFirst()){
do{
UserTasks note = new UserTasks();
note.setUser_id(cur.getInt(cur.getColumnIndex(UID)));
note.setUserName(cur.getString(cur.getColumnIndex(UserName)));
note.setPassword(cur.getString(cur.getColumnIndex(Password)));
note.setNote(cur.getString(cur.getColumnIndex(Note)));
note.setStatus(cur.getInt(cur.getColumnIndex(STATUS)));
note.setDate(cur.getString(cur.getColumnIndex(date)));
note.setTitle(cur.getString(cur.getColumnIndex(titleChe)));
note.setDecs(cur.getString(cur.getColumnIndex(desc)));
note.setDay(cur.getString(cur.getColumnIndex(day)));
listNote.add(note);
}
while(cur.moveToNext());
}
}
}
finally {
db.endTransaction();
assert cur != null;
cur.close();
}
return listNote;
}
how i can fix this small issue? pls help

You always get the first sign up user because you always retrieve table index 0
displName.setText(database.getAllNote().get(0).getUserName());
So I suggest you to use SharedPreference to increment the count of signup user.
When user successfully signup you have to increase the number of user
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Int countUser = pref.getInt("count_user", 0); // getting Integer
Editor editor = pref.edit();
editor.putInt("count_user", countUser+1);
editor.apply();
After that, change your displName.setText to this:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Int countUser = pref.getInt("count_user", 0); // getting Integer
displName.setText(database.getAllNote().get(countUser).getUserName());
You will always get latest signup username.

Related

Read Downloaded images from the "Downloads" folder from the Shared Storage in Android Emulator using MediaStore. Cursor object returns with size 0

I am looking to read a set of image files from the sdcard/download directory. I am getting content://media/external_primary/downloads as the URI string when calling
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
collection = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
}
I am using the Cursor interface to iterate through the directory but for some reason, my cursor is returning with a size of 0. I do not know what I am doing wrong to make this happen but below is the code that I have so far. Looking for some direction.
Uri collection;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
collection = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
}
String[] projection = {
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.TITLE
};
try {
Cursor cursor = getApplicationContext().getContentResolver().query(collection, projection, null, null, null);
// Cache column indices.
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads.TITLE);
while (cursor.moveToNext()) {
// Get values of columns for a given video.
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME));
Uri contentUri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id);
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageURI(contentUri);
}
} catch (Exception e) {
e.printStackTrace();
}
Snippet to the directory structure
https://i.stack.imgur.com/ELkQw.png

How to get contacts which are in the given list

My purpose is to set a list that comes from API which includes phonenumbers of the users of my app. So i only need to see contact that are in this list. But I dont know how set below code to do this. I mean in the below it opens contacts with all of the contact that are in the phone. I dont need to see the all the contacts but the ones that are in the given list
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent,1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 1 :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(contactData, null, null, null, null);
if (cur.getCount() > 0) {// thats mean some resutl has been found
if(cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("Names", name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("Number", phoneNumber);
}
phones.close();
}
}
}
cur.close();
}
break;
}
}
Consider you already have a list which has data from API, and create new list which will have common elements from API list and ContentResolver, now to add elements to your desired list, in ContentResolver check if the PhoneNumber is in API list before adding it to output.
ArrayList<String> apiPhoneNumbers;// this data is populated by API
ArrayList<String> commonPhoneNumbers = new ArrayList<>();
//inside onActivityResult
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("Number", phoneNumber);
if(apiPhoneNumbers.contains(phoneNumber)){//add to output only if it is in API list
commonPhoneNumbers.add(phoneNumber);
}
}
phones.close();
}

How to get data from Intent or SharedPreferences

I'm writing a weather app in Android Studio and I've a problem. When the user closes the app, I want to save the last city searched, and I used SharedPreferences for this.
If the user wants to search a new city, I have a "search button" that starts a new activity, where the user can choose another city and with an Intent put the string in the MainActivity.
The problem is to check (at the start of the app) if a SharedPreferences exists(and get old data from this) or intent is != null (and get new data from this).
This is my code in "OnCreate" method. It works on emulator but not on my smartphone:
value = ""; //this is a String
pref = getSharedPreferences("meteo", Context.MODE_PRIVATE);
receive_from_intent = getIntent(); //This intent gets from "SearchActivity".
add_city.setOnClickListener(new View.OnClickListener() { //this is the search button
#Override
public void onClick(View view) {
Intent start_new = new Intent(MainActivity.this, SearchActivity.class);
MainActivity.this.startActivity(start_new);
}
});
if (receive_from_intent.getExtras() != null) {
value = receive_from_intent.getStringExtra("luogo"); //if it's a string you stored.
//luogo means "city"
if (!value.matches("")) {
SharedPreferences.Editor editor = pref.edit();
editor.putString("luogo", value);
editor.apply();
}
url = "https://api.openweathermap.org/data/2.5/weather?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
url2 = "https://api.openweathermap.org/data/2.5/forecast?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
CercaLuogo(url, url2);
} else if (pref.contains("luogo")) {
value = pref.getString("luogo", "");
url = "https://api.openweathermap.org/data/2.5/weather?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
url2 = "https://api.openweathermap.org/data/2.5/forecast?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
CercaLuogo(url, url2);
} else Toast.makeText(this, "Click on search button and insert new city.", Toast.LENGTH_SHORT).show();

Checking if in-app purchases are owned in Android on first launch

I am trying to detect if any of the in-app purchases are owned by the user when the app is started on first try to renew the Pro mode of the app using SharedPreferences. The following code is unfortunately not working :(
if (version.equals("null")) { //checking version of the app, if it is unset equals first launch
SharedPreferences.Editor editor = appinfo.edit();
version = currentversion;
editor.putString("version", version);
editor.apply();
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (mHelper == null) return; //IabHelper mHelper;
Purchase purchase = Inventory.getPurchase("sku1");
Purchase purchase2 = Inventory.getPurchase("sku2");
Purchase purchase3 = Inventory.getPurchase("sku3");
if (purchase != null || purchase2 != null || purchase3 != null) {
final SharedPreferences ispro = getApplicationContext().getSharedPreferences("ispro", 0);
SharedPreferences.Editor editor = ispro.edit();
editor.putInt("ispro", 1);
editor.apply();
}
}
};
startActivity(new Intent(MainPage.this, Changelog.class));
EDIT1: After some edits the code now looks like this:
final List<String> skus = Arrays.asList("sku1", "sku2", "sku3");
if (version.equals("null")) {
SharedPreferences.Editor editor = appinfo.edit();
version = currentversion;
editor.putString("version", version);
editor.apply();
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
}
if (mHelper == null) return;
mBroadcastReceiver = new IabBroadcastReceiver(MainPage.this);
IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
registerReceiver(mBroadcastReceiver, broadcastFilter);
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (mHelper == null) return;
Purchase purchase = Inventory.getPurchase("sku1");
Purchase purchase2 = Inventory.getPurchase("sku2");
Purchase purchase3 = Inventory.getPurchase("sku3");
if (purchase != null || purchase2 != null || purchase3 != null) {
final SharedPreferences ispro = getApplicationContext().getSharedPreferences("ispro", 0);
SharedPreferences.Editor editor = ispro.edit();
editor.putInt("ispro", 1);
editor.apply();
}
}
};
try {
mHelper.queryInventoryAsync(true, skus, null, mReceivedInventoryListener);
} catch (IabHelper.IabAsyncInProgressException e) {
}
}
});
startActivity(new Intent(MainPage.this, Changelog.class));
I am not aware what is wrong with this code. Thank you in advance for the help and Happy New Year! :)
You must call IabHelper.queryInventoryAsync() in order for a QueryInventoryFinishedListener to do anything useful. Just add a call to that function immediately prior to your startActivity() call. (This is assuming you've already called IabHelper.startSetup() and all that good stuff first.)
You cannot refer to a local variable prior to its declaration. The reason you got a "mReceivedInventoryListener cannot be resolved" error is because the answer referenced in your example swapped the two lines in a confusing way.
Obligatory mention: IabHelper is apparently no longer supported by Google; you're supposed to use the billing client library instead.

Invalid characters in sqlite query?

I'm having issues creating a valid sql query.
Im trying to check if a value, title is present in my db.
Here is the method in my adapter class that creates the query.
public Cursor byTitle(String title) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_URL
},
"title" + "=" +title,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
And its called onClick with
holder.fb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final FDBAdapter db = new FDBAdapter(ctx);
title = holder.itemName.getText().toString();
db.open();
Cursor c = db.byTitle(title);
if (c.getCount()>0) {
while (c.moveToNext()) {
Toast.makeText(ctx, "yup! " + c.getString(0), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ctx, "nope! " + holder.itemName.getText().toString(), Toast.LENGTH_LONG).show();
}
c.close();
db.close();
}
});
My error is
android.database.sqlite.SQLiteException: near "Rootz": syntax error: , while compiling: SELECT DISTINCT url FROM favs WHERE title=[Guide] Rootz Wiki's List of ROMs / Kernels / Tweaks / Theme's / Radios LTE Edition
I've tried putting quotes around title like "\""+title+"\"" but that wasn't working for me either. How can I make this a valid db query?
Can you try this, might work.
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_URL
},
"title=?",
title,
null,
null,
null,
null);
Not familiar with SQLite, but I'd try single quotes, like this:
"title" + "='" + title + "'",

Categories

Resources