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.
Related
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();
}
}
I'm in a dire situation of finding a solution for speeding up loading data into the RecyclerView. Data load from the server database and populate the row. Each row has a few EditTexts where user enters some values. Within the OnBindViewHolder, each value entered by the user is captured using a text watcher, and then totals are calculated and displayed real-time in the footer of the parent view.(outside the RecyclerView) Also, inside the OnBindViewHolder, a method is called to update a table in the DB, with the values just entered and captured.
So, basically, when each row gets bound, both the DB and the UI get updated. When the data load is huge, loading of the recyclerView is really slow. What I have tried are moving the DB update to a separate thread, using async task to update the DB. But nothing worked. What should I do here?
Adapter's OnBindViewHolder code is displayed below.
public void onBindViewHolder(final MyViewHolder holder, #SuppressLint("RecyclerView") final int position, List<Object> payload) {
//onBindViewHolder(holder,position);
holder.ref = position;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
onBind = true;
// data passed from getAllData method aka all from TempInvoice
SalesInvoiceModel siModel = salesInvoice.get(position);
holder.code.setText(siModel.getCode());
holder.product.setText(siModel.getProduct());
holder.batchNum.setText(siModel.getBatchNumber());
try {
Date date = simpleDateFormat.parse(siModel.getExpiryDate());
holder.expiry.setText(date.toString());
} catch (Exception ex) {
holder.expiry.setText("Error");
}
holder.expiry.setText(siModel.getExpiryDate());
if (siModel.getDiscountRate() > 0) {
holder.unitprice.setText(siModel.getRetailPrice() + "");
} else {
holder.unitprice.setText(siModel.getUnitPrice() + "");
}
holder.stock.setText(siModel.getStock() + "");
holder.lineval.setText(siModel.getLineValue() + "");
if (payload == null || payload.size() == 0) {
holder.shelf.setText(siModel.getShelf() + "");
holder.request.setText(siModel.getRequest() + "");
holder.order.setText(siModel.getOrder() + "");
holder.free.setText(siModel.getFree() + "");
holder.discount.setText(siModel.getDiscountRate() + "");
} else {
for (Object editText : payload) {
//String val = (String)payload.get(0);
String val = (String) editText;
switch (val) {
case SHELF:
if (lostFocus) {
holder.shelf.setText(salesInvoice.get(position).getShelf() + "");
}
break;
case REQUEST:
if (lostFocus) {
holder.request.setText(salesInvoice.get(position).getRequest() + "");
}
break;
case ORDER:
if (lostFocus) {
holder.order.setText(salesInvoice.get(position).getOrder() + "");
}
break;
case FREE:
if (lostFocus) {
holder.free.setText(salesInvoice.get(position).getFree() + "");
}
break;
case DISCOUNT:
if (lostFocus) {
holder.discount.setText(salesInvoice.get(position).getDiscountRate() + "");
}
break;
case LINEVAL:
holder.lineval.setText(salesInvoice.get(position).getLineValue() + "");
break;
default:
onBindViewHolder(holder, position);
break;
}
}
}
//ADD TEXT WATCHERS
holder.shelf.setOnFocusChangeListener(new FocusChangeListener());
holder.shelf.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
int pos = holder.ref;
if (!onBind) {
if (!s.equals("")) {
notifyItemChanged(pos, SHELF);
Log.d(TAG, "inside text change typed shelf_" + s);
salesInvoice.get(pos).setShelf(Integer.parseInt(s + ""));
} else {
salesInvoice.get(pos).setShelf(0);
}
lastUpdatedRow = pos;
}
}
});
holder.request.setOnFocusChangeListener(new FocusChangeListener());
holder.request.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
boolean valHasChanged = false;
boolean freeHasChanged = false;
int pos = holder.ref;
if (!onBind) {
if (!(s.equals(""))) {
int val = Integer.parseInt((s));
int stock = salesInvoice.get(pos).getStock();
// if stock does not have the particular product
if (val > stock) {
val = stock;
valHasChanged = true;
}
salesInvoice.get(pos).setRequest(val);
if (!refresh) salesInvoice.get(pos).setOrder(val);
if (salesInvoice.get(pos).getFree() + salesInvoice.get(pos).getOrder() > salesInvoice.get(pos).getStock()) {
salesInvoice.get(pos).setFree(0);
freeHasChanged = true;
}
} else {
salesInvoice.get(pos).setRequest(0);
}
notifyItemChanged(pos, ORDER);
if (valHasChanged) {
notifyItemChanged(pos, REQUEST);
}
if (freeHasChanged) {
notifyItemChanged(pos, FREE);
}
lastUpdatedRow = pos;
}
}
});
holder.order.setOnFocusChangeListener(new FocusChangeListener());
holder.order.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
boolean valHasChanged = false;
boolean freeHasChanged = false;
int pos = holder.ref;
if (!onBind) {
if (!(s.equals(""))) {
int val = Integer.parseInt(s);
int stock = salesInvoice.get(pos).getStock();
if (val > stock) {
val = stock;
valHasChanged = true;
}
salesInvoice.get(pos).setOrder(val);//make sure we set returnQty before
//checking the total of returnQty and free against stock
if (salesInvoice.get(pos).getOrder() + salesInvoice.get(pos).getFree() > salesInvoice.get(pos).getStock()) {
salesInvoice.get(pos).setFree(0);
freeHasChanged = true;
}
} else {
salesInvoice.get(pos).setOrder(0);
}
if (valHasChanged) {
notifyItemChanged(pos, ORDER);//notify the adapter that value changed and refresh the view mentioned by the string
}
if (freeHasChanged) notifyItemChanged(pos, FREE);
notifyItemChanged(pos, LINEVAL);
lastUpdatedRow = pos;
}
}
});
holder.free.setOnFocusChangeListener(new FocusChangeListener());
holder.free.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
boolean valChanged = false;
int pos = holder.ref;
if (!onBind) {
if ((!s.equals("")) && (!(s.equals("0")))) {
int val = Integer.parseInt(s);
salesInvoice.get(pos).setFree(val);
holder.discount.setEnabled(false);
if (salesInvoice.get(pos).getOrder() + salesInvoice.get(pos).getFree() > salesInvoice.get(pos).getStock()) {
salesInvoice.get(pos).setFree(0);
valChanged = true;
holder.discount.setEnabled(true);
}
} else {
salesInvoice.get(pos).setFree(0);
holder.discount.setEnabled(true);
}
notifyItemChanged(pos, LINEVAL);
if (valChanged) notifyItemChanged(pos, FREE);
holder.setCursor(FREE);
lastUpdatedRow = pos;
}
}
});
holder.discount.setOnFocusChangeListener(new FocusChangeListener());
holder.discount.addTextChangedListener(new GenericTextWatcher() {
#Override
public void afterTextChanged(String s) {
int pos = holder.ref;
if (!(s.equals(salesInvoice.get(pos).getDiscountRate() + ""))) {
if ((!s.equals("")) && (!(s.equals("0"))) && (!(s.equals("0.0"))) && (!(s.equals("0.")))) {
Double rate = Double.parseDouble(s.toString().trim());
Log.i(" RAte ", rate + "");
salesInvoice.get(pos).setDiscountRate(rate);
holder.free.setEnabled(false);
} else {
salesInvoice.get(pos).setDiscountRate(0.0);
holder.free.setEnabled(true);
}
if (!onBind) {
notifyItemChanged(pos, LINEVAL);
lastUpdatedRow = pos;
}
}
}
});
if (position % 2 == 0) {
holder.setColor(Color.LTGRAY);
} else {
holder.setColor(Color.GRAY);
}
onBind = false;
notifyUpdate(); //calling to update the UI
Log.d("ASY", "before db call");
DBAdapterAsync dbAdapter = new DBAdapterAsync(getContextForAdapter);
dbAdapter.execute(salesInvoice.get(holder.ref));
Log.d("ASY", "after db call");
}
//async task class for DB Update
#SuppressLint("StaticFieldLeak")
private class DBAdapterAsync extends AsyncTask<SalesInvoiceModel, Void, String> {
private SQLiteDatabase db;
private DBHelper dbHelper;
DBAdapterAsync(Context context) {
this.dbHelper = new DBHelper(context);
Log.d("ASY", "inside constructor");
}
#Override
protected void onPreExecute() {
try {
db = dbHelper.getWritableDatabase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
dbHelper.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(SalesInvoiceModel... models) {
SalesInvoiceModel model = models[0];
Log.d(TAG, "inside updateInvoiceData_");
Log.d(TAG, "shelf_" + model.getShelf());
Log.d(TAG, "order_" + model.getOrder());
Log.d(TAG, "free_" + model.getFree());
String sql = "UPDATE temp_invoice SET" +
" Shelf=" + model.getShelf() + " , Request=" + model.getRequest()
+ " , OrderQty=" + model.getOrder() + " , Free=" + model.getFree()
+ " , Disc=" + model.getDiscountRate() + " , LineVal=" + model.getLineValue()
+ ", RetailPriceLineVal=" + model.getRetailLineVal()
+ " WHERE _id=" + model.getId();
db.execSQL(sql);
Log.d(TAG, "DB method finished,");
Log.d("ASY", "after do in background");
return null;
}
}
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
I have a list view with a list of channels on them and when I press one of the channels, it starts to load a streaming URL to watch the channel. However, I can still navigate through the list and select another entry in the list which causes an Exception to occur. How can I disable controller input similar to how I can disable touch input once something has been pressed?
Here is the code for my onItemClickListener:
channel_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
main_progressBar.setVisibility(View.VISIBLE);
//to disable touch input
//getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
final int channel = channelListAdapter.getItem(position);
final String switch_major = majorChannelNumberList.get(channel);
Log.d(TAG, "Switch Major :" + switch_major);
final String switch_minor = minorChannelNumberList.get(channel);
Log.d(TAG, "Switch Minor :" + switch_minor);
final String switch_name = channelNameList.get(channel);
Log.d(TAG, "Switch Name :" + switch_name);
final String tuner = tuneLink + "Major=" + switch_major + "&Minor=" + switch_minor + "&Resolution=" + "1280x720";
Log.d(TAG, "Tuner String :" + tuner);
new Thread(new Runnable() {
#Override
public void run() {
String playlive = "";
String tuneResponse = tuneConnection.get_response(tuner);
if(tuneResponse.contains("successful")){
long startTime = System.currentTimeMillis();
do {
String hlsStatusResponse = hlsConnection.get_response(HLSLink);
Log.d(TAG,"HLS Status Response :" + hlsStatusResponse);
Matcher matcher = Pattern.compile("<hls_link>(.+?)</hls_link>").matcher(hlsStatusResponse);
while(matcher.find()){
playlive = matcher.group(1);
}
playlink = "http://" + ip + "/" + playlive;
} while (Objects.equals(playlive, "none") && (System.currentTimeMillis()-startTime)<20000);
if(!playlink.contains("none")){
streamConnection.get_response(playlink);
} else {
//TODO: implement some sort of message here to show no channel, see tablet app
}
} else {
Toast.makeText(OfflineActivity.this, "Ch " + switch_major + "-" + switch_minor + " " + switch_name + " is not available now",
Toast.LENGTH_LONG).show();
}
}
}).start();
//start player activity
streamConnection.responseHandler = new Handler(){
#Override
public void handleMessage(Message message){
Toast.makeText(OfflineActivity.this, "Tune to Channel " + switch_major + "-" + switch_minor, Toast.LENGTH_LONG).show();
Intent intent = new Intent(OfflineActivity.this, OfflinePlaybackActivity.class);
intent.putExtra("stream",playlink);
intent.putExtra("channel_index", channel);
startActivity(intent);
main_progressBar.setVisibility(View.INVISIBLE);
}
};
}
});
I know I can use
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
to disable touch input, looking for something similar for Amazon Fire TV.
Decided to use channel_list_view.setClickable(false) to prevent user from clicking on it.
I am trying to get the string of the EditText and if it is " I want to get " also but the string is appearing this in the EditText
android.support.v7.widget.AppCompatEditText{42e33310 VFED..CL .F ....ID40,40-1160,315 #7f0c006f app:id\CalculatorDisplay}
after getting it and giving it to the EditText again
and here is a part of the onClick that works when I press a button and the rest of it is not dealing with this problem the problem is in NoRepeatNumber as I tested that when I get it in TestTV TextView I saw the code above
public void onClick(View view) {
TestTV.setText("enterd ");
String buttonPressed = ((Button) view).getText().toString();
PublicButtonPressed = buttonPressed;
if (DIGITS.contains(buttonPressed)) {
SinOrNumber=2;
TestTV.append("numbering");
// digit was pressed
if (!Started) {
mCalculatorDisplay.setText("");
TestTV.append("\nenterd setText");
} else {
TestTV.append("\nenterd setText eslse");
}
if (Started) {
OperationEnded = true;
}
if (NumberingEnded) {
FullNumber = String.valueOf(Number[Ni]);
Ni++;
NumberingEnded = false;
FullCalculation= FullNumber + " ";
NoRepeatNumber="";
DisplayCalculations();
}
FullNumber = FullNumber + buttonPressed;
Number[Ni] = Integer.parseInt(FullNumber);
TestTV.append("\nNumber[" + Ni + "] =" + + Number[Ni] + "\n" + "buttonPressed =" + buttonPressed + "\nFullNumber =" + FullNumber);
//DisplayCalculations();
if ("".equals(mCalculatorDisplay)) {
TestTV.append("\nentered equal\"\"");
NoRepeatNumber="";
} else {
if (NoRepeatNumber == "") {
NoRepeatNumber = String.valueOf(mCalculatorDisplay);
TestTV.append("\nNoRepeatNumber =" + NoRepeatNumber);
}
}
if(!NumberingEnded){
mCalculatorDisplay.setText(NoRepeatNumber + FullNumber);
}
if (!Started) {
Started = true;
}
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
Number[Ni] = Integer.parseInt(FullNumber);
}
}
userIsInTheMiddleOfTypingANumber = true;
} else {}}
Call mCalculatorDisplay.getText().toString() instead of String.valueOf(mCalculatorDisplay).
I guess mCalculatorDisplay is an EditText?
Update: NoRepeatNumber = String.valueOf(mCalculatorDisplay); - this is the problem part