Whats wrong with my code? I used ClassName instead of variable name? BTW I want to create an EditText for my quiz with an answer - android-edittext

I get the text
"Error:(45, 37) error: non-static method getText() cannot be referenced from a static context"
Did I use ClassName instead of variable name?
I want to create an EditText for my quiz where the user has to put in the answer, how do I do that?
Thank you for your help
package com.example.android.myquizapp2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getResults(View view) {
/*
Code for answers
*/
boolean answerArray[];
answerArray = new boolean[10];
RadioButton answer = (RadioButton) findViewById(R.id.answerOne);
answerArray[0] = answer.isChecked();
answer = (RadioButton) findViewById(R.id.question22group);
answerArray[1] = answer.isChecked();
answer = (RadioButton) findViewById(R.id.question13group);
answerArray[2] = answer.isChecked();
answer = (RadioButton) findViewById(R.id.question14group);
answerArray[4] = answer.isChecked();
CheckBox answerCheckBox = (CheckBox) findViewById(R.id.taipei);
answerArray[5] = answerCheckBox.isChecked();
EditText answerEditText = (EditText) findViewById(R.id.question01group);
answerArray[6] = answerEditText.isTextSelectable();
This is where I have my mistake(I get the text
"Error:(45, 37) error: non-static method getText() cannot be referenced from a static context")
String UserAnswer = EditText.getText().trim();
Boolean truth = UserAnswer.equals(answerEditText);
/*
Score
*/
int score = calculateScore(answerArray);
displayScore(calculateScore(answerArray));
if (score == 5)
score = 'A';
if (score == 4)
score = 'B';
else if (score == 3)
score = 'C';
else if (score == 2)
score = 'D';
else if (score == 1)
score = 'E';
else
score = 'F';
System.out.println("Score: " + score + " score: " + score);
}
private int calculateScore(boolean scoreArray[]) {
int Score = 0;
for (int i = 0; i < 10; i++) {
if (scoreArray[i]) {
Score = Score + 1;
}
}
return Score;
}
/*
I wrote return Score instead of methodScore
*/
/*
Method score on screen
*/
private void displayScore(int finalScore) {
Toast scoreMessage = Toast.makeText(this, "Good job!" + finalScore, Toast.LENGTH_SHORT);
scoreMessage.show();
}
/*
Method which will show the correct answers
*/
public void correctAnswers(View view) {
ScrollView scrollToTop = (ScrollView) findViewById(R.id.mainScrollView);
scrollToTop.fullScroll(ScrollView.FOCUS_UP);
RadioGroup choiceGroup = (RadioGroup) findViewById(R.id.question1group);
choiceGroup.check(R.id.answerOne);
choiceGroup = (RadioGroup) findViewById(R.id.question2group);
choiceGroup.check(R.id.question22group);
choiceGroup = (RadioGroup) findViewById(R.id.question3group);
choiceGroup.check(R.id.question13group);
choiceGroup = (RadioGroup) findViewById(R.id.question4group);
choiceGroup.check(R.id.question14group);
Toast infoMessage =
Toast.makeText(this, "These are the correct answers for the quiz.", Toast.LENGTH_LONG);
infoMessage.show();
}
}

you need to take EditText object like answerEditText.getText().toString().trim(); instead of calling the class name

Related

how save first three best scores

How save best first three scores or only best score, I am new in programming.
I have score, but how define new score and old score.
public class HighScores extends Activity {
private TextView thighscore1;
private TextView thighscore2;
private TextView thighscore3;
public TextView name;
public int highscore1 =0;
public int highscore2 =0;
public int highscore3 =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high);
name = (TextView) findViewById(R.id.Names);
thighscore1 = (TextView) findViewById(R.id.highscore1);
thighscore2 = (TextView) findViewById(R.id.highscore2);
thighscore3 = (TextView) findViewById(R.id.highscore3);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey",
Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
thighscore1.setText("" + score);
if(score > highscore2) {
highscore1 = score;
thighscore1.setText("" + highscore1);
}else{
highscore1=highscore1;
}
if(score > highscore3 && score < highscore1){
highscore2 = score;
thighscore2.setText("" + highscore2);
}else{
highscore2 = highscore2;
}
if (score > 0 && score < highscore2){
highscore3 = score;
thighscore3.setText("" + highscore3);
}else{
highscore3 = highscore3;
}
SharedPreferences sp = this.getSharedPreferences("MyKey",0);
String data = sp.getString("tag", "");
name.setText(""+ data);
}}
For setting scores in Preference:
SharedPreferences.Editor editor = getSharedPreferences("PreferenceName",MODE_PRIVATE).edit();
editor.putInt("Score1", highscore1);
editor.putInt("Score2", highscore2);
editor.putInt("Score3", highscore3);
editor.apply();
For retrieving scores from Preference:
SharedPreferences prefs = getSharedPreferences("PreferenceName",MODE_PRIVATE);
if(prefs.getString("text", null) != null) {
int score1 = prefs.getInt("Score1", 0); // 0 is the default value
int score2 = prefs.getInt("Score2", 0);
int score3 = prefs.getInt("Score3", 0);
}
More information on SharedPreferences
To delete any value from Preference
editor.remove("highscore1"); // will delete highscore1
I resolved my problem with score also have a name:
if (number > prefs.getInt("key", 0)) {
editor.putInt("key", number);
editor.putString("tag", value);
} else if (number < prefs.getInt("key", 0)) {
if (number > prefs.getInt("key1", 0)) {
editor.putInt("key1", number);
editor.putString("tag1", value1);
}
}
if (number < prefs.getInt("key1", 0)) {
editor.putInt("key2", number);
editor.putString("tag2", value2);
}

Why does this priority queue implementation only print one value repeatedly?

This program should print out the values in order ascending order. But it only displays 957.0 repeatedly. How do I display the numbers in order?
import java.io.*;
import java.util.*;
class PriorityQ {
public int maxSize;
public double[] queArray;
public int nItems;
//------
public PriorityQ(int s){
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
//-----
public void insert(double item){
int j;
if(nItems == 0){
queArray[nItems++] = item;
}
else{
for(j = nItems-1; j >= 0; j--){
if(item > queArray[j]){
queArray[j + 1] = item;
}
else{
break;
}
}
queArray[j + 1] = item;
nItems++;
}
}
//-----
public double remove(){
return queArray[--nItems];
}
//-----
public double peekMin(){
return queArray[nItems - 1];
}
//-----
public boolean isEmpty(){
return(nItems == 0);
}
//-----
public boolean isFull(){
return(nItems == maxSize);
}
}
//-----
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(546);
thePQ.insert(687);
thePQ.insert(36);
thePQ.insert(98);
thePQ.insert(957);
while(!thePQ.isEmpty()){
double item = thePQ.remove();
System.out.print(item + " ");
}
System.out.println("");
}
}
You should save yourself the effort and use a priority queue with the generic type Double. If you wanted descending order you could even use a comparator that orders the highest value before the lowest, but you asked for ascending.
Your problem is that your array does contain many copies of 957.
This is because of this line in your code:
if(item > queArray[j]){
queArray[j + 1] = item;
}
Try:
import java.io.*;
import java.util.*;
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQueue<Double> thePQ = new PriorityQueue<Double>(5);
thePQ.add(546);
thePQ.add(687);
thePQ.add(36);
thePQ.add(98);
thePQ.add(957);
while(thePQ.size() > 0){
double item = thePQ.poll();
System.out.print(item + " ");
}
System.out.println("");
}
}
Or I can fix your code to print out the queue in descending order leaving it to you to then make it print out in ascending order, the block I pointed to before should read like this instead:
if(item < queArray[j]){
queArray[j + 1] = queArray[j];
}

Get data only one folder not for all folders in treeview - Blackberry

i want to show all folders(images, videos,files) with directories/files, currently only show images folder with files, but other folder are not show. I try to find solution but not found. Here is the code & its screenshot(http://postimg.org/image/wm5ypbk9d/).
FileManager.java
package com.rim.samples.device.mapactiondemo;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
public class FilesManager extends MainScreen {
FTPMessages _ftp = null;
String[] fileList;
// ..................
private final Bitmap openIcon = Bitmap.getBitmapResource("open.png");
private final Bitmap closedIcon = Bitmap.getBitmapResource("closed.png");
private final Bitmap movieIcon = Bitmap.getBitmapResource("movie.png");
private final Bitmap songIcon = Bitmap.getBitmapResource("song.png");
private final Bitmap playIcon = Bitmap.getBitmapResource("play.png");
private final Bitmap imgIcon = Bitmap.getBitmapResource("images.png");
String nodeTen;
int node10;
TreeField myTree;
String[] nodeData;
// ListField to be displayed - null - no Field displayed
// List of entries to be displayed - null or length = 0 means no entries
// protected so that another Thread can update this list....
protected ListDirectory[] _resultsList = null; // entries available for
// display
private ListDirectory _selectedEntry = null;
public FilesManager(FTPMessages ftp) {
super();
_ftp = ftp;
// Setting starting directory
try {
/*
* fileList = _ftp.list(); for (int i = 0; i < fileList.length; i++)
* { _ftp.cwd(fileList[i]); }
*/
_ftp.cwd("images");
_ftp.cwd("files");
_ftp.cwd("videos");
} catch (Exception e) {
}
this.setTitle("Server File List");
TreeCallback myCallback = new TreeCallback();
myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0
&& (status & KeypadListener.STATUS_SHIFT) == 0) {
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node. Do some default action or
// else fall through.
// Note: this will also detect empty folders, which
// might or
// might not be something your app has to handle
Dialog.alert("clicked " + getCookie(node));
// TODO: open player screen, etc.
return true;
}
}
return super.navigationClick(status, time);
}
};
myTree.setDefaultExpanded(false);
myTree.setRowHeight(openIcon.getHeight());
try {
node10 = myTree.addChildNode(0, _ftp.pwd());
} catch (Exception e) {
}
this.add(myTree);
refreshList();
}
private void refreshList() {
// TODO Auto-generated method stub
_resultsList = null;
String[] directory = null;
try {
directory = _ftp.list();
} catch (Exception e) {
}
if (directory != null && directory.length > 0) {
_resultsList = new ListDirectory[directory.length];
for (int i = 0; i < directory.length; i++) {
_resultsList[i] = new ListDirectory(directory[i],
ListDirectory.UNIX_SERVER);
}
}
if (_resultsList != null && _resultsList.length > 0) {
// we have some results
for (int i = 0; i < _resultsList.length; i++) {
String bb = directory[i];
String nodeFive = new String(bb);
this.myTree.addChildNode(node10, nodeFive);
}
} else {
}
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
final int PAD = 8;
String text = (String) _tree.getCookie(node);
Bitmap icon = closedIcon;
if (text.endsWith(".mp3")) {
icon = songIcon;
} else if (text.endsWith(".avi")) {
icon = movieIcon;
} else if (text.endsWith(".png") || text.endsWith(".jpg")) {
icon = imgIcon;
} else if (_tree.getExpanded(node)) {
icon = openIcon;
}
g.drawBitmap(indent, y, icon.getWidth(), icon.getHeight(), icon, 0,
0);
// This assumes filenames all contain '.' character!
if (text.indexOf(".") > 0) {
// Leaf node, so this is a playable item (movie or song)
g.drawBitmap(_tree.getWidth() - playIcon.getWidth() - PAD, y
+ PAD, playIcon.getWidth(), playIcon.getHeight(),
playIcon, 0, 0);
}
int fontHeight = getFont().getHeight();
g.drawText(text, indent + icon.getWidth() + PAD,
y + (_tree.getRowHeight() - fontHeight) / 2);
}
}
}
The other classes that used with this code, download from that link(complete project classes)
http://remote.offroadstudios.com/files/filemanager.zip
you can also check files on server, ip:64.207.150.31:21, username:remote, password:123456789

How to get multiple selected list items from list field checkbox and add into an arraylist in blackberry

Please anyone help me get selected listitems from a listfieldcheckbox, and add them into an arraylist. If possible, give any useful links also. Here's my code so far (I am new to blackberry application development). Please help.
package mypackage;
import java.util.Vector;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.IntVector;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements ListFieldCallback
{
private Vector _listData = new Vector();
private Vector _checkedData = new Vector();
private ListField listField;
private static final String[] _elements = {"First element", "Second element","Third element"
};
//private static final String[] _elements1 = {"hai","welcome","where r u"
//};
private MenuItem _getDataMenu,selectall,Delete;
Vector result = new Vector();
protected void makeMenu(Menu menu, int instance)
{
menu.add(_getDataMenu);
menu.add(selectall);
menu.add(Delete);
//Create the default menu.
super.makeMenu(menu, instance);
}
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
public Vector getCheckedItems() {
return _checkedData;
}
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
VerticalFieldManager main = new VerticalFieldManager(VerticalFieldManager.USE_ALL_HEIGHT|
VerticalFieldManager.USE_ALL_WIDTH|VerticalFieldManager.VERTICAL_SCROLL);
this.add(main);
HorizontalFieldManager hfm = new HorizontalFieldManager();
main.add(hfm);
listField = new ListField(){
//Allow the space bar to toggle the status of the selected row.
protected boolean keyChar(char key, int status, int time)
{
boolean retVal = false;
//If the spacebar was pressed...
if (key == Characters.SPACE)
{
//Get the index of the selected row.
int index = getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
invalidate(index);
//Consume this keyChar (key pressed).
retVal = true;
}
return retVal;
}
};
listField.setCallback(this);
reloadList();
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.addElement(new ChecklistData(_elements[count], false));
//_listData.addElement(new ChecklistData(_elements1[count], false));
listField.insert(count);
}
main.add(listField);
_getDataMenu =new MenuItem("Get Data", 200, 10) {
public void run(){
int index = listField.getSelectedIndex();
ChecklistData data = (ChecklistData)_listData.elementAt(index);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
//Dialog.alert(message);
// get all the checked data indices
IntVector selectedIndex = new IntVector(0, 1);
//ChecklistData data;
for (int i=0;i<_listData.size();i++) {
data = (ChecklistData)_listData.elementAt(i);
if(data.isChecked()) {
selectedIndex.addElement(i);
String selectedvalues = data.getStringVal();
System.out.println("Selected items are:"+selectedvalues);
}
}
data = null;
// now selectedIndex will contain all the checked data indices.
//String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
}
};
selectall = new MenuItem("Selectall", 200, 10){
public void run(){
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.setElementAt(new ChecklistData(_elements[count], true), count);
}
}
};
Delete = new MenuItem("Delete", 200, 10){
public void run(){
int index = listField.getSelectedIndex();
_listData.removeElementAt(index);
// update the view
listField.delete(index);
listField.invalidate(index);
}
};
}
private void reloadList() {
// TODO Auto-generated method stub
_listData.setSize(_listData.size());
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*if (currentRow.isChecked()) {
if( -1 ==_checkedData.indexOf(currentRow))
_checkedData.addElement(currentRow);
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else {
if( -1 !=_checkedData.indexOf(currentRow))
_checkedData.removeElement(currentRow);
rowString.append(Characters.BALLOT_BOX);
} */
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
}
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
return _listData.indexOf(p, s);
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
protected boolean navigationClick(int status, int time) {
int index1 = listField.getSelectedIndex();
/*System.out.println("Selected item index:"+index1);
//int[] list =listField.getSelection();
//String s = Integer.toString(list);
System.out.println(" items are:"+_elements[index1]);
//ChecklistData data = (ChecklistData)_listData.elementAt(index1);*/
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index1);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
System.out.println("message is:"+message);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index1);
//Invalidate the modified row of the ListField.
listField.invalidate(index1);
return true;
}
}

how to find the size of object stored (in bytes or kb,mb) on persistence store in blackberry

I am trying to find the size of the object that I store on persistence store . I have programatically found out the size of object as shown in code but I can not find out the size of this object when it is stored on persistence store.
Does data get compressed automatically when it is comitted to store.
I m using Memory.getFlashStats().getFree(); to get the free size of persistence store before and after commitnig the object to store and the difference between the two values should be equal to the size of object that i have calculated.
please see the code
package Bean;
import java.util.Enumeration;
import java.util.Vector;
import net.rim.device.api.system.Memory;
import net.rim.device.api.system.MemoryStats;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;
import bean.UserCredentials;
public class MyStoreScreen extends MainScreen implements FieldChangeListener
{
private int nObjectSize;
static final long PERSISTENT_STORE_DEMO_ID = 0x42c16456ab0b5eabL;
private static PersistentObject oPersistenStore;
private int nFreePersistenceInStarting=Memory.getPersistentStats().getFree();
private int nFreePersistenceAtEnd;
ButtonField oCalculateMemButton ;
private MenuItem saveItem = new MenuItem("Save ", 110, 10)
{
public void run()
{
Dialog.alert("initially free memory ----------------------"+nFreePersistenceInStarting);
oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
Vector storeVector = (Vector)oPersistenStore.getContents();
Vector userinfo ;
int size = (storeVector == null) ? 0 : storeVector.size();
if(size == 0)
{
userinfo = new Vector();
}
else
{
userinfo = storeVector;
}
UserCredentials oUserCredentials = new UserCredentials("akanksha","chandra",1,3434.3434,343545646);
for(int i =0;i<=100;i++)
{
userinfo.addElement(oUserCredentials);
}
nObjectSize= fnCalculateSizeOfObject(userinfo);
Dialog.alert("size of object is "+ nObjectSize);
synchronized(oPersistenStore)
{
oPersistenStore.setContents(userinfo);
oPersistenStore.commit();
}
}
};
private MenuItem getItem = new MenuItem( "Get item", 110, 11 )
{
public void run()
{
oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
synchronized(oPersistenStore)
{
Vector arrCredential = (Vector)oPersistenStore.getContents();
if(arrCredential != null)
{
String dataContents = "";
int nSize = (arrCredential == null) ? 0 : arrCredential.size();
if(nSize != 0)
{
for (int i = 0; i < nSize; i++)
{
UserCredentials oUserCredentials = (UserCredentials)arrCredential.elementAt(i);
dataContents+="\n size of vector is "+nSize+ " username : "+oUserCredentials.getStrUsername()+"\n password : "+oUserCredentials.getStrPassword();
dataContents += "\n\nUser sal : "+oUserCredentials.getdSalary();
dataContents += "\n amount : "+oUserCredentials.getlAmount();
dataContents += "\n s no "+oUserCredentials.getnSerialNo();
}
Dialog.alert(dataContents);
}
else
{
Dialog.alert("Zero Elements ");
}
}
else
{
Dialog.alert("No contents ");
}
}
}
};
private MenuItem resetStoreItem = new MenuItem( "Delete Store", 110, 11 )
{
public void run()
{
int choice = Dialog.ask(Dialog.D_OK_CANCEL, "Do you want to delete ?");
if(choice == Dialog.D_OK)
{
// oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
PersistentStore.destroyPersistentObject(PERSISTENT_STORE_DEMO_ID);
}
else
{
}
}
};
private MenuItem CalculateTotalFlashUsed = new MenuItem("calculate used flash size ", 0, 7)
{
public void run()
{
Dialog.alert("used size of Persistence Store is "+fnUsedPersistenceSize());
};
};
public MyStoreScreen()
{
oCalculateMemButton = new ButtonField("calculate free flash memory in starting", ButtonField.CONSUME_CLICK);
oCalculateMemButton.setChangeListener(this);
this.add(oCalculateMemButton);
this.addMenuItem(saveItem);
this.addMenuItem(getItem);
this.addMenuItem(resetStoreItem);
this.addMenuItem(CalculateTotalFlashUsed);
oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
}
public void fieldChanged(Field field, int context)
{
if(field ==oCalculateMemButton)
{
// nFreeFlashInStarting =Memory.getFlashTotal();
// nFreeFlashInStarting =Memory.getFlashStats().getFree();
// nFreeFlashAtEnd =Memory.getFlashStats().getFree();
// String message = "total flash is Memory.getFlashStats().getAllocated(); "+nFreeFlashInStarting+" Memory.getFlashTotal() is : "+Memory.getFlashTotal();
String message = "total free flash memory in starting is :"+ nFreePersistenceInStarting;
Dialog.alert(message);
}
}
private int fnCalculateSizeOfObject(Vector userInfo )
{
int nSize = 0;
Enumeration oEnumeration = userInfo.elements();
while(oEnumeration.hasMoreElements())
{
UserCredentials oUserCredentials = (UserCredentials) oEnumeration.nextElement();
String UserName = oUserCredentials.getStrUsername();
String password = oUserCredentials.getStrPassword();
int nSerialNo = oUserCredentials.getnSerialNo();
double dSalary = oUserCredentials.getdSalary();
long lAmount = oUserCredentials.getlAmount();
nSize+= 4+8+8+fnCalculateSizeOfString(UserName)+fnCalculateSizeOfString(password);
}
return nSize;
}
private int fnCalculateSizeOfString(String strInputString)
{
//convert String to char array
char[] characterArray = strInputString.toCharArray();
int nlength = characterArray.length;
return nlength;
}
public int fnUsedPersistenceSize()
{
nFreePersistenceAtEnd = Memory.getPersistentStats().getFree();
int nUsedPersistenceMemory = nFreePersistenceInStarting -nFreePersistenceAtEnd;
return nUsedPersistenceMemory;
}
}
Memory.getFlashStats().getFree() is not that accurate, you can see it when measuring storage of the same object several times - values may be different every time.
The best way to measure object size is to calculate its fields size (what you actually doing).

Resources