I'm currently developing an android app that requires data to be inserted into an azure Mobile Service DB. An id string and a first login integer, to be exact. However the following error is being thrown up.
"IllegalArgumentException: The class representing the MobileServiceTable must have a single id property defined"
The id value that I need to insert into the database is being passed back from a fragment interface using passId(). Inside the override of this is where I am attempting to insert the values into azure as shown below.
#Override
public void passId(String id) {
userInstance user = new userInstance();
user.user_id = id;
user.first_login = 0;
mClient.getTable(userInstance.class).insert(user, new TableOperationCallback<userInstance>() {
public void onCompleted(userInstance entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
// Insert succeeded
} else {
// Insert failed
}
}
});
The mClient var represents the MobileServicesClient as shown below
try {
mClient = new MobileServiceClient(
"https://xxxx.azure-mobile.net/",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
this);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
The table name that I am trying to insert the data into is "user_table" if that helps at all.
I hope you're able to help, and thanks in advance for any help you guys give me.
SOLUTION:
Because the Azure Table that I was attempting to add data to auto created an "id" column, the user object that I was using to construct user info to insert into the database had to define an "id" String. As shown below:
public class userInstance {
#com.google.gson.annotations.SerializedName("id")
public String mId;
#com.google.gson.annotations.SerializedName("user_id")
public String mUserId;
#com.google.gson.annotations.SerializedName("first_login")
public int mLogin;
}
Related
I want to create the sqlite database file DatabaseName.db with few entities that should be created in path of application (/data/data/MyApplicationName/databases/DatabaseName.db) when I try to execute the snippet code bellow, however the DatabaseName.db file is not there. Why ?
MyDatabaseSample db = Room.databaseBuilder(context,
MyClass.class,
"DatabaseName.db")
.addCallback(new RoomDatabase.Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase ssdb) {
super.onCreate(db);
Log.d(TAG, "Database created - populate database");
}).build();
The database is created in the path of application only if I create an instance of a entity object and insert it in database right after get the database reference db. As I want to pre-populate database just after database creation, I think just make sense do it inside onCreate method of callback, but onCreate will never be called. So, How can I create the "DatabaseName.db" file with all tables representing entities and populate the database using callback ?
OBS: I am using Room version use 1.1.0-alpha2 and compiling with SDK android API 27.
I think you need to define some Room entities before pre-populate the db that's what i have done and it works just as expected, here is some code of what i have done so far:
public class DatabaseCreator {
private static MyDatabaseSample appDatabase;
private static final Object LOCK = new Object();
public synchronized static MyDatabaseSample getDBInstance(final Context context){
if(appDatabase == null) {
synchronized (LOCK) {
if (appDatabase == null) {
RoomDatabase.Callback appDBCallback = new RoomDatabase.Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
try {
ReadScript.insertFromFile(context, R.raw.populate_db, db);
} catch (IOException e) {
Log.d("DB Population Error", e.toString());
}
}
};
appDatabase = Room.databaseBuilder(context,
MyDatabaseSample.class, "DatabaseName").addCallback(appDBCallback).build();
}
}
}
return appDatabase;
}
}
The code above is a singleton that uses the Callback's onCreate to pre-populate the db using a "raw resource" (To add raw resources to your project just create a folder inside your res folder like this "res/raw") that contains an sql script. To read the script i have used this code:
public class ReadScript {
public static int insertFromFile(Context context, int resourceCode, SupportSQLiteDatabase db) throws IOException {
// Reseting Counter
int result = 0;
// Open the resource
InputStream insertsStream = context.getResources().openRawResource(resourceCode);
BufferedReader insertReader = new BufferedReader(new InputStreamReader(insertsStream));
// Iterate through lines (assuming each insert has its own line and theres no other stuff)
while (insertReader.ready()) {
String insertStmt = insertReader.readLine();
if(insertStmt != null){
if(insertStmt.isEmpty()) continue;
db.execSQL(insertStmt);
result++;
Log.d("Statement #", Integer.toString(result));
}
}
insertReader.close();
// returning number of inserted rows
return result;
}
}
And then you just create the db instance by doing:
MyDatabaseSample db = DatabaseCreator.getDBInstance(getContext());
Note: You can try to create tables inside the raw script but i haven't tried it yet.
Goog luck.
Hi i seem to be forever looking for an example of how to insert and retrieve data from Azure. I have managed to insert data into the azure easy table (happy days).I want to know how to retrieve that data and display it in a list view or even an alertDialog builder for all i care just need a way to view the data in my app.
using the code below i have managed to enter some data into the azure database.
public void saveToAzure(){
button_save_to_azure = (Button)findViewById(R.id.btnSaveDataToAzure);
button_save_to_azure.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myAzuretbl.SEEDNAME = edittext_seed_name_for_azure.getText().toString();
mClient.getTable(Azuretbl.class).insert(myAzuretbl, new TableOperationCallback<Azuretbl>() {
#Override
public void onCompleted(Azuretbl entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
// Insert succeeded
Toast myToast = Toast.makeText(getApplicationContext(),"Inserted", Toast.LENGTH_LONG);
myToast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
myToast.show();
edittext_seed_name_for_azure.setText("");
} else {
// Insert failed
Toast myFailToast = Toast.makeText(getApplicationContext(),"Not Inserted", Toast.LENGTH_LONG);
myFailToast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
myFailToast.show();
edittext_seed_name_for_azure.setText("");
}
}
});
}
}
);
}
At the moment i can enter 1 field into the database and i know how to enter more. I would like to now retrieve this data.
my local azure table looks like this at the moment:
package com.jonnyg.gardenapp;
public class Azuretbl {
public String Id;
public String SEEDNAME;
}
nothing special but it does the job.
I have looked at the documentation and none of it makes sense to me.looking at the new quick start guide and then looking at the documentation are completely different.
from the way i am doing it here is there a follow up in retriving the data and viewing it in either a list view or alertDialog builder?.
#JonnyG,
Could you please try to use the excute() method and refer to SDK document (https://github.com/Azure/azure-mobile-services/blob/master/sdk/android/src/sdk/src/main/java/com/microsoft/windowsazure/mobileservices/table/MobileServiceTable.java )?
Generally, we can retrieve the table rows as following:
MobileServiceList<Azuretbl> result =mClient.getTable(Azuretbl.class).execute().get();
for(Azuretbl item:result)
{
//your code
}
Also, you can check this official document sample(https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/#querying)
Hope this helps.
I am new to Android and Window Azure.I have created a database in Azure and some Tables.now I successfully inserted data to the table but now I want to delete a row from that table.I have tried the following code but its not working and the amulater gets hing .Please help me to solve this problem
//code use for delete.
del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final MobileServiceTable<Test> mtest;
mtest=mClient.getTable(Test.class);
try {
final MobileServiceList<Test>res=mtest.where().field("fullname").eq("hanan").execute().get();
mtest.delete("res");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
In the above code I just tried to delete the row whose fullname field =="hanan"
If you are using Moblie Service with SQL database as a backend server, there are 2 ways to delete an item form table referred on official guide
A, mTable.delete(item)
B, mTable.delete(IDString)
However, in your code:
mtest.delete("res");
you used a string in delete function, Azure will delete the row with id field equl “res”.
I'm using Parse.com services for an Android application but when I try to get datas from Parse, an error occurs:
com.parse.ParseException: corrupted json: org.json.JSONException: No value for code
Here is the code I use to get the datas:
public void getCategories() {
listCategories = new ArrayList<>();
ParseQuery<Category> query = ParseQuery.getQuery(Category.class);
query.findInBackground(new FindCallback<Category>() {
#Override
public void done(List<Category> categories, ParseException e) {
if (e == null) {
// Clear previously loaded Categories
listCategories.clear();
for (Category category : categories) {
// Fill the list with retrieved Categories
lsistCategories.add(category);
}
}else {
Log.d("Error happened while retrieving data:", e.getMessage());
}
}
});
}
Any idea of what could be the problem?
I solved it, in fact I forgot to register my custom Category class in my Application class.
I added this to the onCreate method in my Application class and now it works:
ParseObject.registerSubclass(Category.class);
Here are following my classes:
StatsObjectId.java
public class StatsObjectId extends Activity {
DBClass db;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
db = new DBClass(this);
}
public void addObjId(String objid){
Log.e("objectid","This is the object id going to store: "+objid);
db.addObjectId(objid); //This is the line# 105
if(getObjId()){
Log.e("objectid","Successfully stored!");
}else{
Log.e("objectid","Error in storing object id!");
}
}
public boolean getObjId(){
boolean result;
try{
c = db.getObjectId();
c.moveToFirst();
String str = c.getString(c.getColumnIndex("objectid"));
Log.e("objectid","Object id returned form DB: "+str);
result = true;
}catch(CursorIndexOutOfBoundsException e){
Log.e("objectid","Cursor index out of bound");
result = false;
e.printStackTrace();
}catch(Exception e){
Log.e("objectid","Some Another Exception");
result = false;
e.printStackTrace();
}
return result;
}
ParseComServerAccessor.java
public class ParseComServerAccessor {
//I am skipping some irrelevant code
public void putStats(String authtoken, String userId, Tas statsToAdd) throws Exception {
//Again skip some code
//Here I got some HttpResponse and I need to extract an object id and save it to database
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(responseString);
Log.e("objectid","Now Object Id is: "+json.getString("objectId") );
StatsObjectId ob = new StatsObjectId();
ob.addObjId(json.getString("objectId")); // This is the line#156
//skip some code
}
}
TasSyncAdapter.java
public class TasSyncAdapter extends AbstractThreadedSyncAdapter {
//skipped Constructor code
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
//skipped some code
ParseComServerAccessor parseComService = new ParseComServerAccessor();
//skipped some code again
parseComService.putStats(authToken, userObjectId, remoteTas); //This is the line# 134
//skip some code
}
}
Now finally when I run my app... this is the following Log Cat
Tag Text
objectid This is the object id going to store: 9AFysqffz7
System.err java.lang.NullPointerException
System.err at com.myapp.ds_app.StatsObjectId.addObjId(StatsObjectId.java:105)
System.err at com.myapp.ds_app.syncadapter.ParseComServerAccessor.putStats(ParseComServerAccessor.java:156)
System.err at com.myapp.ds_app.syncadapter.TasSyncAdapter.onPerformSync(TasSyncAdapter.java:134)
System.err at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:254)
DBClass.java
public class DBClass extends SQLiteOpenHelper {
private static final String DATABASE_NAME="myapp.db";
public DBClass(Context cxt){
super(cxt, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase mydatabase) {
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS temp (objectid STRING)");
}
public Cursor getObjectId(){
Cursor cursor = getReadableDatabase().rawQuery("SELECT objectid FROM temp", null);
return cursor;
}
public void addObjectId(String objid){
try{
ContentValues cv = new ContentValues(1);
Log.e("objectid","In DBClass and object id: "+objid);
cv.put("objectid", objid);
Log.e("objectid","Content value contains: "+cv.toString());
getWritableDatabase().insert("temp", "objectid", cv);
}catch(NullPointerException e){
e.printStackTrace();
}
}
}
Now, I am stucked at this point!
So far, I need to save just a single value. I tried to create a file instead of saving a value in database. But again there is some exception of ContextWrapper.
I am currently interested to deal with database.
Please let me know if you guys need any other information.
I would really appreciate if any one please explain this thing. I'm android newbie and would love to learn about this problem. Thanks in advance!
StatsObjectId ob = new StatsObjectId();
You are instanciating an Activity class. You are not allowed to do that. (There should really be something in Android to tell you when you do that) Basically, the context is not initialized, because android needs to do that in order to have a functional Activity.
Plus, Android (when it creates the Activity) calls the onCreate method with a proper context. You don't (and you can't, either), therefore your db is null.
In AbstractThreadedSyncAdapter, you have a getContext method to get a proper context. Use this to initialize your database and to insert data in it, rather than passing it to the Activity object.