ORMLite examples for Android won't compile - java

I have been trying to work through the HelloAndroid example for ORMLite but haven't been able to successfully compile. I am having a problem with the DatabaseHelper class. Specifically the getDao() method:
/**
* Returns the Database Access Object (DAO) for our SimpleData class.
* It will create it or return the cached value.
*/
public Dao<SimpleData, Integer> getDao() throws SQLException {
if (simpleDao == null) {
simpleDao = getDao(SimpleData.class);
}
return simpleDao;
}
Here is the compile time error I am receiving:
Type parameters of D cannot be determined; no unique maximal instance exists for type variable D with upper bounds com.j256.ormlite.dao.Dao,com.j256.ormlite.dao.Dao

I got a similar error when trying to build my ormlite project using Netbeans:
Compiling 15 source files to ~/NetBeansProjects/Main/build/classes
Main.java:74: type parameters of D cannot be determined;
no unique maximal instance exists for type variable D with upper bounds
com.j256.ormlite.dao.Dao,com.j256.ormlite.dao.Dao
pcDao = DaoManager.createDao(connectionSource, PC.class);
Due to the comments I switched my Java Platform from OpenJDK 1.6 to Oracle's JDK 1.7.0_02 and it resolved the issue.

My solution:
public class HelloAndroid extends OrmLiteBaseActivity<DatabaseHelper>
{
private final String LOG_TAG = getClass().getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.i(LOG_TAG, "creating " + getClass() + " at " + System.currentTimeMillis());
TextView tv = new TextView(this);
doSampleDatabaseStuff("onCreate", tv);
setContentView(tv);
}
/**
* Do our sample database stuff.
*/
private void doSampleDatabaseStuff(String action, TextView tv)
{
// get our dao
RuntimeExceptionDao<SimpleData, Integer> simpleDao = getHelper().getSimpleDataDao();
// query for all of the data objects in the database
List<SimpleData> list = simpleDao.queryForAll();
// our string builder for building the content-view
StringBuilder sb = new StringBuilder();
sb.append("got ").append(list.size()).append(" entries in ").append(action).append("\n");
// if we already have items in the database
int simpleC = 0;
for (SimpleData simple : list)
{
sb.append("------------------------------------------\n");
sb.append("[").append(simpleC).append("] = ").append(simple).append("\n");
simpleC++;
}
sb.append("------------------------------------------\n");
for (SimpleData simple : list)
{
simpleDao.delete(simple);
sb.append("deleted id ").append(simple.id).append("\n");
Log.i(LOG_TAG, "deleting simple(" + simple.id + ")");
simpleC++;
}
int createNum;
do
{
createNum = new Random().nextInt(3) + 1;
}
while (createNum == list.size());
for (int i = 0; i < createNum; i++)
{
// create a new simple object
long millis = System.currentTimeMillis();
SimpleData simple = new SimpleData(millis);
// store it in the database
simpleDao.create(simple);
Log.i(LOG_TAG, "created simple(" + millis + ")");
// output it
sb.append("------------------------------------------\n");
sb.append("created new entry #").append(i + 1).append(":\n");
sb.append(simple).append("\n");
try
{
Thread.sleep(5);
}
catch (InterruptedException e)
{
// ignore
}
}
tv.setText(sb.toString());
Log.i(LOG_TAG, "Done with page at " + System.currentTimeMillis());
}
}

Related

Android subscription purchase AccountHold is null

I am using official google example code for user subscription play-billing-sample. I get nullpointexception on checking the account hold when switching google accounts (my phone has two google accounts registered as test accounts to test the purchases).
I log into the first account without any problems and purchase basic or premium subscriptions
when I switch to the second account, I get the error below:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference at com.pishimishi.test.classytaxijava.billing.BillingUtilities.isAccountHold(BillingUtilities.java:151)
BillingUtilities.java:
/**
* Returns true if account hold should be shown.
*/
public static boolean isAccountHold(SubscriptionStatus subscription) {
return subscription != null &&
!subscription.isEntitlementActive &&
subscription.isAccountHold &&
!subscription.subAlreadyOwned;
}
and SubscriptionStatus.java:
/**
* Local subscription data. This is stored on disk in a database.
*/
#Entity(tableName = "subscriptions")
public class SubscriptionStatus {
public class SubscriptionStatusList {
#Nullable
#SerializedName("subscriptions")
List<SubscriptionStatus> subscriptionStatuses;
SubscriptionStatusList(#Nullable List<SubscriptionStatus> subscriptionStatuses) {
this.subscriptionStatuses = subscriptionStatuses;
}
}
public static final String SUBSCRIPTIONS_KEY = "subscriptions";
public static final String SKU_KEY = "sku";
public static final String PURCHASE_TOKEN_KEY = "purchaseToken";
public static final String IS_ENTITLEMENT_ACTIVE_KEY = "isEntitlementActive";
public static final String WILL_RENEW_KEY = "willRenew";
public static final String ACTIVE_UNTIL_MILLISEC_KEY = "activeUntilMillisec";
public static final String IS_FREE_TRIAL_KEY = "isFreeTrial";
public static final String IS_GRACE_PERIOD_KEY = "isGracePeriod";
public static final String IS_ACCOUNT_HOLD_KEY = "isAccountHold";
// Local fields
#PrimaryKey(autoGenerate = true)
public int primaryKey = 0;
#Nullable
public String subscriptionStatusJson;
public boolean subAlreadyOwned;
public boolean isLocalPurchase;
// Remote fields
#Nullable
public String sku;
#Nullable
public String purchaseToken;
public Boolean isEntitlementActive;
public Boolean willRenew;
public Long activeUntilMillisec = 0L;
public Boolean isFreeTrial;
public Boolean isGracePeriod;
public Boolean isAccountHold;
/**
* Parse subscription data from Map and return null if data is not valid.
*/
#Nullable
public static List<SubscriptionStatus> listFromMap(Map<String, Object> map) {
List<SubscriptionStatus> subscriptions = new ArrayList<>();
List<Map<String, Object>> subList = null;
if (map.get(SUBSCRIPTIONS_KEY) instanceof ArrayList) {
subList = (ArrayList) map.get(SUBSCRIPTIONS_KEY);
}
if (subList == null) {
return null;
}
for (Map<String, Object> subStatus : subList) {
SubscriptionStatus subscriptionStatus = new SubscriptionStatus();
subscriptionStatus.sku = (String) subStatus.get(SKU_KEY);
subscriptionStatus.purchaseToken = (String) subStatus.get(PURCHASE_TOKEN_KEY);
subscriptionStatus.isEntitlementActive =
(Boolean) subStatus.get(IS_ENTITLEMENT_ACTIVE_KEY);
subscriptionStatus.willRenew = (Boolean) subStatus.get(WILL_RENEW_KEY);
subscriptionStatus.activeUntilMillisec =
(Long) subStatus.get(ACTIVE_UNTIL_MILLISEC_KEY);
subscriptionStatus.isFreeTrial = (Boolean) subStatus.get(IS_FREE_TRIAL_KEY);
subscriptionStatus.isGracePeriod = (Boolean) subStatus.get(IS_GRACE_PERIOD_KEY);
subscriptionStatus.isAccountHold = (Boolean) subStatus.get(IS_ACCOUNT_HOLD_KEY);
subscriptions.add(subscriptionStatus);
}
return subscriptions;
}
/**
* Parse subscription data from String and return null if data is not valid.
*/
#Nullable
public static List<SubscriptionStatus> listFromJsonString(String dataString) {
Gson gson = new Gson();
try {
SubscriptionStatusList subscriptionStatusList =
gson.fromJson(dataString, SubscriptionStatusList.class);
if (subscriptionStatusList != null) {
return subscriptionStatusList.subscriptionStatuses;
} else {
return null;
}
} catch (JsonSyntaxException e) {
return null;
}
}
/**
* Create a record for a subscription that is already owned by a different user.
*
* The server does not return JSON for a subscription that is already owned by
* a different user, so we need to construct a local record with the basic fields.
*/
public static SubscriptionStatus alreadyOwnedSubscription(String sku, String purchaseToken) {
SubscriptionStatus subscriptionStatus = new SubscriptionStatus();
subscriptionStatus.sku = sku;
subscriptionStatus.purchaseToken = purchaseToken;
subscriptionStatus.isEntitlementActive = false;
subscriptionStatus.subAlreadyOwned = true;
return subscriptionStatus;
}
#Override
public String toString() {
return "SubscriptionStatus{" +
"primaryKey=" + primaryKey +
", subscriptionStatusJson='" + subscriptionStatusJson + '\'' +
", subAlreadyOwned=" + subAlreadyOwned +
", isLocalPurchase=" + isLocalPurchase +
", sku='" + sku + '\'' +
", purchaseToken='" + purchaseToken + '\'' +
", isEntitlementActive=" + isEntitlementActive +
", willRenew=" + willRenew +
", activeUntilMillisec=" + activeUntilMillisec +
", isFreeTrial=" + isFreeTrial +
", isGracePeriod=" + isGracePeriod +
", isAccountHold=" + isAccountHold +
'}';
}
}
I don't understand it why I have to get NPE. Or if we get if from the server, why don't I get it with the first account (I even tested putting the purchase on pause for the first account) and it works.
PS. Initially in my play console, Account hold feature was not active, but later on, I activated the account hold and account pause feature. But still I get the same error just after switching to the second google account.
Every time when Java uses Boolean object in if statement it unwraps it to primitive which is boolean type with Boolean.booleanValue() method.
To fix the issue you have to change isAccountHold and isEntitlementActive types from Boolean to boolean.
If those fields have to be Boolean type then check them for null before:
public static boolean isAccountHold(SubscriptionStatus subscription) {
return subscription != null &&
(subscription.isEntitlementActive == null || !subscription.isEntitlementActive) &&
(subscription.isAccountHold != null || subscription.isAccountHold) &&
!subscription.subAlreadyOwned;
}

How to create two instances of the same method with different parameters

I need to create 2 instances that run the same SQL procedure but with different parameters.
public void run() {
// TRUE if there is no more VER_STOCK
boolean booEsgotado = false;
System.out.println("Starting thread" + numThread );
try {
objLigacao = DriverManager.getConnection(LIGACAO,
UTILIZADOR, SENHA);
// manual control of transactions
objLigacao.setAutoCommit(false);
while (booEsgotado == false && i<=5) {
try {
objComando = objLigacao.prepareCall(INSERE);
// 1 = first parameter (:1)
objComando.setInt(1, ID);
objComando.setInt(2, PRODUTO);
objComando.setInt(3, Q);
objComando.execute();
objComando.close();
// If done with success commit the operations
objLigacao.commit();
i++;
System.out.println("Sold a unit in thread " + numThread + " i = " + i);
objComando = objLigacao.prepareCall(QUANT);
objComando.setInt(1, PRODUTO);
objResultado = objComando.executeQuery();
while(objResultado.next()) {
stock=objResultado.getInt(1);}
System.out.println("Stock atual=" + stock);
}
catch (SQLException objExcepcao) {
System.out.println("" + objExcepcao.getMessage());
// If something failed rollback the operations
objComando.close();
objLigacao.rollback();
booEsgotado = true;
System.out.println("Product is out of stock in thread" + numThread);
}
}
// Libertação de recursos.
objLigacao.close();
} catch (SQLException objExcepcao) {
System.out.println(objExcepcao.getMessage());
}
System.out.println("The end of thread " + numThread );
}
The thing is that I can only run the same procedure with the same arguments in both instances. Where I need to execute the same procedure but with different arguments in both instances.
runne1 objInstancia1 = new runne1(1);
runne1 objInstancia2 = new runne1(2);
// Create a thread for each instance
Thread objThread1 = new Thread(objInstancia1);
Thread objThread2 = new Thread(objInstancia2);
objThread1.start();
objThread2.start();
try {
objThread1.join();
objThread2.join();
Subclass Thread to provide a constructor that specifies parameters you need and store them as instance fields.
In this way, you could use them in the run() method.
public class MyCallThread extends Thread {
private int paramOne;
private int paramTwo;
public MyCallThread (Runnable runnable, int paramOne, int paramTwo){
super(runnable);
this.paramOne = paramOne;
this.paramTwo = paramTwo;
}
public void run(){
...
objComando.setInt(1, paramOne);
...
}
}
And instantiate it like that :
int paramOne = ...;
int paramTwo = ...;
Thread objThread1 = new MyCallThread(objInstancia1, paramOne, paramTwo);
...

detect concurrent access to syncronized function java

I Have a multithreaded environment in android app. I use a singleton class to store data. This singleton class contains a arraylist that is accessed using a synchronized method.
The app uses this arraylist to render images in app.
Initial problem : Concurrent modification error use to come so I made the get arraylist function syncronized.
Current Problem:Concurrent modification error not coming but in between empty arraylist returned (maybe when there is concurrent access).
Objective : I want to detect when Concurrent modification so that Instead of empty arraylist being return I can return last state of the arraylist.
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
//for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
Referred to Detecting concurrent modifications?
Please help!
EDIT1:
This problem occurs rarely not everytime.
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?? I'm new to multithreading , please guide
Edit 2
in oncreate following methods of singleton are called periodically
DataModelManager.getInstance().getCurrentDataToShow();
DataModelManager.getInstance().parseData(responseString);
Complete singleton class
public class DataModelManager {
private static DataModelManager dataModelManager;
private ImageFrameActivity imageFrameAct;
private String defaultFileName;
public List<FrameData> listFrameData = new ArrayList<FrameData>();
// public CopyOnWriteArrayList<FrameData> listFrameData= new CopyOnWriteArrayList<FrameData>();
private String screensaverName;
private boolean isToDownloadDeafultFiles;
private String tickerMsg = null;
private boolean showTicker = false;
private boolean showHotspot = false;
private String hotspotFileName=null;
public String getDefaultFileName() {
return defaultFileName;
}
public boolean isToDownloadDeafultFiles() {
return isToDownloadDeafultFiles;
}
public void setToDownloadDeafultFiles(boolean isToDownloadDeafultFiles) {
this.isToDownloadDeafultFiles = isToDownloadDeafultFiles;
}
private String fileNames;
private DataModelManager() {
}
public static DataModelManager getInstance() {
if (dataModelManager == null) {
synchronized (DataModelManager.class) {
if (dataModelManager == null) {
dataModelManager = new DataModelManager();
}
}
}
return dataModelManager;
}
private synchronized void addImageData(FrameData frameData) {
//Log.d("Frame Data","Start date "+frameData.getStartDate()+ " " +"end date "+frameData.getEndDate());
listFrameData.add(frameData);
}
public synchronized void parseData(String jsonStr) throws JSONException {
listFrameData.clear();
if (jsonStr == null) {
return;
}
List<String> listFileNames = new ArrayList<String>();
JSONArray jsonArr = new JSONArray(jsonStr);
int length = jsonArr.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
dataModelManager.addImageData(new FrameData(jsonObj.optString("filename", ""), jsonObj.optString("start", ""), jsonObj.optString("end", ""), jsonObj.optString("filetype", ""), jsonObj.optString("playTime", ""), jsonObj.optBoolean("allDay", false)));
listFileNames.add(jsonObj.optString("filename", ""));
}
fileNames = listFileNames.toString();
}
public void setDefaultFileData(String jsonStr) throws JSONException {
JSONObject jsonObj = new JSONObject(jsonStr);
defaultFileName = jsonObj.optString("default_image", "");
screensaverName = jsonObj.optString("default_screensaver ", "");
}
#Override
public String toString() {
return fileNames.replace("[", "").replace("]", "") + "," + defaultFileName + "," + screensaverName;
}
public FrameData getFrameData(int index) {
return listFrameData.get(index);
}
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
// for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
public String getCurrentFileNames() {
String currFileNames = "";
List<FrameData> currFrameData = getCurrentDataToShow();
for (FrameData data : currFrameData) {
currFileNames += "," + data.getFileName();
}
return currFileNames;
}
public ImageFrameActivity getImageFrameAct() {
return imageFrameAct;
}
public void setImageFrameAct(ImageFrameActivity imageFrameAct) {
this.imageFrameAct = imageFrameAct;
}
}
This is the only part of your question that is currently answerable:
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?
It depends on whether you are calling getCurrentDataToShow() on the same target object; i.e. what this is.
If this is the same for both calls, then the first call will complete before the second call starts.
If this is different, you will be locking on different objects, and the two calls could overlap. Two threads need to lock the same object to achieve mutual exclusion.
In either case, this method is not changing the listFrameData collection. Hence it doesn't matter whether the calls overlap! However, apparently something else is changing the contents of the collection. If that code is not synchronizing at all, or if it is synchronizing on a different lock, then that could be a source of problems.
Now you say that you are not seeing ConcurrentModificationException's at the moment. That suggests (but does not prove) that there isn't a synchronization problem at all. And that suggests (but does not prove) that your current problem is a logic error.
But (as I commented above) there are reasons to doubt that the code you have shown us is an true reflection of your real code. You need to supply an MVCE if you want a more definite diagnosis.

Creating 140,000-row SQLite database in AsyncTask doInBackground taking many, many minutes

I haven't dealt with SQLite databases before last week. I last dealt with SQL many years ago, but I still have the gist of it.
The code below reads 140,000 words from an asset named dictionary.dic and inserts each into a SQLite database along with its status. My expectation was that it would take a good while, but it's been like 25 minutes on a 7" tablet and still not near finished (on P).
Should I say, "Hey, it's 1/7 of a million rows. It's gonna take awhile." But I can read all 140,000 words into an ArrayList<String> in 30 seconds. I realize there's overhead in creating the database, but many, many minutes?
Should I say, "Well, think how long it would take if not using AsyncTask" and accept it since it's a one-time task? But it's really obnoxious, taking so long. It's off-putting.
Should I say, "Why are you using a Scanner? No wonder it's taking so long?" and do some other asset access? Or is that not the real problem?
I also have never used AsyncTask. Am I misusing doInBackground? I've got a lot of code in there; not all MUST go there, but the loop is what it is and there's the hangup.
Is using database.Insert, which is called a "convenience method", what's causing the hangup? Should I be using a Cursor and query instead? I'm not entirely sure how I'd do that. Got my idea from Deitel's "Address Book" app in "Android for Programmers--App Driven...", but his database is empty at the outset.
I've given this plenty of thought. I just need someone with experience to look and say, "Well, HERE'S your problem." I can't justify starting redoing all the things I've thought of without some guidance about whether any of it is going to help.
public class DatabaseConnector //extends ArrayList<String>
{
public static Cursor cursor ;
Scanner scDict;
InputStream stream = null;
Context mContext;
AssetManager mAssets;
public static final String DATABASE_NAME = "Dictionary";
public static final String TABLE_NAME = "wordlist";
public static final String WORD_COLUMN_NAME = "word";
public static final String STATUS_COLUMN_NAME = "status";
public static final String [] columns = new String[]{WORD_COLUMN_NAME, STATUS_COLUMN_NAME};
private DatabaseOpenHelper ___databaseOpenHelper; // creates the database
private SQLiteDatabase ___database; // for interacting with the database
public DatabaseConnector(Context _context, AssetManager assets)
{
mContext = _context;
mAssets = assets;
___databaseOpenHelper = new DatabaseOpenHelper(_context, DATABASE_NAME, null, 1);
Log.w("DB connected", ___databaseOpenHelper.getDatabaseName());
createDbIfNecessary();
};
public void open() throws SQLException // opens/creates
{
___database = ___databaseOpenHelper.getWritableDatabase(); // create OR open
}
public void createDbIfNecessary(){
this.open();
if(getDbCount() < 140000){
try { stream = mAssets.open("dictionary.dic"); }
catch (IOException e) { System.out.println(Arrays.toString(e.getStackTrace())); }
MainActivity.setLblProgress("This one-time task takes awhile: loading letter... ");
LoadWords loadWords = new LoadWords();
loadWords.execute((Object[]) null);
this.close();
}
}
public void close(){
if(___database != null)
___database.close();
}
public int getDbCount(){
this.open();
return ___database.query(TABLE_NAME, columns, null, null, null, null, null).getCount();
}
public long insertWord(String _word)
{
ContentValues
__newWord;
__newWord = new ContentValues();
__newWord.put(WORD_COLUMN_NAME, _word);
__newWord.put(STATUS_COLUMN_NAME, true);
long __row = ___database.insert(TABLE_NAME, null, __newWord);
return __row; // -1 if can't insert
}
//////////////////////////////////////////////////////////////////////////////////////////////////
private class DatabaseOpenHelper extends SQLiteOpenHelper
{
public DatabaseOpenHelper(Context _context, String _name, CursorFactory _factory, int _version)
{ super(_context, _name, _factory, _version); }
#Override public void onCreate(SQLiteDatabase _db)
{
_db.execSQL( "CREATE TABLE " + TABLE_NAME +
"("
+ WORD_COLUMN_NAME + " TEXT primary key , " //not null, "
+ STATUS_COLUMN_NAME + " BOOLEAN" +
");"
); // execute query to create the ___database
}
} // end class DatabaseOpenHelper
//////////////////////////////////////////////////////////////////////////////////////////////////
private class LoadWords extends AsyncTask<Object, Integer, Void>
{
#Override
protected Void doInBackground(Object... params) {
long k = 0;
scDict = new Scanner(stream).useDelimiter("\r\n");
long count = getDbCount();
Log.w("Start load at " , "" + count);
String s = "";
while(k++ < count){
s = scDict.next();
}
Log.w("Add after " , s);
while (scDict.hasNext())
{
s = scDict.next();
publishProgress((Integer)(int)s.charAt(0));
insertWord(s) ;
return null;
}
protected void onProgressUpdate(Integer... progress) {
int c = (int)progress[0];
MainActivity.setLastLetterProcessed((char) c);
}
#Override
protected void onPostExecute(Void x)
{
MainActivity.popupMessage("Database has been created", mContext);
}
}
} // end class DatabaseConnector
You are attempting to do 140,000 individual database transactions. That might take weeks.
Instead, either wrap your entire thing in a single transaction, or batch the inserts into transactions (e.g., every 1000 words). You can create your own transaction bounds using this pseudo-Java:
db.beginTransaction();
try {
// do your SQL work here
db.setTransactionSuccesful();
}
catch (Exception e) {
// logging, event bus message to UI, whatever
}
finally {
db.endTransaction();
}
Thanks to #Commonsware, the 140,000 records now load in under a minute, as opposed to under an HOUR. All I did was use his "p-code" to surround my insert with a 1000-count loop:
protected Void doInBackground(Object... params) {
...
scDict = new Scanner(stream).useDelimiter("\r\n");
long count = getDbCount();
while (k++ < count)
s = scDict.next();
while (scDict.hasNext())
{
//////////////////////////////////////////////////////// start insert
int ki = 0;
try
{
___database.beginTransaction();
while (ki < MAX_TRANSACTIONS && scDict.hasNext())
{
//////////////////////////////////////////////////////// end
insertWord(scDict.next());
//////////////////////////////////////////////////////// start insert
++ki;
}
___database.setTransactionSuccessful();
}
catch(Exception e){ Log.w("Exception",e);}
finally
{
___database.endTransaction();
publishProgress((Integer) (int) s.charAt(0));
}
//////////////////////////////////////////////////////// end
}
return null;
}
...
}

ParseObject as a data to the table/chart

I'm new in coding and I have a problem to understand something. I follow the example form Parse.com Doc and wrote this.
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
int object_value = Integer.parseInt(obiect);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
I understand this like:
I send query to server
get obiect with "lxFzCTeOcl" id
if there is no exception I create String object which takes string
form "value" column.
convert String to int
My question is: How can I use object_value for example to make a chart or put it into a table?
Here we will add the array list to your code and start to store an object inside the array every time we call the getData method in your class.
private ArrayList<Integer> dataArray;
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(obiect);
if(dataArray==null)
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
And here I'm just adding a simple example of how to create a simple pie chart using our array list (note that I used the lib AChartEngine http://www.achartengine.org/):
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private GraphicalView createPieChart(ArrayList<Integer> data){
GraphicalView chartView;
CategorySeries series = new CategorySeries("PIE");
for (int i = 0; i < VALUES.length; i++) {
series.add(i, data.get(i));
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(series.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
chartView = ChartFactory.getPieChartView(this, series, new DefaultRenderer());
chartView.repaint();
return chartView;
}
Now you can add this GraphicalView to your view.
The returned object is much like a map, with key/value pairs. In your example, the key is "value", which makes it a little confusing, but it would be like this if you wanted all fields:
for (Field field : myInstance.getClass().getDeclaredFields()) {
String name = field.getName();
value = field.get(myInstance).toString();
map.put(name, value);
}

Categories