Can I use Shared Preference rather SQLite Database? - android

I want to keep data with shared preference. I looked some examples on the internet but I couldn't answer my question. I can use database for my purpose but it is really hard especially in android. There are examples that has more than 10 class to just create database. Why is it hard ?. It is cons of the db in android.
Anyway, I will keep just 1 table that has 4(relational) columns in my application.
id | name | surname |phone number.
Can I use Shared Preference to achieve this goal? How to use for 4 different columns?

You should use Database for this,
But if you will have only one entry in each column then you can use shared preference
Database is not that hard, check below page
http://www.tutorialspoint.com/android/android_sqlite_database.htm

DataBase Meet your needs ,if you want to easily use DataBase ,try xUtils, ------some code about xUtils:
//add
User user1 = new User();
user1.setAge(40);
user1.setName("bob");
user1.setPhone("123456789");
ArrayList<User> list = new ArrayList<>();
list.add(user1);
try {
MyApplication.dbUtils.saveAll(list);
} catch (DbException e) {
e.printStackTrace();
Log.d("TAG",e.getMessage());
}
//updata---1
try {
User users = MyApplication.dbUtils.findById(User.class,1);
users.setAge(18);
MyApplication.dbUtils.update(users,"age");
} catch (DbException e) {
e.printStackTrace();
}
//delete
User user = new User();
user.setId(3);
try {
MyApplication.dbUtils.delete(user);
} catch (DbException e) {
e.printStackTrace();
}
//query
List<User> allUsers = MyApplication.dbUtils.findAll(Selector.from(User.class)
.where("age",">","20")
.and("age","<","50"));

Related

Insert data into database in Android

This is my first Application with database, I hope that someone can help me to understand this problem. I have this insert method:
public long insertData(String name, int password){
....
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_PASSWORD, password);
return db.insert(DBHelper.TABle_NAME, null, contentValues);
}
I can insert few data with this method, but what about if I have thousands of rows? how can I insert all these data into database? where can I write all these data, in extra class or what?
As others have said, you'll need to do some sort of iteration.
Efficiency can be gained by performing a bulk transaction. Here's an example:
public int bulkInsert(#NonNull ContentValues[] values) {
int insertCount = 0;
SQLiteDatabase db = mSqlHelper.getWritableDatabase();
try {
db.beginTransaction();
for (ContentValues value : values) {
if (db.insertOrThrow(tableName, null, value) == -1) {
throw new Exception("Unknown error while inserting entry in database.");
}
insertCount++;
}
db.setTransactionSuccessful();
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred while bulk-inserting database entries.\n" + e.getMessage(), e);
} finally {
db.endTransaction();
}
return insertCount;
}
There is no 'bulk load' facility that I'm aware of.
You'd just have to spin through the list, and insert the items.
You might want to think about why you're potentially trying to insert thousands of items into a database on a hardware-limited device like a phone or a tablet.
Might it be better to put the data on a server, and create an API that you can use to load data (for display) by pages?
you can do it the same way, that you do with few data, you only need to catch the thousands rows to insert into your database using your method, you can use asyntask, or a service to do that
You can use the same method to insert any amount of records, whether it's 1 or 1,000. Use a loop to call your insert method and add your records to your database. Consider putting your database executions in an AsyncTask to prevent your UI thread from hanging.
Your data can come from anywhere, as long as it's formatted to fit your function parameters String, int

Retrive value of a column in parse.com

I have made a table in Parse.com using Dashboard name Blogs. I have made a column url type String using Dashboard inside it where I have to post blogs url and I have posted some url inside this column by adding rows. Now I am trying to get these values inside my application by using this code in onCreate() method.
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("Blogs");
parseQuery.whereEqualTo("url", true);
List<ParseObject> objects = null;
try {
objects = parseQuery.find();
}
catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
I am getting objects of size 0. I am unable to understand how to get my url column all values.
Read the api docs carefully.
I believe you want to query if the urls exists in the column. (since you have used parseQuery.whereEqualTo("url", true);)
From the docs,
public ParseQuery<T> whereEqualTo(String key,
Object value)
What it does : Add a constraint to the query that requires a particular key's value to be equal to the provided value.
So in this case for url, the value should be a String (which you want to match to) if you have defined the column as String. Putting value as boolean will give you undesired result.
If you want to check if the column url exists for the object,
then use whereExists(String key).
Use like this
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("Blogs");
parseQuery.whereEqualTo("url","true");
List<ParseObject> objects = null;
try
{
objects = parseQuery.find();
}
catch (ParseException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}

how to get data from separate columns in parse.com

I am new to parse.com and databases in general.
For my android app, I need to search if an object is available and if so, then it should give me its price. So my class is vegetables, and it has a column called 'isAvailable' and another column called 'price'
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("vegetables");
query.whereEqualTo("isAvailable", true); try {
ob = query.find();
}
catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
So, now I do have a list of all the vegetables that are available, but how do I query the price?
I was thinking of using the whereMatchesQuery(key, query) but it doesnt make too much sense on how to use it.
Could you guide me so as to what I should be doing, thanks !
So now you'll have a list of vegetables objects in ob.
Just iterate through ob pulling the price from each one in the list.
for(ParseObject vegetable : ob){
Log.d("TAG", "price: " + vegetable.getDouble("price"))
}

OrmLite: Advanced where logic

I have these tables in an Android based application where I'm using OrmLite for the database management.
What I want to have an x number of array list depending on how many of the product type FOLDER I have.
So in this case I want to a list of products where the productId equals parentId.
So I want a list where
if(productType = FOLDER) {
if(productId = parentId){
//add product
}
}
Basically what I want to end up with, in this case three lists with each containing a list of products where parentId is the same for every product.
I've tried many things, and some works better than others, but a code I want to run actually throws a nullpointer.
DatabaseHelper dbHelper = getHelper();
List<Product> productsParents = null;
try {
Dao<Product, Integer> dao = dbHelper.getDao();
PreparedQuery<Product> prepQu = dao.queryBuilder().where()
.eq("parentId", dao.queryBuilder().selectColumns("productId").where()
.eq("productType", ProductType.FOLDER).prepare()).prepare();
productsParents = dao.query(prepQu);
} catch (SQLException e) {
...
}
This code isn't working because productParents returns null, and it does not do what I want, even though it's a slight hint. If someone know how to do this in code that would be sufficient also, or more likely a mix of java and ormlite.
Have you had a chance to RTFM around building queries? The ORMLite docs are pretty extensive:
http://ormlite.com/docs/query-builder
Your problem is that a prepared query cannot be an argument to the eq(...) method. Not sure where you saw an example of that form.
So there are a couple ways you can do this. The easiest way is to do a different query for each productType:
Where<Product, Integer> where = dao.queryBuilder().where();
where.eq("parentId", parentId).and().eq("productType", ProductType.FOLDER);
productsParents = where.query();
// then do another similar query again with ProductType.PRODUCT, ...
If you want to do just one query then you can get all products that match the parentId and then separate them using code:
Where<Product, Integer> where = dao.queryBuilder().where();
where.eq("parentId", parentId);
productsParents = where.query();
List<Product> productFolders = new ArrayList<Product>();
List<Product> productProducts = new ArrayList<Product>();
...
for (Product product : productsParents) {
if (product.getProductType() == ProductType.FOLDER) {
productFolders.add(product);
} else if (product.getProductType() == ProductType.PRODUCT) {
productProducts.add(product);
} else ...
}

how to cast a ParseObject to ParseUser

Hi I was wondering how I can get a ParseUser object from a ParseObject. I need to do this because a ParseQuery returns a List. Here is my code and thank you for the help!
// get the currentUser
currentUser = ParseUser.getCurrentUser();
List<ParseObject> friendsList = currentUser.getList("friendsList");
// search for the person the user wants to add as a friend
List<ParseObject> userResults = new ArrayList<ParseObject>();
ParseQuery otherUserQuery = ParseUser.getQuery();
otherUserQuery.whereEqualTo("username", "jyo2");
try {
userResults = otherUserQuery.find();
} catch (ParseException e1) {
// fail
e1.printStackTrace();
}
// get the friend from the query if there was one and add it to the
// currentUser friends list
if (userResults.size() != 0) {
ParseObject currentObject = userResults.get(0);
friendsList.add(currentObject);
currentUser.put("friendsList", friendsList);
}
// save the update
try {
currentUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try to view the friends
List<ParseObject> currentFL = currentUser.getList("friendsList");
ParseObject currentPU = currentFL.get(0);
System.out.println("THIS IS SIZE" + currentFL.size());
System.out.println(currentPU.get("name"));
Use the existing "User" class in Parse but subclass it using
#ParseClassName("_User")
public class PUser extends ParseUser {
As per this article. You actually specifically need to refer to the _User "ParseClassName" when subclassing this object. It's super hairy, I was stuck on this for ages because for other classes you only need to "register" the class with Parse using it's literal name as per the Parse Data Browser, which in this case is "User", "Info", "Post" etc, but the User class specifically requires the underscore
Edit Sorry, I should have mentioned, then you simply cast the subclass PUser when you get your returned objects from the query. You may need to change the query to be a User query instead of an object one too.
I know this is an old question, but this wasn't clear for me and there wasn't a complete thread on the issue I had, on SO. Hope this helped.
I don't think you need to "cast" is to ParseUser, a parseuser is a parseobject as well, apart from having some basic pre-defined properties attached to it, which you can anyways query like you'd query any other parseobject

Categories

Resources