How to get output using CLIPS Rule Engine in Android/kotlin - android

Hi I am new to clips rule engine and have to do following in clips in mobile app (Android/Kotlin). we are using CLIPS4android library as wrapper of JNI.
How to get output from class file, when the rule gets executed by invoking the clips.run()
class RulesTest(filepath: String?) {
private val clips: Environment
fun stop() {
clips.destroy()
}
/**
* Example of how to use "assert".
* #throws CLIPSError
*/
#Throws(CLIPSError::class)
fun assertItems(products: List<Item>) {
for (product in products) {
Log.d(tag, "(Product " + "(productId " + product.ProductId + ")" + "(uomid " + product.UOMId + " )" + "(quantity " + product.Quantity + " ))")
var InsertItem: String
InsertItem = "(Product " + "(productId " + product.ProductId + ")" + "(uomid " + product.UOMId + " )" + "(quantity " + product.Quantity + " ))"
clips.assertString(InsertItem)
}
}
fun run() {
clips.eval("(facts)");
clips.run()
}
companion object {
const val tag = "CLIPSProductRulesTest"
}
init {
clips = Environment()
clips.load(filepath)
Log.d(tag, "Loading .clp...\n\n")
clips.reset()
}
}

In the 0.4 version of CLIPSJNI, you can define an implementation of the Router class to capture the output and then you can do whatever your want with the output in the print method of the implementation.
import CLIPSJNI.*;
class Example
{
static class CaptureRouter implements Router
{
public int getPriority()
{
return 10;
}
public String getName()
{
return "grab";
}
public boolean query(
String logName)
{
if (logName.equals("wwarning") ||
logName.equals("werror") ||
logName.equals("wtrace") ||
logName.equals("wdialog") ||
logName.equals("wprompt") ||
logName.equals("wdisplay") ||
logName.equals("stdout"))
{ return true; }
return false;
}
public void print(
String routerName,
String printString)
{
System.out.print(printString);
}
public int getchar(
String routerName)
{
return -1;
}
public int ungetchar(
String routerName,
int theChar)
{
return -1;
}
public boolean exit(
int exitCode)
{
return true;
}
}
public static void main(String args[])
{
Environment clips;
clips = new Environment();
clips.addRouter(new CaptureRouter());
clips.build("(defrule hello => (printout t \"Hello World!\" crlf))");
clips.reset();
clips.run();
}
}

Related

How do you cloud save each level data. for unity Game Like Candy crush game

I am developing a puzzle game for Android using unity. So I want to save the score, time and stars earned for each level in the google play Cloud. But I am able to save it for one single level if I try to save it for more then 1 level. it overwrites the previous data. So how do I overcome this problem?
public class CloudSave : MonoBehaviour {
[SerializeField]
private Text message;
private int totalCoin = 20;
public int levelNumber;
public int starEarnedPerLevel;
#region Cloud_Save
private string GetSaveString() {
string data = "";
data += PlayerPrefs.GetInt("HighScore").ToString();
data += "|";
data += totalCoin.ToString();
data += "|";
data += levelNumber.ToString();
data += "|";
data += starEarnedPerLevel.ToString();
return data;
}
private void LoadSaveString(string save) {
string[] data = save.Split('|');
PlayerPrefs.SetInt("HighScore", int.Parse(data[0]));
totalCoin = int.Parse(data[1]);
levelNumber = int.Parse(data[2]);
starEarnedPerLevel = int.Parse(data[3]);
Debug.Log("LoadSaveString Function");
}
private bool isSaving = false;
public void OpenSave(bool saving) {
Debug.Log("Open Save");
if (Social.localUser.authenticated) {
isSaving = saving;
((PlayGamesPlatform)Social.Active).SavedGame
.OpenWithAutomaticConflictResolution(
"MyCloudFile",
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime, SavedGameOpen);
}
}
private void SavedGameOpen(SavedGameRequestStatus reqStatus, ISavedGameMetadata metadata) {
Debug.Log("SavedGameOpen");
if (reqStatus == SavedGameRequestStatus.Success) {
if (isSaving)// Writting
{
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(GetSaveString());
SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().WithUpdatedDescription("Saved At :" + System.DateTime.Now.ToString()).Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(metadata, update, data, SaveUpdate);
}
else // Reading or Loading
{
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(metadata,SaveRead);
}
}
}
//success Save
private void SaveUpdate(SavedGameRequestStatus reqStatus, ISavedGameMetadata metadata) {
Debug.Log(reqStatus);
if (reqStatus == SavedGameRequestStatus.Success)
{
message.text = ("Data Saved successfully ");
}
else {
message.text = ("Data Saved failed " + reqStatus.ToString());
}
}
//Load
private void SaveRead(SavedGameRequestStatus reqStatus, byte[] data) {
if (reqStatus == SavedGameRequestStatus.Success) {
string savedData = System.Text.ASCIIEncoding.ASCII.GetString(data);
message.text = ("Data read successfully " + savedData);
LoadSaveString(savedData);
}
else
{
message.text = ("Data read Failed!" + reqStatus.ToString());
}
}
#endregion
}
Use JSON to keep the game data , splitting string is hard to maintain.
{
"currentLevel":"3",
"totalCoin":"20",
"levelData":[
{
"levelNum":1,
"starEarn":3,
"highScore":123456
},
{
"levelNum":2,
"starEarn":1,
"highScore":1234
}
]
}
//GameData.cs
[System.Serializable]
public class GameData {
public int currentLevel;
public int totalCoin;
private Dictionary<int, LevelData> levelDataList;
public GameData(){
//
// constructor
//
}
public string GetSaveString(){
string res = JsonUtility.ToJson (this);
res = res.Substring (0, res.Length - 1);
res = res + ",\"levelData\":[";
foreach (LevelData levelData in levelDataList.Values) {
res = res + JsonUtility.ToJson (levelData);
res = res + ",";
}
if(levelDataList.Count > 0)
res = res.Substring (0, res.Length - 1);
res = res + "]}";
return res;
}
}
//LevelData.cs
[System.Serializable]
public class LevelData {
public int levelNum;
public int starEarn;
public int highScore;
public LevelData(){
//
// constructor
//
}
}

Android/Java, Cloud Firestore .toObject method not working

I develop an Android app which interacts with Google Firebase Cloud Firestore. To get data from Firestore, I use addOnCompleteListener with DocumentSnapshot.toObject() method. However, method toObject() seems not to work properly because it doesn't transmit data from snapshot to object.
Goal.class
#Entity
public class Goal {
// private variables
#PrimaryKey (autoGenerate = true)
private int id;
private String remoteId;
private int goalPos;
private String goalName;
private int goalCategory;
private String goalDescription;
private int goalColor;
private int goalFrequency;
private long goalFrequencyCode;
private boolean goalRewardType;
private double goalReward;
private int activated;
private boolean isSynced;
// constructor
public Goal() {
remoteId = "";
goalPos = 0;
goalName = "";
goalCategory = 15;
goalDescription = "";
goalColor = R.color.cat_Black;
goalFrequency = 0; // 0=Daily, 1=Weekly, 2=Monthly
goalFrequencyCode = 1111111111; // 1111111.111 - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; first of month, middle of month, last of month
goalRewardType = false; // false = standard, true = individual
activated = 1; // 0=No, 1=Yes
isSynced = false;
}
// getter and setter
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRemoteId() {
return remoteId;
}
public void setRemoteId(String remoteId) {
this.remoteId = remoteId;
}
public int getGoalPos() {
return goalPos;
}
public void setGoalPos(int goalPos) {
this.goalPos = goalPos;
}
public String getGoalName() {
return goalName;
}
public void setGoalName(String goalName) {
this.goalName = goalName;
}
public int getGoalCategory() {
return goalCategory;
}
public void setGoalCategory(int goalCategory) {
this.goalCategory = goalCategory;
}
public String getGoalDescription() {
return goalDescription;
}
public void setGoalDescription(String goalDescription) {
this.goalDescription = goalDescription;
}
public int getGoalColor() {
return goalColor;
}
public void setGoalColor(int goalColor) {
this.goalColor = goalColor;
}
public int getGoalFrequency() {
return goalFrequency;
}
public void setGoalFrequency(int goalFrequency) {
this.goalFrequency = goalFrequency;
}
public long getGoalFrequencyCode() {
return goalFrequencyCode;
}
public void setGoalFrequencyCode(long goalFrequencyCode) {
this.goalFrequencyCode = goalFrequencyCode;
}
public LinkedList<Integer> getGoalFrequencyCodeAsList() {
LinkedList<Integer> stack = new LinkedList<>();
long number = goalFrequencyCode;
while (number > 0) {
long longTempMod = number % 10;
int intTempMod = (int) longTempMod;
stack.push(intTempMod);
number = number / 10;
}
return stack;
}
public void setGoalFrequencyCodeFromList(LinkedList<Integer> stack) {
double number = 0;
for (int j = 0; j < stack.size(); j++) {
Log.d(String.valueOf(j), String.valueOf(stack.get(j)));
}
if (stack.size() <= 1) {
goalFrequencyCode = 1111111111;
} else {
for (int i = 0; i < stack.size(); i++) {
Log.d(String.valueOf(stack.get(i)), String.valueOf(number));
number = number + (stack.get(i) * Math.pow(10, (stack.size() - 1 - i)));
}
Log.d("Sent from Goal - number", String.valueOf(number));
goalFrequencyCode = (long) number;
Log.d("Sent from Goal - long", String.valueOf(goalFrequencyCode));
}
}
public boolean getGoalRewardType() {
return goalRewardType;
}
public void setGoalRewardType(boolean goalRewardType) {
this.goalRewardType = goalRewardType;
}
public double getGoalReward() {
return goalReward;
}
public void setGoalReward(double goalReward) {
this.goalReward = goalReward;
}
public int getActivated() {
return activated;
}
public void setActivated(int activated) {
this.activated = activated;
}
public boolean getIsSynced() {
return isSynced;
}
public void setIsSynced(boolean isSynced) {
this.isSynced = isSynced;
}
#Override
public String toString() {
return "Goal{" +
"id=" + id +
", remoteId='" + remoteId + '\'' +
", goalPos=" + goalPos +
", goalName='" + goalName + '\'' +
", goalCategory=" + goalCategory +
", goalDescription='" + goalDescription + '\'' +
", goalColor=" + goalColor +
", goalFrequency=" + goalFrequency +
", goalFrequencyCode=" + goalFrequencyCode +
", goalRewardType=" + goalRewardType +
", goalReward=" + goalReward +
", activated=" + activated +
", isSynced=" + isSynced +
'}';
}
}
FirebaseService.class
public LiveData<ApiResponse<List<Goal>>> getGoals() {
final MutableLiveData<ApiResponse<List<Goal>>> list = new MutableLiveData<>();
if (mAuth.getCurrentUser() != null) {
userId = mAuth.getCurrentUser().getUid();
colRefGoals = firestore.collection(userId).document("data").collection("goals");
colRefGoals
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Goal> goalsList = new ArrayList<Goal>();
for (DocumentSnapshot documentSnapshot : task.getResult()) {
Log.d("firebaseService", "DocumentSnapshop.getData: " + documentSnapshot.getData());
Goal goal = documentSnapshot.toObject(Goal.class);
Log.d("firebaseService", "DocumentSnapshot.toObject(Goal.class): " + goal.toString());
goalsList.add(goal);
}
ApiResponse<List<Goal>> apiResponse = new ApiResponse<List<Goal>>(goalsList);
list.setValue(apiResponse);
}
}
});
} else {
Throwable error = new Throwable("No user logged in");
ApiResponse<List<Goal>> apiResponse = new ApiResponse<List<Goal>>(error);
list.setValue(apiResponse);
return list;
}
return list;
}
Following my debug log comparison between .getData and .toObject:
12-05 19:53:42.663 11470-11470/com.benjaminsommer.dailygoals D/firebaseService: DocumentSnapshop.getData: {goals={goalRewardType=true, remoteId=10L44s0EcvTTzGajzhidgoals, id=2, goalFrequencyCode=1001111111, activated=1, goalColor=-4365347, goalCategory=8, goalDescription=Description Test, goalReward=1, goalPos=1, goalFrequency=2, goalName=Test}}
12-05 19:53:42.663 11470-11470/com.benjaminsommer.dailygoals D/firebaseService: DocumentSnapshot.toObject(Goal.class): Goal{id=0, remoteId='', goalPos=0, goalName='', goalCategory=15, goalDescription='', goalColor=2131558437, goalFrequency=0, goalFrequencyCode=1111111111, goalRewardType=false, goalReward=0.0, activated=1, isSynced=false}
.toObject doesn't transform the datasnapshot to my class. I already checked the documentation:
Important: Each custom class must have a public constructor that takes
no arguments. In addition, the class must include a public getter for
each property.
I have a constructor with no args and public getters for each property. I tried it with an empty constructor, but not working either. Is anything wrong with my getters? I use it in combination with Room, maybe there can be an issue?
Really appreciate your help and support.
Thanks, Ben

Javssist generated empty class

In my Android Project, I try to use Transform API and Javasist to make an AOP framework.
But some class is transformed to an empty class and then I got the build error :
/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar] (Can't process class xxx/xxx/xxx/ABC.class
because the ABC.class get empty after javasist handle(I just load it with javasiit and then write back).
The code I write to modify class is :
public void weave(String path) {
println("Begin to weave androidClassPath = " + androidClassPath)
println("Begin to weave path = " + path)
pool.appendClassPath(path)
pool.appendClassPath(androidClassPath)
pool.importPackage("android.util.Log");
File dir = new File(path)
int indexOfPackage = path.length() + 1;
if (dir.isDirectory()) {
dir.eachFileRecurse { File file ->
String filePath = file.absolutePath
if (isWeavableClass(filePath)) {
println("Begin to inject filePath " + filePath)
int end = filePath.length() - 6 // .class = 6
String className = filePath.substring(indexOfPackage, end).replace(File.separator, '.')
CtClass clazz = pool.getCtClass(className)
if (clazz.isFrozen()) {
clazz.defrost()
}
boolean timeDebugClass = false;
boolean parameterDebugClass = false;
if(clazz.hasAnnotation(TimingDebug.class)) {
timeDebugClass = true;
}
if(clazz.hasAnnotation(ParameterDebug.class)) {
parameterDebugClass = true;
}
println "timeDebugClass = "+ timeDebugClass + " parameterDebugClass = " + parameterDebugClass
CtMethod[] methods = clazz.getDeclaredMethods();
for (CtMethod method : methods) {
boolean emptyMethod = method.isEmpty()
boolean isNativeMethod = Modifier.isNative(method.getModifiers());
println("method name = " + method + " emptyMethod " + emptyMethod + " isNativeMethod = " + isNativeMethod)
if (!emptyMethod && !isNativeMethod) {
if (method.hasAnnotation(ParameterDebug.class) || parameterDebugClass) {
weaveParameterDebugMethod(clazz, method)
}
if (method.hasAnnotation(TimingDebug.class) || timeDebugClass) {
weaveTimingDebugMethod(clazz, method)
}
}
}
CtConstructor[] constructors = clazz.getDeclaredConstructors();
for(CtConstructor constructor: constructors){
boolean emptyMethod = constructor.isEmpty()
println("constructor name = " + constructor + " emptyMethod " + emptyMethod)
if (!emptyMethod) {
if (constructor.hasAnnotation(ParameterDebug.class) || parameterDebugClass) {
weaveParameterDebugMethod(clazz, constructor)
}
if (constructor.hasAnnotation(TimingDebug.class) || timeDebugClass) {
weaveTimingDebugMethod(clazz, constructor)
}
}
}
clazz.writeFile(path)
clazz.detach()
}
}
}
}

Rfid card reader value android detecting twice

I am trying to make an android app for RFID card reader (i am not using NFC), for this i connect one high frquency RFID card reader through OTG cable and i am using EditText where card number is displaying. it is working fine, but problem is sometime it detects multiple time card number.
1- Any idea how can i resolve this (i cannot put size limit condition because card number length is not fixed)?
2- One more problem when i am using ultra high frequency card reader then card is showing different value, any idea how can i make an android app which supports both frequency card readers.
Rfid continue reading tag its not one time reading so from this repetition you have to manage to your side. Check its reading data or not if yes then ignore.Below the call Where implement Rfid methods and its reading data handle.
public class ReaderListener implements RfidEventListener {
private RfidReader reader;
private ReadInventory eventForm;
//private ItemTransfer eventFormitm;
private final ToneGenerator tg = new ToneGenerator(5, 100);
private boolean isEnabled;
private Map<String, Long> scannedItemsMap = new TreeMap<String, Long>();
public ReaderListener(ReadInventory frm, String make, String macid) throws ReaderConnectionException, LicenseExpiryException, IOException, GeneralSecurityException {
Log.d("Test1", " "+make.toString().trim()+" "+ macid.toString().trim());
reader = RfidFactory.getInstance().getRfidReader(make.toString().trim(), macid.toString().trim(),
PlatformConnector.AndroidConnector.getPlatformName());
Log.d("Test2", " "+reader+" ");
//reader.removeAllListeners();
reader.registerListener(this);
setEnabled(true);
this.eventForm = frm;
}
#Override
public void handleData(String tagid, int arg1, int arg2) {
synchronized (scannedItemsMap) {
if (!scannedItemsMap.containsKey(tagid)) {
System.out.println("got data............ :" + tagid);
scannedItemsMap.put(tagid, System.currentTimeMillis());
if (eventForm != null) {
eventForm.handleData(tagid);
//this.tg.startTone(25);
Log.d("tagid", " " + tagid + " ");
}
/*if (eventFormitm != null) {
eventFormitm.handleData(tagid);
}*/
} else if (scannedItemsMap.containsKey(tagid)) {
scannedItemsMap.put(tagid, System.currentTimeMillis());
}
}
}
#Override
public void handleError(String msg) {
if (eventForm != null) {
eventForm.handleError(msg);
}
}
#Override
public boolean isEnabled() {
return isEnabled;
}
#Override
public void setEnabled(boolean arg0) {
this.isEnabled = arg0;
}
public boolean startScan(int power,int speed) throws ReaderConnectionException {
if (reader != null && !reader.isScanning()) {
reader.setSession(RfidSession.ONE);
reader.setPower(power);
reader.setScanSpeed(speed);
reader.startScan();
}
return true;
}
public void stopScan() throws ReaderConnectionException {
if (reader.isScanning())
reader.stopScan();
}
public boolean isScanning() {
return reader.isScanning();
}
public boolean isConnected() {
return reader.isConnected();
}
public void removeAll() {
scannedItemsMap.clear();
}
public void remove(String tagid) {
scannedItemsMap.remove(tagid);
}
public int getBatteryLevel(){
try {
return reader.getBatteryLevel();
}catch (Exception e){
return 0;
}
}
#Override
public void handleReaderEvent(ReaderEvent arg0) {
// TODO Auto-generated method stub
}
}
Now Handle The data in activity ....
Show in below method.
public void handleData(final String tagid) {
// TODO Auto-generated method stub
try {
final String Code_samplecode = convertHexToString(tagid);
// Log.e("Name", "Itemcode" + Code_samplecode);
if (SampleCode.contains(Code_samplecode)&& !p_SampleCode.contains(Code_samplecode)) {
// Scann items count
tgf.startTone(25);
int ind_val = SampleCode.indexOf(Code_samplecode);
if (ind_val != -1) {
final String SampleNo1 = SampleNo.get(ind_val);
final String StyleNo1 = StyleNo.get(ind_val);
final String SampleCode1 = SampleCode.get(ind_val);
final String StyleCode1 = StyleCode.get(ind_val);
//final String CartStyleCode1 = CartStyleCode.get(ind_val);
// final String CartStyleNo1 = CartStyleNo.get(ind_val);
SampleNo.remove(ind_val);
StyleNo.remove(ind_val);
SampleCode.remove(ind_val);
StyleCode.remove(ind_val);
runOnUiThread(new Runnable() {
#Override
public void run() {
// p_Code.add(Code.get(ind_val));
p_SampleNo.add(SampleNo1);
p_StyleNo.add(StyleNo1);
p_SampleCode.add(SampleCode1);
p_StyleCode.add(StyleCode1);
//Code.remove(ind_val);
// adapter3.notifyDataSetChanged();
// adapter1.notifyDataSetChanged();
total_item.setAdapter(null);
adapter3 = new Adapter_for_Inventoryitem(ReadInventory.this,
StyleNo, SampleNo);
total_item.setAdapter(adapter3);
present_item.setAdapter(null);
adapter1 = new Adapter_for_Inventoryitem(ReadInventory.this,
p_StyleNo, p_SampleNo);
present_item.setAdapter(adapter1);
textvie.setText("Total " + p_SampleNo.size() + " Found Styles");
textvi.setText("Total " + SampleNo.size() + " Available Styles");
List<Inventory> c = db.get_all_data_INVENTARY_Query("SELECT * FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
if (c.size() > 0) {
db.execute_query("INSERT INTO Inventory_p (Code, SampleNo,StyleNo,SampleCode,StyleCode,CartStyleNo,CartStyleCode) VALUES ('" + c.get(0).getCode() + "' , \"" +
c.get(0).getSampleNo() + "\" , \"" + c.get(0).getStyleNo() + "\" , '" +
c.get(0).getSampleCode() + "' , '" + c.get(0).getStyleCode() + "' , \"" +
c.get(0).getCartStyleNo() + "\" , '" + c.get(0).getCartStyleCode() + "')");
}
db.execute_query("DELETE FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
}
});
}
} else {
if (!SampleCode.contains(Code_samplecode) && !p_SampleCode.contains(Code_samplecode)
&& !not_fount_items.contains(Code_samplecode)) {
tgn.startTone(20);
scanneditems_unkown = scanneditems_unkown + 1;
runOnUiThread(new Runnable() {
#Override
public void run() {
not_fount_items.add(Code_samplecode);
not_fount_items_txt.setText("Total " + not_fount_items.size() + " Unknown Styles");
}
});
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
scan_counts.setText("Total " + p_SampleNo.size() + " Scanned");
scan_counts_unknown.setText("Total " + scanneditems_unkown + " Unknown");
last_scanned_items.setText("Item : " + Code_samplecode);
}
});
} catch (Exception e) {
e.printStackTrace();
Message message = new Message();
message.what = READEREXCEPTION;
itemDetectedHandler.sendMessage(message);
}
}
You need to Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
//To get the characters (One By one)
event.getDisplayLabel();
}
And use Debounce (I'll recommend using RX Java) if the card numbers are of different length.
What debounce does is, it will wait for a particular amount of time after a keyevent happens, So you can concat the whole string and then use it.

Android Parcelable and inheritance

I have a class Drills and few classes that extend it, for example AddDrill.
I want to be able to pass this Drill objects "family" between activities, so I am using Parcelable.
I have found this answer and this example and I have created this Drill and AddDrill classes, I think I have done something wrong, is every thing good in my implementation?
Drill:
package com.simplemathgame;
import android.os.Parcel;
import android.os.Parcelable;
public abstract class Drill implements Parcelable{
protected int firstNumber;
protected int secondNumber;
protected int answer;
protected int userAnswer;
protected String userAnswerString;
protected String symbol;
protected int minBound, maxBound;
protected int drillNumber;
public String getUserAnswerString() {
return userAnswerString;
}
public void setUserAnswerString(String userAnswerString) {
this.userAnswerString = userAnswerString;
}
Drill(int min, int max){
minBound = min;
maxBound = max;
answer = answerCalculatetion();
userAnswerString = "";
}
public Drill(Parcel in) {
readFromParcel(in);
}
public int getDrillNumber() {
return drillNumber;
}
public void setDrillNumber(int drillNumber) {
this.drillNumber = drillNumber;
}
public int getUserAnswer() {
return userAnswer;
}
public void setUserAnswer(int userAnswer) {
this.userAnswer = userAnswer;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getMinBound() {
return minBound;
}
public void setMinBound(int minBound) {
this.minBound = minBound;
}
public int getMaxBound() {
return maxBound;
}
public void setMaxBound(int maxBound) {
this.maxBound = maxBound;
}
//getters and setters
public int getFirstNumber() {
return firstNumber;
}
public void setFirstNumber(int firstNumber) {
this.firstNumber = firstNumber;
}
public int getSecondNumber() {
return secondNumber;
}
public void setSecondNumber(int secondNumber) {
this.secondNumber = secondNumber;
}
public int getAnswer() {
return answer;
}
public void setAnswer(int answer) {
this.answer = answer;
}
protected int getRandomNumber(int high, int low){
return (int) ((Math.random( ) * (high - low + 1)) + low);
}
protected abstract int answerCalculatetion();
protected String printDrill(){
String FirstNumberS;
String SecondNumberS;
if(this.getFirstNumber() < 0){
FirstNumberS = "(" + this.getFirstNumber() + ")";
}
else{
FirstNumberS = "" + this.getFirstNumber();
}
if(this.getSecondNumber() < 0){
SecondNumberS = "(" + this.getSecondNumber() + ")";
}
else{
SecondNumberS = "" + this.getSecondNumber();
}
return (FirstNumberS + " " + this.getSymbol() + " " + SecondNumberS + " " + "=");
}
protected String printDrillAnswer(){
String FirstNumberS;
String SecondNumberS;
String answerS;
if(this.getAnswer() < 0){
answerS = "(" + this.getAnswer() + ")";
}
else{
answerS = "" + this.getAnswer();
}
if(this.getFirstNumber() < 0){
FirstNumberS = "(" + this.getFirstNumber() + ")";
}
else{
FirstNumberS = "" + this.getFirstNumber();
}
if(this.getSecondNumber() < 0){
SecondNumberS = "(" + this.getSecondNumber() + ")";
}
else{
SecondNumberS = "" + this.getSecondNumber();
}
return (FirstNumberS + " " + this.getSymbol() + " " + SecondNumberS + " " + "=" + " " + answerS);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// We just need to write each field into the
// parcel. When we read from parcel, they
// will come back in the same order
dest.writeInt(firstNumber);
dest.writeInt(secondNumber);
dest.writeInt(answer);
dest.writeInt(userAnswer);
dest.writeString(userAnswerString);
dest.writeString(symbol);
dest.writeInt(minBound);
dest.writeInt(maxBound);
dest.writeInt(drillNumber);
}
/**
*
* Called from the constructor to create this
* object from a parcel.
*
* #param in parcel from which to re-create object
*/
protected void readFromParcel(Parcel in) {
// We just need to read back each
// field in the order that it was
// written to the parcel
firstNumber = in.readInt();
secondNumber = in.readInt();
answer = in.readInt();
userAnswer = in.readInt();
userAnswerString = in.readString();
symbol = in.readString();
minBound = in.readInt();
maxBound = in.readInt();
}
}
AddDrill:
package com.simplemathgame;
import android.os.Parcel;
import android.os.Parcelable;
public class AddDrill extends Drill {
AddDrill(int min, int max) {
super(min, max);
symbol = "+";
firstNumber = getRandomNumber(min, max);
secondNumber = getRandomNumber(min, max);
answer = answerCalculatetion();
}
private AddDrill(Parcel in) {
super(in);
}
protected int answerCalculatetion() {
return (this.getFirstNumber() + this.getSecondNumber());
}
public static final Parcelable.Creator<AddDrill> CREATOR = new Parcelable.Creator<AddDrill>() {
public AddDrill createFromParcel(Parcel in) {
return new AddDrill(in);
}
public AddDrill[] newArray(int size) {
return new AddDrill[size];
}
};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
}
Thanks
In your AddDrill class, you'll need to implement writeToParcel() method and also the constructor from a Parcel. You'll probably need to use #Override for both of such methods as well but you need to experiment to find out the final solution

Categories

Resources