Throwing OutOfMemoryError Android - java

My Scenario is, I have some data's in Database SQLite. I can get data's Correctly by,
Cursor c0 = OCTDBHelper.myDataBase.rawQuery("SELECT DISTINCT ALIAS FROM ICT32 where ALIAS NOT NULL", null);
Log.i("IC-Count", "IC-Count : " + c0.getCount());
String arr[] =new String[c0.getCount()];
c0.moveToFirst();
for(int i = 0; i < c0.getCount(); i++)
{
arr[i] = c0.getString(0);
c0.moveToNext();
}
here i got all data's correctly in arr like,
arr[0] :abcb,hjhj,jkshdf,hdjf,ghsg,aghgh,
arr[1] : klkl,sdjk,jkji,iui,jiji,jij,
.
.
.
arr[n] : qw,rwer,re,tr,yty,uyu,rtr,ter,etr,yrt,ytr
ie, each location has 10-30 data with comma(,). total arr.length is 1322
after getting that data i need to do some operation with those data as follow as,
I need to split(",") based on comma(,) and add into Single List until array reach n'th position.
Finally my output should be,
list[0] : abcb
list[1] : hjhj
list[2] : jkshdf
...
list[n-1] : yrt
list[n] : ytr
I think already did correctly. but it gives error like Throwing OutOfMemoryError
My code is,
Cursor c0 = OCTDBHelper.myDataBase.rawQuery("SELECT DISTINCT ALIAS FROM ICT32 where ALIAS NOT NULL", null);
Log.i("IC-Count", "IC-Count : " + c0.getCount());
ArrayList<String> tmp = new ArrayList<>();
c0.moveToFirst();
for(int i = 0; i < c0.getCount(); i++)
{
String arr[] = c0.getString(0).split(",");
for(int j= 0; j< arr.length;i++)
{
if(!arr[j].equals(","))
{
tmp.add(arr[j]);
}
}
c0.moveToNext();
}
Log.i("Alias" , "count : " +tmp.size());
this code gives Throwing OutOfMemoryError
Logcat
FATAL EXCEPTION: main
Process: estec.android.mvi32, PID: 11005
java.lang.OutOfMemoryError: Failed to allocate a 103059952 byte allocation with 16777120 free bytes and 58MB until OOM
at java.util.ArrayList.add(ArrayList.java:118)
at estec.android.mvi32.OCTActivity.onOptionsItemSelected(OCTActivity.java:294)
at android.app.Activity.onMenuItemSelected(Activity.java:2882)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:144)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:99)
at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:541)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:187)
at android.widget.AdapterView.performItemClick(AdapterView.java:300)
at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044)
at android.widget.AbsListView.onTouchUp(AbsListView.java:3872)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3627)
at android.view.View.dispatchTouchEvent(View.java:8388)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2424)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2158)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2172)
at android.widget.PopupWindow$PopupViewContainer.dispatchTouchEvent(PopupWindow.java:1682)
at android.view.View.dispatchPointerEvent(View.java:8578)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4021)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3887)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5701)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5675)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5646)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5791)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
How to resolve this problem??.

This for loop never terminates, look close at the last part:
for(int j= 0; j< arr.length;i++)
Change the i++ to j++ to fix this bug.

Related

How to fix Integer.intValue() for RTL languages in Android

In my application I write some codes and this codes I used string.
I want use UTF-8 languages (Farsi), But after run application show me error and force close application.
But when use English language not show me any error and run successfully!!
My codes :
this.q.put("dry land swim", Integer.valueOf(R.array.dry_land_swim));
TypedArray obtainTypedArray = getResources().obtainTypedArray(((Integer) this.q.get(stringArray[i])).intValue());
int length = obtainTypedArray.length();
int[] iArr2 = new int[length];
WorkoutData workoutData = new WorkoutData();
for (int i2 = 0; i2 < length; i2++) {
iArr2[i2] = obtainTypedArray.getResourceId(i2, -1);
}
workoutData.setExcName(stringArray[i]);
Log.e("ShowError", "" + (this.r.get(stringArray[i])).intValue());
workoutData.setExcDescResId(((Integer) this.r.get(stringArray[i])).intValue());
When change this line text (from En to Fa) :
this.q.put("تست", Integer.valueOf(R.array.dry_land_swim));
Show me error for this lines :
TypedArray obtainTypedArray = getResources().obtainTypedArray(((Integer) this.q.get(stringArray[i])).intValue());
workoutData.setExcDescResId(((Integer) this.r.get(stringArray[i])).intValue());
Error message :
java.lang.RuntimeException: Unable to start receiver com.crazytrends.healthmanager.WalkandStep.receivers.HardwareStepCountReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.crazytrends.healthmanager/.WalkandStep.services.HardwareStepCounterService }: app is in background uid UidRecord{528e8bd u0a841 RCVR idle change:idle|uncached procs:1 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver(ActivityThread.java:4452)
at android.app.ActivityThread.access$1600(ActivityThread.java:301)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2159)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8512)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.crazytrends.healthmanager/.WalkandStep.services.HardwareStepCounterService }: app is in background uid UidRecord{528e8bd u0a841 RCVR idle change:idle|uncached procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1795)
at android.app.ContextImpl.startService(ContextImpl.java:1740)
at android.content.ContextWrapper.startService(ContextWrapper.java:738)
at android.content.ContextWrapper.startService(ContextWrapper.java:738)
at com.crazytrends.healthmanager.WalkandStep.receivers.HardwareStepCountReceiver.onReceive(HardwareStepCountReceiver.java:22)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:4443)
How can I Fix it?

Getting the cover image of song from local media

ContentResolver musicResolver = getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri,null,null,null,null);
if(musicCursor!=null && musicCursor.moveToFirst()){
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int imageColumn = musicCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
//Add songs to the array list
do{
String theArt = musicCursor.getString(imageColumn);
Bitmap image = BitmapFactory.decodeFile(theArt);
long songId = musicCursor.getLong(idColumn);
String songTitle = musicCursor.getString(titleColumn);
String songArtist = musicCursor.getString(artistColumn);
songsArrayList.add(new Songs(songId,songTitle,songArtist,image));
}while (musicCursor.moveToNext())
I want to get the cover image of the song which i am getting from the local storage, I have no idea how to do it so i get
int imageColumn =
musicCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
this code on internet to get album art this is showing error when i get string from it . That accessing column -1 , I think its not getting the right column to get the image , please let me know how to get the image from media in the way of above code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.downloadbro.mumusic, PID: 10877
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.downloadbro.mumusic/com.downloadbro.mumusic.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2755)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2816)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1555)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6383)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at android.database.CursorWrapper.getString(CursorWrapper.java:137)
at com.downloadbro.mumusic.MainActivity.getSongList(MainActivity.java:80)
at com.downloadbro.mumusic.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6861)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
And this may give me album art but i want media art no function as such showing to me

ArrayList just recognise the first element

I have an ArrayList that I add some data in a method, when I try to remove a item that isn't the first one I get the following error
07-25 00:39:03.024 28960-28960/murilopereira.brofut E/[HAS CHECK]: 2
07-25 00:39:03.025 28960-28960/murilopereira.brofut E/[CHECK INDEX]: udidjdid
0
84jdkd
1
07-25 00:39:07.787 28960-29062/murilopereira.brofut D/OpenGLRenderer: endAllActiveAnimators on 0x7f6b86bc00 (MenuPopupWindow$MenuDropDownListView) with handle 0x7f6b8e6940
07-25 00:39:08.054 28960-28960/murilopereira.brofut E/[HAS CHECK]: 1
07-25 00:39:08.055 28960-28960/murilopereira.brofut E/[CHECK INDEX]: 84jdkd
0
07-25 00:39:08.055 28960-28960/murilopereira.brofut D/AndroidRuntime: Shutting down VM
07-25 00:39:08.060 28960-28960/murilopereira.brofut E/AndroidRuntime: FATAL EXCEPTION: main
Process: murilopereira.brofut, PID: 28960
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at murilopereira.brofut.Times.deleteTeam(Times.java:203)
at murilopereira.brofut.Times.access$100(Times.java:29)
at murilopereira.brofut.Times$2.onClick(Times.java:109)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
But if I check the size of the array, that indicates a number uppon one
My code to delete:
public static ArrayList<String> hasKeys = new ArrayList<>();
...
private void deleteTeam(int indexRemove){
Log.e("[HAS CHECK]", hasKeys.size() + "");
for(int i = 0; i < hasKeys.size(); i++){
Log.e("[CHECK INDEX]", hasKeys.get(i));
Log.e("[CHECK INDEX]", i + "");
}
// Log.e("[CHECK INDEX]", hasKeys.indexOf(m_orders.get(indexRemove).getTeamName()) + "");
hasKeys.remove(hasKeys.indexOf(m_orders.get(indexRemove).getTeamName()) - 1);
Menu.teams.remove(m_orders.get(indexRemove).getTeamName());
m_orders.remove(indexRemove);
m_adapter.removeItem(indexRemove);
m_adapter.notifyDataSetChanged();
}
I'm using the following code to add items to it
m_orders = new ArrayList<Teams>();
Teams o1 = new Teams();
hasKeys.add(teamName.getText().toString());
Log.e("[HAS CHECK]", hasKeys.size() + "");
o1.setTeamName(teamName.getText().toString());
o1.setTeamPlayers(playerOne.getText().toString() + ", " + playerTwo.getText().toString() + ", " + playerThree.getText().toString() + ", " + playerFour.getText().toString() + ", " + playerFive.getText().toString());
Menu.teams.put(o1.getTeamName(), o1.getTeamPlayers());
m_orders.add(o1);
This is happening because your item is always added at index 0. The size of array list is 1 every time from your add items. I don't know the exact flow of your code. But it's seems like if you are calling below statement every time:
m_orders = new ArrayList<Teams>();
This is instantiating your array list.

How to use a Cursor?

I have an app that receives the id of an animal and pass that id to a method from the database that will be read several times in a do-while. I want to know why this error happens?
This is my code:
bd = new BaseDados(getApplicationContext());
Cursor cc = bd.getIdAnimal(chipnumber);
if (cc.moveToFirst()) {
idanimal = cc.getInt(cc.getColumnIndex("idanimal"));
}
Cursor ccc = bd.getGruupsnosAnimals(idanimal);
do{
if(ccc.moveToFirst()){
String groupname= ccc.getString(ccc.getColumnIndex("groupname"));
}
}while (ccc.moveToNext());
This is my error:
Process: com.example.nobre.myapplication, PID: 4529
android.database.sqlite.SQLiteException: not an error (code 0)
at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method)
at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:845)
at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:144)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:197)
at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:237)
at com.example.nobre.myapplication.Activities.VerAnimaisActivity.showDialog(VerAnimaisActivity.java:193)
at com.example.nobre.myapplication.Activities.VerAnimaisActivity$2.onClick(VerAnimaisActivity.java:153)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Exception: not an error? That's a new one.
Your bottom loop is a bit weird and may be a bug- you're moving to next but may not even have moved to first if that failed. And if it succeeded you'll infinitely loop. Try this instead:
if(ccc.moveToFirst()){
do{
String groupname= ccc.getString(ccc.getColumnIndex("groupname"));
}while (ccc.moveToNext());
}
do{
if(ccc.moveToFirst()){
String groupname= ccc.getString(ccc.getColumnIndex("groupname"));
}
}while (ccc.moveToNext());
this is an infinite loop, while you have next item in your cursor, you move to first one, and next iteration you would again move to first one.
Also do not forget to call Cursor.close() after usage.
Try this:
// Move the cursor to the first row if cursor is not empty
if(ccc.moveToFirst()) {
do{
String groupname= ccc.getString(ccc.getColumnIndex("groupname"));
}while (ccc.moveToNext()); // Move cursor to next row until it pass last entry
}
Instead of:
do{
if(ccc.moveToFirst()) {
String groupname= ccc.getString(ccc.getColumnIndex("groupname"));
}
}while (ccc.moveToNext());

Remove extra dots in float value before a separater " , " occurs using java

I am generating a statistical calculator application.
So I want to format input from edittext like this
i/p = 3.5.6, 6.5 to 3.5 , 6.5
Using " , " (comma) as separator so splitting the input string to float array when a " , " occurs.
I want to ignore 3.5[.6] and generate array like this
s[1] = 3.5 , s[2] = 6.5
While calculating mean application crashes due to extra " . " dots.
s = it.getText().toString(); //"it" is edittext
s=s.replaceAll( ",+" , "," );
String[] strarray =s.split(",");
float[] farray = new float[strarray.length];
for(int i = 0; i < strarray.length; i++)
{
farray[i] = Float.parseFloat(strarray[i]);
}
--DEBUG LOGCAT--
W/dalvikvm(3051): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid float: "6.7."
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:310)
at java.lang.Float.parseFloat(Float.java:300)
at com.cal.mc2.Mean$1.onClick(Mean.java:67)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)`
`at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.cal.mc2/.Mean
How about this simple function (IdeOne link here: https://ideone.com/utKPjP):
public static float myParseFloat(String str) {
int firstDot = str.indexOf('.');
if (firstDot != -1) {
int secondDot = str.indexOf('.', firstDot+1);
return Float.parseFloat(secondDot == -1 ? str : str.substring(0,secondDot));
}
return Float.parseFloat(str);
}
Then you just replace this statement in your code:
farray[i] = Float.parseFloat(strarray[i]);
with:
farray[i] = myParseFloat(strarray[i]);
You can use regex like this :
public static void main(String[] args) {
String s = "3.5.6, 6.5";
s = s.replaceAll("(?<=\\d\\.\\d)\\.\\d", "");// positive look behind. Only replace `.[digit]` if it is preceeded by [digit][.][digit]
System.out.println(s);
String[] arr = s.split(",");
System.out.println(Arrays.toString(arr));
}
O/P :
3.5, 6.5 --> value of s after replacement
[3.5, 6.5] --> array contents

Categories

Resources