How to count pdf pages in fragment - java

To count pdf pages in a fragment I use https://github.com/TomRoush/PdfBox-Android but I got an error in line 197.
The error is:
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2
And my code is:
if (requestCode== 86 && resultCode==RESULT_OK && data!=null){
pdfUri = data.getData(); //return the uri of selected file.
notification.setText(data.getData().getLastPathSegment());
try {
PDFBoxResourceLoader.init(applicationContext);
PDDocument doc = PDDocument.load(applicationContext.getContentResolver().openInputStream(pdfUri));
noOfPages.setText(doc.getNumberOfPages()); //line 197
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}else{
Toast.makeText(getActivity(),"Please select a file",Toast.LENGTH_SHORT).show();
}
}

You are setting the text via setText() but that has multiple overloads , especially these 2 are interesting:
final void setText(int resid)
final void setText(CharSequence text)
So you are setting the Number of Pages as the text, but the value is an int - so the upper overload is used. Now the Number of Pages is not going to match any String constant (aka Resources) - that is basically the error.
You wanted to use the 2nd overload. To to that, pass a String instead of int.
either by doc.getNumberOfPages().toString() or by using String.valueOf(doc.getNumberOfPages()).

Related

Zebra RFID API Read Access Operation Code return null

I'm trying to develop a small Application for a Zebra handheld rfid reader and can't find a way to access the MemoryBank of the tag. My reader configuration is as follows:
private void ConfigureReader() {
if (reader.isConnected()) {
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.StartTrigger.setTriggerType(START_TRIGGER_TYPE.START_TRIGGER_TYPE_IMMEDIATE);
triggerInfo.StopTrigger.setTriggerType(STOP_TRIGGER_TYPE.STOP_TRIGGER_TYPE_IMMEDIATE);
try {
// receive events from reader
if (eventHandler == null){
eventHandler = new EventHandler();
}
reader.Events.addEventsListener(eventHandler);
// HH event
reader.Events.setHandheldEvent(true);
// tag event with tag data
reader.Events.setTagReadEvent(true);
reader.Events.setAttachTagDataWithReadEvent(true);
// set trigger mode as rfid so scanner beam will not come
reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE, true);
// set start and stop triggers
reader.Config.setStartTrigger(triggerInfo.StartTrigger);
reader.Config.setStopTrigger(triggerInfo.StopTrigger);
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
}
}
And the eventReadNotify looks like this:
public void eventReadNotify(RfidReadEvents e) {
// Recommended to use new method getReadTagsEx for better performance in case of large tag population
TagData[] myTags = reader.Actions.getReadTags(100);
if (myTags != null) {
for (int index = 0; index < myTags.length; index++) {
Log.d(TAG, "Tag ID " + myTags[index].getTagID());
ACCESS_OPERATION_CODE aoc = myTags[index].getOpCode();
ACCESS_OPERATION_STATUS aos = myTags[index].getOpStatus();
if (aoc == ACCESS_OPERATION_CODE.ACCESS_OPERATION_READ && aos == ACCESS_OPERATION_STATUS.ACCESS_SUCCESS) {
if (myTags[index].getMemoryBankData().length() > 0) {
Log.d(TAG, " Mem Bank Data " + myTags[index].getMemoryBankData());
}
}
}
}
}
When I'm scanning a tag I get the correct TagID but both myTags[index].getOpCode() and myTags[index].getOpStatus() return null values.
I appreciate every suggestion that might lead to a successful scan.
Thanks.
I managed to find a solution for my problem. To perform any Read or Write task with Zebra Handheld Scanners the following two conditions must be satisfied. Look here for reference: How to write to RFID tag using RFIDLibrary by Zebra?
// make sure Inventory is stopped
reader.Actions.Inventory.stop();
// make sure DPO is disabled
reader.Config.setDPOState(DYNAMIC_POWER_OPTIMIZATION.DISABLE);
You have to stop the inventory and make sure to disable dpo in order to get data other than the TagID from a Tag. Unfortunately this isn't mentioned in the docu for Reading RFID Tags.

How to fix "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" Android RFID 8500 Zebra

I am trying to develop and application to read and write to RF tags. Reading is flawless, but I'm having issues with writing. Specifically the error "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values"
I have tried reverse-engineering the Zebra RFID API Mobile by obtaining the .apk and decoding it, but the code is obfuscated and I am not able to decypher why that application's Write works and mine doesn't.
I see the error in the https://www.ptsmobile.com/rfd8500/rfd8500-rfid-developer-guide.pdf at page 185, but I have no idea what's causing it.
I've tried forcefully changing the writeData to Hex, before I realized that the API does that on its own, I've tried changing the Length of the writeData as well, but it just gets a null value. I'm so lost.
public boolean WriteTag(String sourceEPC, long Password, MEMORY_BANK memory_bank, String targetData, int offset) {
Log.d(TAG, "WriteTag " + targetData);
try {
TagData tagData = null;
String tagId = sourceEPC;
TagAccess tagAccess = new TagAccess();
tagAccess.getClass();
TagAccess.WriteAccessParams writeAccessParams = tagAccess.new WriteAccessParams();
String writeData = targetData; //write data in string
writeAccessParams.setAccessPassword(Password);
writeAccessParams.setMemoryBank(MEMORY_BANK.MEMORY_BANK_USER);
writeAccessParams.setOffset(offset); // start writing from word offset 0
writeAccessParams.setWriteData(writeData);
// set retries in case of partial write happens
writeAccessParams.setWriteRetries(3);
// data length in words
System.out.println("length: " + writeData.length()/4);
System.out.println("length: " + writeData.length());
writeAccessParams.setWriteDataLength(writeData.length()/4);
// 5th parameter bPrefilter flag is true which means API will apply pre filter internally
// 6th parameter should be true in case of changing EPC ID it self i.e. source and target both is EPC
boolean useTIDfilter = memory_bank == MEMORY_BANK.MEMORY_BANK_EPC;
reader.Actions.TagAccess.writeWait(tagId, writeAccessParams, null, tagData, true, useTIDfilter);
} catch (InvalidUsageException e) {
System.out.println("INVALID USAGE EXCEPTION: " + e.getInfo());
e.printStackTrace();
return false;
} catch (OperationFailureException e) {
//System.out.println("OPERATION FAILURE EXCEPTION");
System.out.println("OPERATION FAILURE EXCEPTION: " + e.getResults().toString());
e.printStackTrace();
return false;
}
return true;
}
With
Password being 00
sourceEPC being the Tag ID obtained after reading
Memory Bank being MEMORY_BANK.MEMORY_BANK_USER
target data being "8426017056458"
offset being 0
It just keeps giving me "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" and I have no idea why this is the case, nor I know what a "Word value" is, and i've searched for it. This is all under the "OperationFailureException", as well. Any help would be appreciated, as there's almost no resources online for this kind of thing.
Even this question is a bit older, I had the same problem so as far as I know this should be the answer.
Your target data "8426017056458" length is 13 and at writeAccessParams.setWriteDataLength(writeData.length()/4)
you are devide it with four. Now if you are trying to write the target data it is longer than the determined WriteDataLength. And this throws the Error.
One 'word' is 4 Hex => 16 Bits long. So your Data have to be filled up first and convert it to Hex.

CursorWindow: Window is full

I'm new and after days, maybe I found that I have this issue, I have a very big data in a big listView
W/CursorWindow: Window is full: requested allocation 1432389 bytes, free space 750700 bytes, window size 2097152 bytes
E/CursorWindow: Failed to read row 0, column 0 from a CursorWindow which has 0 rows, 64 columns.
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x420aeda0)
03-03 15:50:00.162 16239-16239/id.co.bumisentosa.yantek E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I have read some same issue
android java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow
And I found my issue is my image in blob (byte) will not load into my listView.
Then how can I solve my cameraIntent and save it to a specific folder then put it in database and load it in ListView. I really need your help and by examples. Thank You
What I was use is like this
public void openCamera(int resultCode) {
Inspection_JTR_Fragment_Foto_Tab.gallery = false;
File image = new File(appFolderCheckandCreate(resultCode), "img" + getTimeStamp()
+ ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
id.co.bumisentosa.yantek.fragment_JTM.Inspection_JTM_Fragment_Foto_Tab.cameraImagePath = image.getAbsolutePath();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, resultCode);
}
private String appFolderCheckandCreate(int resultCode) {
String appFolderPath = "";
File externalStorage = Environment.getExternalStorageDirectory();
switch (resultCode) {
case 1:
if (externalStorage.canWrite()) {
appFolderPath = externalStorage.getAbsolutePath() + "/yantek-babel-android/jtr/Keseluruhan Tiang";
File dir = new File(appFolderPath);
if (!dir.exists()) {
dir.mkdirs();
}
} else {
}
break;
}
return appFolderPath;
}
And save it to database
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
if (id == R.id.action_upload) {
// Upload data ke server
imageArray = Inspection_JTM_Fragment_Foto_Tab.getimageArray();
imageArray_2 = Inspection_JTM_Fragment_Foto_Tab.getimageArray_2();
databaseHandler.saveTest(new ItemsDetails(
imageArray,
imageArray_2
));
}
return super.onOptionsItemSelected(item);
}
my database
public String saveTest(ItemsDetails details) {
try {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, post.getId());
// cv.put(KEY_ID, "null");
cv.put(COL_LOCATION_ID, details.getunitID());
cv.put(COL_SECTION_ID, details.getjaringanID());
cv.put(COL_INSPECTION_DATE, details.gettanggalInspeksi());
cv.put(COL_INSPECTION_TYPE_ID, details.gettipeInspeksiID());
cv.put(COL_PHOTO_ENTIRE_PATH, details.getimageArray());
cv.put(COL_PHOTO_ISOLATOR_PATH, details.getimageArray_2());
cv.put(COL_POLE_NO, details.getnoTiang());
cv.put(COL_POLE_IRON, details.gettiangBesi());
cv.put(COL_POLE_CONCRETE, details.gettiangBeton());
cv.put(COL_POLE_WOOD, details.gettiangKayu());
cv.put(COL_POLE_CONDITION_BROKEN, details.getkondisiTiangRetak());
cv.put(COL_POLE_CONDITION_TILT, details.getkondisiTiangMiring());
cv.put(COL_POLE_CONDITION_SHIFT, details.getkondisiTiangPindah());
cv.put(COL_CROSS_ARM_TWIST, details.getcrossArmMelintir());
cv.put(COL_CROSS_ARM_RUST, details.getcrossArmKarat());
cv.put(COL_CROSS_ARM_TILT, details.getcrossArmMiring());
cv.put(COL_ARM_TIE_REPAIR, details.getarmTiePerbaiki());
cv.put(COL_ARM_TIE_RUST, details.getarmTieKarat());
cv.put(COL_ARM_TIE_BRACE, details.getarmTiePasang());
cv.put(COL_ISOLATOR_FULCRUM_R_LEAK, details.getisolatorTumpuRGompel());
cv.put(COL_ISOLATOR_FULCRUM_R_BROKEN, details.getisolatorTumpuRPecah());
cv.put(COL_ISOLATOR_FULCRUM_S_LEAK, details.getisolatorTumpuSGompel());
cv.put(COL_ISOLATOR_FULCRUM_S_BROKEN, details.getisolatorTumpuSPecah());
cv.put(COL_ISOLATOR_FULCRUM_T_LEAK, details.getisolatorTumpuTGompel());
cv.put(COL_ISOLATOR_FULCRUM_T_BROKEN, details.getisolatorTumpuTPecah());
cv.put(COL_ISOLATOR_PULL_R_LEAK, details.getisolatorTarikRGompel());
cv.put(COL_ISOLATOR_PULL_R_BROKEN, details.getisolatorTarikRPecah());
cv.put(COL_ISOLATOR_PULL_S_LEAK, details.getisolatorTarikSGompel());
cv.put(COL_ISOLATOR_PULL_S_BROKEN, details.getisolatorTarikSPecah());
cv.put(COL_ISOLATOR_PULL_T_LEAK, details.getisolatorTarikTGompel());
cv.put(COL_ISOLATOR_PULL_T_BROKEN, details.getisolatorTarikTPecah());
cv.put(COL_ARRESTER_R_BROKEN, details.getarresterRusakR());
cv.put(COL_ARRESTER_S_BROKEN, details.getarresterRusakS());
cv.put(COL_ARRESTER_T_BROKEN, details.getarresterRusakT());
cv.put(COL_CONDUCTOR_R_BUYER, details.getkonduktorRBuyer());
cv.put(COL_CONDUCTOR_R_LOOSE, details.getkonduktorRKendor());
cv.put(COL_CONDUCTOR_S_BUYER, details.getkonduktorSBuyer());
cv.put(COL_CONDUCTOR_S_LOOSE, details.getkonduktorSKendor());
cv.put(COL_CONDUCTOR_T_BUYER, details.getkonduktorTBuyer());
cv.put(COL_CONDUCTOR_T_LOOSE, details.getkonduktorTKendor());
cv.put(COL_CONNECTOR_PG_R_35MM, details.getkonektorPGR35mm());
cv.put(COL_CONNECTOR_PG_R_70MM, details.getkonektorPGR70mm());
cv.put(COL_CONNECTOR_PG_R_150MM, details.getkonektorPGR150mm());
cv.put(COL_CONNECTOR_PG_S_35MM, details.getkonektorPGS35mm());
cv.put(COL_CONNECTOR_PG_S_70MM, details.getkonektorPGS70mm());
cv.put(COL_CONNECTOR_PG_S_150MM, details.getkonektorPGS150mm());
cv.put(COL_CONNECTOR_PG_T_35MM, details.getkonektorPGT35mm());
cv.put(COL_CONNECTOR_PG_T_70MM, details.getkonektorPGT70mm());
cv.put(COL_CONNECTOR_PG_T_150MM, details.getkonektorPGT150mm());
cv.put(COL_BENDING_WIRE_R, details.getbendingWireR());
cv.put(COL_BENDING_WIRE_S, details.getbendingWireS());
cv.put(COL_BENDING_WIRE_T, details.getbendingWireT());
cv.put(COL_ULTRASONIC_R, details.getultrasonicR());
cv.put(COL_ULTRASONIC_S, details.getultrasonicS());
cv.put(COL_ULTRASONIC_T, details.getultrasonicT());
cv.put(COL_GSW_EXIST, details.getgswAda());
cv.put(COL_GSW_NOT_EXIST, details.getgswTidakAda());
cv.put(COL_TREE_EXIST, details.getpohonAda());
cv.put(COL_TREE_NOT_EXIST, details.getpohonTidakAda());
cv.put(COL_LONGITUDE, details.getlongitude());
cv.put(COL_LATITUDE, details.getlatitude());
cv.put(COL_SUGGESTION, details.getSaran());
cv.put(COL_DESCR, details.getketerangan());
db.insert(INSPECTIONS_MV_TABLE_NAME, null, cv);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return getNewTestID();
}
Then how can I solve my cameraIntent and save it to a specific folder
then put it in database and load it in ListView. I really need your
help and by examples.
In short you can't. Although you can store the image in the database you cannot retrieve it from the database because it is too large to fit into a CursorWindow which has a limitation of 2MB (2097152).
The image itself is around 1432389 bytes but the CursorWindow only has 750700 bytes. So as 1432389 is greater than 750700 image (blob) it can't be extracted.
You can get around the issue if you :-
save it to a specific folder, then
save the path (or part of the path) in the database rather than the image, and then
extract the path and then get the image via the path when loading the ListView.

How to gracefully check if a raw resource doesn't exist?

I have a method in my class called play and I want play which plays an audio file. Which file is played depends on the classes current audioIndex value. Basically, there's a switch like this:
int rId;
switch (audioIndex){
case 0: rId = R.raw.e0.wav; break;
case 1: rId = R.raw.e1.wav; break;
default: rId = R.raw.error.wav; break;
}
After the switch I want to verify if the rId is valid before I pass it to MediaPlayer.create(this, rId). It appears create does not throw an exception if the id doesn't exist or can't be opened. So I must check before passing it?
How to gracefully handle this? Until now I have just assumed the rId will always be correct but I would like to check to make sure.
You can get the resource identifier from the filename with this method. It will return 0 if it is not a valid resource ID. See this question for more.
The project shouldn't compile if the resource doesn't exist though, as R.resourcetype.resourcename won't exist in R.java. This is only useful if you don't know what resources you'll have at runtime.
I would suggest you using my method to get a resource ID. If you make simple exception handling there, you will see, that if your resource does not exist it will be thrown. That would gracefully resolve your issue.
Here's the code:
/**
* #author Lonkly
* #param variableName - name of drawable, e.g R.drawable.<b>image</b>
* #param с - class of resource, e.g R.drawable, of R.raw
* #return integer id of resource
*/
public static int getResId(String variableName, Class<?> с) {
Field field = null;
int resId = 0;
try {
field = с.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}

Parsing URL error

It didn't seem like there was a post about this, so here goes. I've been working on a simple app to grab my time table from my school, and get it on my phone. Currently I'm working on the port on android but I've hit an issue. I get the error:
java.io.IOException: -1 error loading URL urladress.
Code:
public void updateTimeTable(){
//Get UID and Birthday
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String uid = prefs.getString("uid", "000000");
String fods = prefs.getString("fodsdag", "000000");
//Set URL
String url = "http://unv1.aalborg-stu.dk/cgi-bin/elevskema.pl?ugen=0&unavn=" + uid + "&fodsdag=" + fods;
try {
Document doc = Jsoup.connect(url).get();
Elements td = doc.getElementsByTag("td");
//ArrayList<String> tdArray = new ArrayList<String>();
// for (Element tds : td) {
// String tdText = tds.text();
// tdArray.add(tdText);
//}
//String[] data = tdArray.toArray(new String[tdArray.size()]);
} catch (IOException e ){
Log.e("Parser", "shite", e);
}
Context context = getApplicationContext();
CharSequence text = url;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
I've commented some lines out to identify where the issue is, and it seems it's at the actual parsing. Anywho, screenshot of the error I get:
Screenshot
I got about 4 days worth of Java experience so forgive me if it's something silly.
Best Regards
Hmm.. hard to say like that, but in a lucky guess, did you set the internet permission in the manifest.xml ?
<uses-permission
android:name="android.permission.INTERNET" />

Categories