IndexOutofBounds when sorting arraylist - android

I'm in the process of adding Actionbarsherlock to my app to update the UI for Android 2.2/2.3 users. ABS is working great but I found an issue with older devices where the ListView would hang after the app was opened after a reboot. The app lists all apps with Internet Permission and then adds a few special apps (the app is a firewall) and would hang while trying to display the information.
Originally the code cached the apps after building the list using standard arrays. I want to move the app away from the caching since i think that's a huge reason for some of the hanging. So I've been moving everything from arrays to ArrayLists for easier usage. I ran into one IndexOutofBounds but corrected that one but this one is stumping me completely. Here is my code for getting the apps and sorting code.
Any help would be greatly appreciated and if any other code is needed please ask!
Thanks in advance!
App list code:
int count = 0;
try {
final PackageManager pkgmanager = ctx.getPackageManager();
final List<ApplicationInfo> installed = pkgmanager
.getInstalledApplications(PackageManager.GET_META_DATA);
final HashMap<Integer, DroidApp> map = new HashMap<Integer, DroidApp>();
final Editor edit = prefs.edit();
boolean changed = false;
String name = null;
String cachekey = null;
final String cacheLabel = "cache.label.";
DroidApp app = null;
for (final ApplicationInfo apinfo : installed) {
count = count + 1;
if(applist != null){
applist.doProgress(count);
}
boolean firstseen = false;
app = map.get(apinfo.uid);
// filter applications which are not allowed to access the
// Internet
if (app == null
&& PackageManager.PERMISSION_GRANTED != pkgmanager
.checkPermission(Manifest.permission.INTERNET,
apinfo.packageName)) {
continue;
}
// try to get the application label from our cache -
// getApplicationLabel() is horribly slow!!!!
cachekey = cacheLabel + apinfo.packageName;
name = prefs.getString(cachekey, "");
if (name.length() == 0) {
// get label and put on cache
name = pkgmanager.getApplicationLabel(apinfo).toString();
edit.putString(cachekey, name);
changed = true;
firstseen = true;
}
if (app == null) {
app = new DroidApp();
app.uid = apinfo.uid;
app.names = new ArrayList<String>();
app.names.add(name);
app.appinfo = apinfo;
map.put(apinfo.uid, app);
} else {
app.names.add(name);
}
app.firstseen = firstseen;
// check if this application is selected
if (!app.selected_wifi
&& Arrays.binarySearch(selected_wifi, app.uid) >= 0) {
app.selected_wifi = true;
}
if (!app.selected_3g
&& Arrays.binarySearch(selected_3g, app.uid) >= 0) {
app.selected_3g = true;
}
if (!app.selected_roaming
&& Arrays.binarySearch(selected_roaming, app.uid) >= 0) {
app.selected_roaming = true;
}
if (!app.selected_vpn
&& Arrays.binarySearch(selected_vpn, app.uid) >= 0) {
app.selected_vpn = true;
}
}
if (changed) {
edit.commit();
}
/* add special applications to the list */
List<DroidApp> special = new ArrayList<DroidApp>();
special.add(new DroidApp(
SPECIAL_UID_ANY,
"(Any application) - Same as selecting all applications", false, false, false, false));
special.add(new DroidApp(SPECIAL_UID_KERNEL, "(Kernel) - Linux kernel", false, false, false, false));
special.add(new DroidApp(android.os.Process.getUidForName("root"), "(root) - Applications running as root", false, false, false, false));
special.add(new DroidApp(android.os.Process.getUidForName("media"),"Media server", false, false, false, false));
special.add(new DroidApp(android.os.Process.getUidForName("vpn"), "VPN networking", false, false, false, false));
special.add(new DroidApp(android.os.Process.getUidForName("shell"), "Linux shell", false, false, false, false));
special.add(new DroidApp(android.os.Process.getUidForName("gps"), "GPS", false, false, false, false));
for (int i = 0; i < special.size(); i++) {
app = special.get(i);
if (app.uid != -1 && !map.containsKey(app.uid)) {
// check if this application is allowed
if (Arrays.binarySearch(selected_wifi, app.uid) >= 0) {
app.selected_wifi = true;
}
if (Arrays.binarySearch(selected_3g, app.uid) >= 0) {
app.selected_3g = true;
}
if (Arrays.binarySearch(selected_roaming, app.uid) >= 0) {
app.selected_roaming = true;
}
if (Arrays.binarySearch(selected_vpn, app.uid) >= 0) {
app.selected_vpn = true;
}
map.put(app.uid, app);
}
}
/* convert the map into an array */
applications = new ArrayList<DroidApp>(map.values());
return applications;
Sorting code:
class ApplicationSort implements Comparator<DroidApp> {
#Override
public int compare(DroidApp o1, DroidApp o2) {
if (o1.firstseen != o2.firstseen) {
return (o1.firstseen ? -1 : 1);
}
boolean o1_selected;
boolean o2_selected;
boolean vpnenabled = getApplicationContext()
.getSharedPreferences(Api.PREFS_NAME, 0).getBoolean(
Api.PREF_VPNENABLED, false);
boolean roamenabled = getApplicationContext()
.getSharedPreferences(Api.PREFS_NAME, 0).getBoolean(
Api.PREF_ROAMENABLED, false);
if (vpnenabled && !roamenabled) {
o1_selected = o1.selected_3g || o1.selected_wifi
|| o1.selected_vpn;
o2_selected = o2.selected_3g || o2.selected_wifi
|| o2.selected_vpn;
if (o1_selected == o2_selected) {
return String.CASE_INSENSITIVE_ORDER.compare(
o1.names.get(0).toString(), o2.names.get(0).toString());
}
if (o1_selected)
return -1;
}
if (roamenabled && !vpnenabled) {
o1_selected = o1.selected_3g || o1.selected_wifi
|| o1.selected_roaming;
o2_selected = o2.selected_3g || o2.selected_wifi
|| o2.selected_roaming;
if (o1_selected == o2_selected) {
return String.CASE_INSENSITIVE_ORDER.compare(
o1.names.get(0).toString(), o2.names.get(0).toString());
}
if (o1_selected)
return -1;
}
if (roamenabled && vpnenabled) {
o1_selected = o1.selected_3g || o1.selected_wifi
|| o1.selected_roaming || o1.selected_vpn;
o2_selected = o2.selected_3g || o2.selected_wifi
|| o2.selected_roaming || o2.selected_vpn;
if (o1_selected == o2_selected) {
return String.CASE_INSENSITIVE_ORDER.compare(
o1.names.get(0).toString(), o2.names.get(0).toString());
}
if (o1_selected)
return -1;
}
if (!roamenabled && !vpnenabled) {
o1_selected = o1.selected_3g || o1.selected_wifi;
o2_selected = o2.selected_3g || o2.selected_wifi;
if (o1_selected == o2_selected) {
return String.CASE_INSENSITIVE_ORDER.compare(
o1.names.get(0).toString(), o2.names.get(0).toString());
}
if (o1_selected)
return -1;
}
return 1;
}
}
ListView code that calls the sorting class
private void createListView(final String searching) {
this.dirty = false;
boolean results = false;
List<DroidApp> namesearch = new ArrayList<DroidApp>();
final List<DroidApp> appnames = Api.getApps(this, null);
if (searching != null && searching.length() > 1) {
for (DroidApp app : appnames) {
for (String str : app.names) {
if (str.contains(searching.toLowerCase())
|| str.toLowerCase().contains(
searching.toLowerCase())) {
namesearch.add(app);
results = true;
}
}
}
}
final List<DroidApp> apps = results ? namesearch
: searching.equals("") ? appnames
: new ArrayList<Api.DroidApp>();
// Sort applications - selected first, then alphabetically
Collections.sort(apps, new ApplicationSort());

I do not see what is DroidApp, but you are using something like this:
o1.names.get(0) and o2.names.get(0)
Is it possible that some of the DroidApps have empty names lists?

Related

how to prevent an Android App root detection failed in a frida code 'antiroot'

On rooted device(by Magisk), my Android app failed root detection when using the below frida code. The app contains root detection module and obfuscation.
Anything I can do to prevent bypass? Is Protect the app from bypassing the root detection (Frida Server) also would work for the case?
Thanks in advance.
Java.perform(function() {
var RootPackages = ["com.topjohnwu.magisk"
];
var RootBinaries = ["su", "busybox", "magisk"];
var RootProperties = {
"ro.build.selinux": "1",
"ro.debuggable": "0",
"service.adb.root": "0",
"ro.secure": "1"
};
var RootPropertiesKeys = [];
for (var k in RootProperties) RootPropertiesKeys.push(k);
var NativeFile = Java.use('java.io.File');
var ProcessBuilder = Java.use('java.lang.ProcessBuilder');
var useProcessManager = false;
NativeFile.exists.implementation = function() {
var name = NativeFile.getName.call(this);
var shouldFakeReturn = (RootBinaries.indexOf(name) > -1);
if (shouldFakeReturn) {
return false;
} else {
return this.exists.call(this);
}
};
ProcessBuilder.start.implementation = function() {
var cmd = this.command.call(this);
var shouldModifyCommand = false;
for (var i = 0; i < cmd.size(); i = i + 1) {
var tmp_cmd = cmd.get(i).toString();
if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd.indexOf("mount") != -1 || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd.indexOf("id") != -1) {
shouldModifyCommand = true;
}
}
if (shouldModifyCommand) {
this.command.call(this, ["grep"]);
return this.start.call(this);
}
if (cmd.indexOf("su") != -1) {
this.command.call(this, ["SOMEFAKECMD"]);
return this.start.call(this);
}
return this.start.call(this);
};
if (useProcessManager) {
var ProcManExec = ProcessManager.exec.overload('[Ljava.lang.String;', '[Ljava.lang.String;', 'java.io.File', 'boolean');
ProcManExec.implementation = function(cmd, env, workdir, redirectstderr) {
var fake_cmd = cmd;
for (var i = 0; i < cmd.length; i = i + 1) {
var tmp_cmd = cmd[i];
if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd == "mount" || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd == "id") {
var fake_cmd = ["grep"];
}
if (tmp_cmd == "su") {
var fake_cmd = ["SOMEFAKECMD"];
}
}
return ProcManExec.call(this, fake_cmd, env, workdir, redirectstderr);
};
}
});
(the code originally from https://codeshare.frida.re/#dzonerzy/fridantiroot/ , removed unnecessary parts)

Luxand API for similarity on android

I'm going to use Luxand api for detect persons.
Scenario:
1- At the first on register activity persons sit in front of the camera and take pictures and templates save on sqlite database. also personal information will be save;
2- After that On detect activity one of them sit in front of the camera and take Auto detection and find same temp and show person information.(similarity is 96%)
my problem:Unfortunately too times detection is wrong and two different people’s templates will be recognized as the same person.
My Code:
1- Register activity for register form
for (int i = 0; i < MAX_FACES; ++i) {
if (rects[i] != null && rects[i].x1 <= x && x <= rects[i].x2 && rects[i].y1 <= y && y <= rects[i].y2 + 30) {
mTouchedID = IDs[i];
mTouchedIndex = i;
temp = (byte[]) ImageFrameFaceIDTemps.get(mTouchedID);
if (mPreview != null) {
onTouchMode = true;
try {
requesting name on tapping the face
if (faceSelected != null) {
faceSelected.Selected(temp, data);
}
} finally {
onTouchMode = false;
}
}
break;
}
2- Detection activity for match form
public int RetrievePersonDetection(byte[] template, float[] maxSimilarity_UnderAccepted, float[] maxSimilarityArray) {
if (IDTemps == null || IDTemps.size() == 0) {
return 0;
}
int person = 0;
FSDK_FaceTemplate currentFaceTemp = new FSDK_FaceTemplate();
currentFaceTemp.template = template;
float[] similarityArray = new float[1];
float maxSimilarity = 0;
float MatchingThreshold[] = new float[1];
FSDK.GetMatchingThresholdAtFRR(LocalSetting.MIN_ACCEPTED_SIMILAITY, MatchingThreshold);
for (int i = 0; i < IDTemps.size(); i++) {
long key = IDTemps.keyAt(i);
FSDK_FaceTemplate faceTemp = (FSDK_FaceTemplate) IDTemps.get(key);
int result = FSDK.MatchFaces(currentFaceTemp, faceTemp, similarityArray);
if (result == 0) {
if (maxSimilarity < similarityArray[0] && similarityArray[0] >= MatchingThreshold[0]) {
maxSimilarity = similarityArray[0];
person = (int) key;
maxSimilarityArray[0] = similarityArray[0];
FSDK_FaceTemplate currentFaceTemp2 = new FSDK_FaceTemplate();
}
else if (maxSimilarity_UnderAccepted[0] < similarityArray[0]) {
maxSimilarity_UnderAccepted[0] = similarityArray[0];
}
}
}
return person;
}
I don't no what's my problem? why return wrong person and 2 person similarity is 96%

How to access Device song from internal memoy

I am new to android development here and I want to open internal memory from my app. But it is open on all devices except Samsung device. It's showing fine on Motorola device, other phones and in Emulator also. I am getting null here: if (scanFolder == null) {return null;}
public List<Folder> loadInBackground() {
List<Folder> folderList = new ArrayList<>();
List<Song> songList = new ArrayList<>();
// Permission Check Runtime For M and above
if (PermissionChecker.checkCallingOrSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) {
FileExtensionFilter mFileExtensionFilter = new FileExtensionFilter(Constants.fileExtensions);
if (dir != null) {
File[] scanFolder = dir.listFiles(mFileExtensionFilter);
// Getting Null over here in Samsung Device scanFolder getting null
if (scanFolder == null) {
return null;
}
// Get Folder List
for (File aScanFolder : scanFolder) {
Folder folder = new Folder();
Cursor cursor = getContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.DATA}, MediaStore.Audio.Media.DATA + " like ? ", new String[]{"%" + aScanFolder.getAbsolutePath() + "%"}, null);
if (cursor != null) {
int count = cursor.getCount();
if (count != 0) {
if (!aScanFolder.isDirectory()) {
String path = aScanFolder.getAbsolutePath();
Song song = Helper.getSongData(Extras.getInstance().getSongSortOrder(), getContext(), path);
songList.add(song);
}
if (!aScanFolder.getAbsolutePath().startsWith("/d")) {
Log.e("FolderLoader", "Path --> " + aScanFolder.getAbsolutePath());
folder.setFile(aScanFolder);
folder.setFileCount(count);
folder.setSongList(songList);
folderList.add(folder);
}
}
}
if (cursor != null) {
cursor.close();
}
}
Collections.sort(folderList, new Comparator<Folder>() {
#Override
public int compare(Folder f1, Folder f2) {
if ((f1.getFile().isDirectory() && f2.getFile().isDirectory()))
return f1.getFile().getName().compareToIgnoreCase(f2.getFile().getName());
else if (f1.getFile().isDirectory() && !f2.getFile().isDirectory())
return -1;
else if (!f1.getFile().isDirectory() && f2.getFile().isDirectory())
return 1;
else if (!f1.getFile().isDirectory() && !f2.getFile().isDirectory())
return f1.getFile().getName().compareToIgnoreCase(f2.getFile().getName());
else return 0;
}
});
if (!dir.getAbsolutePath().equals("/")) {
Folder folder = new Folder();
if (dir.getParentFile() != null) {
folder.setFile(dir.getParentFile());
Log.e("FolderLoader", dir.getParentFile().getAbsolutePath());
folderList.add(0, folder);
}
}
}
return folderList;
} else {
// Error Message
Log.d("Folder", "Permission not granted");
return Collections.emptyList();
}
}
I am getting this Screen UI in Samsung Device.
Getting All songs in Other device except Samsung Device

App crashes sometimes when starting videoview

I am using VideoView to play live streams and it works fine most of the time, but sometimes the app freezes for a moment and either continues to play or crash and send me to home screen.
This is what happens when i select an item from the listview or click KEY_DOWN / KEY_UP:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
if (mVideoView != null && mListView == null) {
if (listViewNext != listViewCurrent) { playChannel(listViewNext, 0); }
return true;
}
}
}
private void playChannel(int channel, int id) {
listViewCurrent = channel;
listViewNext = listViewCurrent + 1;
listViewPrev = listViewCurrent - 1;
if (mListViewChannels == "Danish") {
if (listViewNext >= arrayDanishChannels.size()) { listViewNext = 0; }
if (listViewPrev < 0) { listViewPrev = arrayDanishChannels.size() - 1; }
mListViewLink = arrayDanishLinks.get(listViewCurrent);
} else if (mListViewChannels == "World") {
if (listViewNext >= arrayWorldChannels.size()) { listViewNext = 0; }
if (listViewPrev < 0) { listViewPrev = arrayWorldChannels.size() - 1; }
mListViewLink = arrayWorldLinks.get(listViewCurrent);
}
String listViewName = (String) listView.getItemAtPosition(listViewCurrent);
String[] links = mListViewLink.split(";"); int temp = id + 1;
if (id < 0 || temp > links.length) { id = 0; temp = 1; }
mListViewLink = links[id]; listViewLinkId = temp; listViewLinkIds = links.length;
startVideo(listViewName+" ("+listViewLinkId+"/"+listViewLinkIds+")", mListViewLink);
mListViewCurrent = mListViewChannels;
}
private void startVideo(String title, String link) {
toastDisplay.cancel();
setInfoView(title);
imageView.setVisibility(ImageView.INVISIBLE);
videoView.removeCallbacks(videoRunnable);
videoView.stopPlayback();
MediaController media = new MediaController(MainActivity.this); media.setAnchorView(videoView); media.setMediaPlayer(videoView);
videoView.setMediaController(media);
videoView.setVideoPath(link);
videoView.setOnPreparedListener(videoViewPreparedListener);
videoView.setOnErrorListener(videoViewErrorListener);
videoView.setVisibility(VideoView.VISIBLE);
videoView.postDelayed(videoRunnable, videoViewTimeOut);
videoView.start();
mVideoView = "true";
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor edit = pref.edit();
edit.putString("setLastStream", title+";"+mListViewChannels);
edit.apply();
}
private void setInfoView(String title) {
infoView.removeCallbacks(infoRunnable);
infoView.setText(title);
infoView.setVisibility(TextView.VISIBLE);
progressBar.setVisibility(ProgressBar.VISIBLE);
}
Just a note: I have payed for the streams and some are free to access for anyone, no illegal content.
I am using an android set top box with firmware 4.4.2
I have tried to add try { .. } finally { .. } everywhere and it still freezes sometimes at random times.
Please help, im new in making apps and this is really driving me crazy.
Sorry for my bad english.

Haxe, OpenFL android debug giving error in for cpp

I'm developing an app in FlashDevelop, using Haxe and OpenFl
When I test my app in flash target, it works fine. But when I compile for android, it comes up with this error during the compilation:
./src/ReaderView2.cpp: In member function 'virtual Void ReaderView2_obj::setZoom()':
./src/ReaderView2.cpp:653: error: base operand of '->' has non-pointer type 'String'
Build halted with errors (haxelib.exe).
...Which is obviously something to do with cpp, which I'm not really an expert.
Does any body know what the error means?
Here's the setZooom function: (the whole file is quite large)
public function setZoom()
{
hideOptions();
while (numChildren > 0)
{
Main.remove(getChildAt(0));
}
if (image != null) if (image.parent != null) image.parent.removeChild(image);
images = new Array();
field = new TextField();
var fieldFont = Assets.getFont("fonts/Kreon-Regular.ttf");
var format:TextFormat = new TextFormat(fieldFont.fontName, currentZoom, 0x4F4F4F);
format.align = TextFormatAlign.LEFT;
field.defaultTextFormat = format;
field.embedFonts = true;
field.text = fullText;
field.selectable = false;
field.wordWrap = true;
field.border = false;
field.autoSize = TextFieldAutoSize.LEFT;
field.width = displayWidth;
//field.x = 0;
//split string into words
var allParas:Array<String> = fullText.split("\r\n");
var words:Array<String>;
var fields:Array<TextField> = new Array();
var tempField:TextField = null;
var contentHeight:Float = displayHeight;
var wordI:Int;
var paraI:Int = 0;
var tempArr2:Array<String>;
while (paraI < allParas.length)
{
if (false) //check img tag
{
}
else //if para is words
{
wordI = 0;
words = allParas[paraI].split(" ");
while (wordI < words.length)
{
if (tempField == null || tempField.textHeight > contentHeight)
{
if (tempField != null) {
wordI--;
tempArr2 = tempField.text.toString().split(" ");
for (i in 0... tempArr2.length)
{
tempArr2.remove("");
}
tempArr2.pop();
tempField.text = tempArr2.join(" ");
}
tempField = new TextField();
tempField.defaultTextFormat = field.getTextFormat();
tempField.embedFonts = true;
tempField.text = "";
tempField.border = false;
tempField.selectable = false;
tempField.wordWrap = true;
tempField.autoSize = TextFieldAutoSize.LEFT;
tempField.width = displayWidth-2;
tempField.x = 0;
fields.push(tempField);
}
else
{
tempField.appendText(words[wordI] + (wordI == words.length - 1? "\n": " "));
wordI++;
}
}
}
paraI++;
}
var bd:BitmapData;
for (i in 0... fields.length)
{
bd = new BitmapData(Std.int(fields[i].width), Std.int(fields[i].height));
bd.draw(fields[i]);
images.push(new Bitmap(bd, PixelSnapping.AUTO, true));
}
//addChild(fields[0]);
images[0].x = 10;
addChild(images[0]);
currentPageInstance = images[0];
currentPage = 0;
drawScrollBar();
if (optionsBtn!=null)addChild(optionsBtn);
}
So apparently using the toString() funcion gives problems for a cpp target.

Categories

Resources