Album image cover and java.lang.OutOfMemoryError - java

I am developing an app that show all album image covers. But it crashes with this error:
11-10 18:08:48.148 16187-16187/com.xrobot.andrew.musicalbums E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xrobot.andrew.musicalbums, PID: 16187
java.lang.OutOfMemoryError: Failed to allocate a 1459276 byte allocation with 421736 free bytes and 411KB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:417)
at android.graphics.drawable.Drawable.createFromPath(Drawable.java:1230)
at com.xrobot.andrew.musictest2.SongAdapter.getView(SongAdapter.java:73)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.makeAndAddView(ListView.java:1875)
at android.widget.ListView.fillDown(ListView.java:702)
at android.widget.ListView.correctTooLow(ListView.java:1484)
at android.widget.ListView.fillGap(ListView.java:676)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5036)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4584)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Partial code in the onCreate method:
...
while(...){
String thisCover = getCoverArtPath(cursor.getLong(6), getApplicationContext());
songList.add(new Song(thisId, thisTitle, thisArtist, thisPath, thisDuration, thisCover));
}
SongAdapter songAdt = new SongAdapter(getApplicationContext(), songList);
...
Code that I use to get the album image cover:
private static String getCoverArtPath(long albumId, Context context) {
Cursor albumCursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + " = ?",
new String[]{Long.toString(albumId)},
null
);
boolean queryResult = albumCursor.moveToFirst();
String result = null;
if (queryResult) {
result = albumCursor.getString(0);
}
albumCursor.close();
return result;
}
Layout AlbumCover :
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/song_cover"
android:scaleType = "fitXY"
android:src="#drawable/note"
android:background="#171717"
android:padding="1dp"
android:layout_marginLeft="3dp" />
getView in the Adapter:
#Override
public View getView(View convertView, ViewGroup parent) {
RelativeLayout songLay = (RelativeLayout)songInf.inflate
(R.layout.song_layout, parent, false);
ImageView coverView = (ImageView)songLay.findViewById(R.id.song_cover);
//get song using position
Song currSong = songs.get(position);
if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
coverView.setImageDrawable(img);
}
//set position as tag
songLay.setTag(position);
return songLay;
}
EDIT:
I have tryed glide as suggested, but I still get the same error:
if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
Glide.with(mContext).load("").placeholder(img).override(50,50).into(coverView);
}
This is the new error:
11-11 11:05:55.866 11120-11120/com.xrobot.andrew.musicalbumsE/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xrobot.andrew.musicalbums, PID: 11120
java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available

Related

ContextMenu Fails To Remove A Row From A ListView With A Custom Adapter

The Problem is: My ContextMenu Fails to Remove a Row from a ListView with a Custom Adapter and the app crashes with a NullPointerException, see Logcat output.
I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.
My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.
Java Code: class TestActivity
public class TestActivity extends ListActivity {
private String itemNameArray[];
private String dateArray[];
private ListView listview;
CustomListViewAdapter customListViewAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
registerForContextMenu(getListView());
root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
getDir(root);
listview = getListView();
name=itemNameArray;
lastmod=dateArray;
CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);
listview.setAdapter(customListViewAdapter);
} // End of onCreate code.
class CustomListViewAdapter extends ArrayAdapter<String> {
Context context;
String[] nameArray;
String[] modifiedArray;
CustomListViewAdapter(Context c, String[] name, String[] lastmod)
{
super(c, R.layout.layout_item_view, R.id.rowtext, name);
this.context = c;
this.nameArray = name;
this.modifiedArray = lastmod;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.layout_item_view, parent, false);
TextView myName;
TextView myLastMod;
myName=(TextView) row.findViewById(R.id.rowtext);
myName.setText(nameArray[position]);
myLastMod=(TextView) row.findViewById(R.id.textView6);
myLastMod.setText(modifiedArray[position]);
return row;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem itemMenu) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();
switch (itemMenu.getItemId()) {
case R.id.context_menu_rename:
Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
return true;
case R.id.context_menu_delete:
// NOTE TESTING the line of code below caused a runtime error: java.lang.NullPointerException
customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
customListViewAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
return true;
return super.onContextItemSelected(itemMenu);
}
}
}
Logcat output:
11-12 12:46:59.965 14265-14265/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
11-12 12:46:59.981 14265-14265/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.testing.listapp, PID: 14265
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.testing.listapp.TestActivity$CustomListViewAdapter.remove(java.lang.Object)' on a null object reference
at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5454)
at android.app.Activity.onMenuItemSelected(Activity.java:2905)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
at android.widget.AbsListView$3.run(AbsListView.java:3860)
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)
Logcat output #2 :
11-13 10:45:21.229 21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
11-13 10:45:21.246 21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.testing.listapp, PID: 21432
java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:638)
at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
at java.util.AbstractCollection.remove(AbstractCollection.java:229)
at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
at android.app.Activity.onMenuItemSelected(Activity.java:2905)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
at android.widget.AbsListView$3.run(AbsListView.java:3860)
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)
Try to change the line
CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);
to:
customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);
just curious if is the local variable, anyway the instance variable CustomListViewAdapter has been initialized.
Have a look to the famous SO post that usually is given when there are NPE

Getting Null Pointer exception while using Palette API getRgb() method

Am not able figure out the solution for this problem Please help me.
Am trying to change the color of the toolbar by extracting the color in an image inside the collapseToolbarLayout here is my java code
public class ToolbarColorDynamic extends AppCompatActivity {
private CollapsingToolbarLayout collapsingToolbarLayout;
ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toolbar_color_dynamic);
setupToolbar();
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar4);
collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));//to set the title
mImageView = (ImageView) findViewById(R.id.profile_id1);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.leodicaprio);
mImageView.setImageBitmap(bm);
setToolbarColor(bm);
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar4);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
// Show menu icon
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
}
/* This method is to set the color and to set the image*/
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
private Palette createPaletteSync(Bitmap bitmap) {
Palette p = Palette.from(bitmap).generate();
return p;
}
private Palette.Swatch checkVibrantSwatch(Palette p){
Palette.Swatch vibrant = p.getVibrantSwatch();
if (vibrant != null){
return vibrant;
}
return null;
}
}
I tried several steps like assert the value to not equal to null
assert vibrantSwatch != null;
and this step too--
if(vibrantSwatch != null){
tb.setBackgroundColor(vibrantSwatch.getRgb());
}
But Nothing seems to work!... I tried googling and check here too but couldn't find a solution for this.
Below is my logcat log
04-21 12:06:32.420 20288-20288/basavaraj.com.librarytools E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
04-21 12:06:37.974 20288-20288/basavaraj.com.librarytools E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{basavaraj.com.librarytools/basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic.setToolbarColor(ToolbarColorDynamic.java:64)
at basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic.onCreate(ToolbarColorDynamic.java:42)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395) 
at android.app.ActivityThread.access$600(ActivityThread.java:162) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5371) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method)
Please help solve this issue.
Thank you!..
Your Toolbar is null. At the beginning in your setupToolbar() Method you reference the toolbar with the ID R.id.toolbar4 but inside of setToolbarColor() you reference it by R.id.toolbar
I found the solution.
In setToolbarColor() method i was referencing to a wrong toolbar id
so i just changed the code:-
From----
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);//This is the line i did silly mistake
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
To---
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar4);
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}

Android app keep crashing to OutOfMemoryError

My app keep crashing, and I can't understand what's wrong with it, been searching for answer everywhere, from what I understood, people said it is because of the device is out of memory, but I don't understand what is causing this ?
Is it because I have too many images in my res/drawable folder ?
Is it because I have one quite high resolution image in my res/drawable folder ?
If the problem is one of the above, what is the solution ? put the images in assets folder or what ? Below is the error stacks.
Thank you.
MainActivity.java
public class MainActivity extends Activity {
Class <? extends Activity> classVariable;
int last_level;
TextView text_play, text_level, game_title;
RelativeLayout playBtn, levelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (RelativeLayout) findViewById(R.id.playBtn);
levelBtn = (RelativeLayout) findViewById(R.id.levelBtn);
game_title = (TextView) findViewById(R.id.game_title);
text_play = (TextView) findViewById(R.id.text_play);
text_level = (TextView) findViewById(R.id.text_level);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/snap-itc.ttf");
text_play.setTypeface(tf);
text_level.setTypeface(tf);
game_title.setTypeface(tf);
// Check if file exists
File file = getBaseContext().getFileStreamPath("levels.json");
if (file.exists()) {
// Get the JSON Object from the data
JSONObject parent = this.parseJSONData();
try {
last_level = parent.getInt("level");
} catch (JSONException e) {
e.printStackTrace();
}
}
switch (last_level) {
case 1:
classVariable = Level002Activity.class;
break;
case 2:
classVariable = Level003Activity.class;
break;
case 3:
classVariable = Level004Activity.class;
break;
case 5:
classVariable = Level005Activity.class;
break;
default:
classVariable = Level001Activity.class;
}
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
Level002Activity.class);
startActivity(i);
}
});
levelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(),
Level001Activity.class);
startActivity(in);
}
});
}
public JSONObject parseJSONData() {
String JSONString = null;
JSONObject jsonObject = null;
try {
// Open the inputStream to the file
FileInputStream fin = openFileInput("levels.json");
int sizeOfJSONFile = fin.available();
// array that will store all the data
byte[] bytes = new byte[sizeOfJSONFile];
// reading data into the array from the file
fin.read(bytes);
// close the input stream
fin.close();
JSONString = new String(bytes, "UTF-8");
jsonObject = new JSONObject(JSONString);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException x) {
x.printStackTrace();
return null;
}
return jsonObject;
}
}
It keeps showing that error when calling ChooseLevelActivity.class
ChooseLevelActivity.java
public class ChooseLevelActivity extends Activity implements View.OnClickListener {
ImageView level001, level002, level003, level004, level005;
int last_level, best_move;
String best_time, level_selected;
TextView levelName, bestMove, bestTime;
Class <? extends Activity> classVariable;
Button playBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_level);
level001 = (ImageView) findViewById(R.id.level001);
level002 = (ImageView) findViewById(R.id.level002);
level003 = (ImageView) findViewById(R.id.level003);
level004 = (ImageView) findViewById(R.id.level004);
level005 = (ImageView) findViewById(R.id.level005);
levelName = (TextView) findViewById(R.id.level_name);
bestMove = (TextView) findViewById(R.id.best_move);
bestTime = (TextView) findViewById(R.id.best_time);
playBtn = (Button) findViewById(R.id.playBtn);
// Get the JSON Object from the data
JSONObject parent = parseJSONData("levels.json");
// Array of ImageView
final ImageView[] levelsArray = {level001, level002, level003, level004, level005};
// This will store all the values inside "best_move and time" in an element string
try {
last_level = parent.getInt("level");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < last_level; i++) {
levelsArray[i].setVisibility(View.VISIBLE);
levelsArray[i].setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.level001:
level_selected = "level001";
classVariable = Level001Activity.class;
break;
case R.id.level002:
level_selected = "level002";
classVariable = Level002Activity.class;
break;
case R.id.level003:
level_selected = "level003";
classVariable = Level003Activity.class;
break;
case R.id.level004:
level_selected = "level004";
classVariable = Level004Activity.class;
break;
case R.id.level005:
level_selected = "level005";
classVariable = Level005Activity.class;
break;
}
String fileName = "record_" + level_selected + ".json";
// Get the JSON Object from the data
JSONObject parents = parseJSONData(fileName);
// This will store all the values inside "best_move and time" in an element string
try {
best_move = parents.getInt("best_move");
best_time = parents.getString("best_time");
} catch (JSONException e) {
// e.printStackTrace();
}
levelName.setText("Level " + level_selected.substring(5));
bestMove.setText("Best Move: " + best_move);
bestTime.setText("Best Time: " + best_time);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
classVariable);
startActivity(i);
finish();
}
});
}
public JSONObject parseJSONData(String file) {
String JSONString = null;
JSONObject jsonObject = null;
try {
// Open the inputStream to the file
FileInputStream fin = openFileInput(file);
int sizeOfJSONFile = fin.available();
// array that will store all the data
byte[] bytes = new byte[sizeOfJSONFile];
// reading data into the array from the file
fin.read(bytes);
// close the input stream
fin.close();
JSONString = new String(bytes, "UTF-8");
jsonObject = new JSONObject(JSONString);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException x) {
x.printStackTrace();
return null;
}
return jsonObject;
}
}
Error Stacks:
Process: com.example.ed.pieces, PID: 12939
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ed.pieces/com.example.ed.pieces.Level001Activity}: android.view.InflateException: Binary XML file line #289: Binary XML file line #289: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #289: Binary XML file line #289: Error inflating class <unknown>
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
at android.app.Activity.setContentView(Activity.java:2166)
at com.example.ed.pieces.Level001Activity.onCreate(Level001Activity.java:62)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #289: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
        at android.app.Activity.setContentView(Activity.java:2166)
        at com.example.ed.pieces.Level001Activity.onCreate(Level001Activity.java:62)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 10240012 byte allocation with 4194304 free bytes and 7MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.view.View.<init>(View.java:3948)
at android.widget.ImageView.<init>(ImageView.java:145)
at android.widget.ImageView.<init>(ImageView.java:140)
at android.widget.ImageView.<init>(ImageView.java:136)
Out of Memory Error
Out of memory error is very common error when you are developing for a application that deals with multiple images sets or large bitmaps or some Animation stuff. In this case we have to be very careful and efficient while handling the images or object allocation and deallocation. OOM error comes when the allocation crosses the heap limit or your process demand a amount of memory that crosses the heap limit.
In Android, every application runs in a Linux Process. Each Linux Process has a Virtual Machine (Dalvik Virtual Machine) running inside it. There is a limit on the memory a process can demand and it is different for different devices and also differs for phones and tablets. When some process demands a higher memory than its limit it causes a error i.e Out of memory error.
Try this may help you add this tag in your manifest file.
android:largeHeap="true"
it will allocate large heap for your app
To convert Drawable into Bitmap,Use this,
Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
Using this method,you can decode your image
public static Bitmap decodeImageFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
Then call this method where you using this:
Bitmap b = decodeImageFile(f, 1280, 720);
if your image resolution is high, i suggested you loading image with buffer.
String defCoverPath = "drawable/" + "def_cover" + ".png";
yourView.setBackgroundDrawable(LoadResourceImage(defCoverPath));
public static BitmapDrawable LoadResourceImage(String resPath){
AssetManager assets = MyApp.GetContext().getResources().getAssets();
BitmapDrawable bitmapDrawable = new BitmapDrawable();
try {
InputStream buffer = new BufferedInputStream((assets.open(resPath)));
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
bitmapDrawable = new BitmapDrawable(MyApp.GetContext().getResources(), bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmapDrawable;
}

createBitmap throws outOfMemory exception very often

my app is throwing outofmemory exceptions to lots of people using it. my app creates a bitmap of the current screen then animates it to transition between pages.
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4222)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4217)
... 10 more
Caused by: android.view.InflateException: Binary XML file line #118: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:640)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.de_veloper.businessbuilder.MainActivity.premiumMenu(MainActivity.java:558)
... 13 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
... 23 more
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 8683212 byte allocation with 6867876 free bytes and 6MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:726)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:547)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1014)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:3723)
at android.content.res.Resources.loadDrawable(Resources.java:3596)
at android.content.res.TypedArray.getDrawable(TypedArray.java:750)
at android.widget.ImageView.<init>(ImageView.java:151)
at android.widget.ImageView.<init>(ImageView.java:140)
at android.widget.ImageView.<init>(ImageView.java:136)
... 26 more
the code that creates the bitmap
public static Bitmap loadBitmapFromView(View v) {
Bitmap bitmap;
v.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v.getDrawingCache());
bitmap.setHasAlpha(false);
v.setDrawingCacheEnabled(false);
return bitmap;
}
the code that animates the bitmap
public void mainMenu(View view) {
$isonfirstpage = 0;
$isonmainmenu = 1;
$isonpremiummenu = 0;
final RelativeLayout backgroundLayout = (RelativeLayout) findViewById(R.id.activity_background);
LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout newLayout = (RelativeLayout)inflate.inflate(R.layout.main_menu, null);
Bitmap bitmap = loadBitmapFromView(backgroundLayout);
Drawable d = new BitmapDrawable(getResources(), bitmap);
backgroundLayout.removeAllViewsInLayout();
View mainmenuView = findViewById(R.id.mainmenuView);
View firstpageView = findViewById(R.id.firstpageView);
final ImageView screenie = new ImageView(getApplicationContext());
screenie.setImageDrawable(d);
backgroundLayout.addView(newLayout);
backgroundLayout.addView(screenie);
screenie.animate()
.translationY(backgroundLayout.getHeight())
.setDuration(300);
new Handler().postDelayed(new Runnable() {
public void run() {
backgroundLayout.removeView(screenie);
}
}, 1500);
}
when ever the Bitmap size is huse then you will get OutOfMemory Exception you can decode/scale the bitmap when ever you are setting it to the imageview.
public Bitmap decodeUri(Uri path) throws FileNotFoundException
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(path),null,o);
int REQUIRED_SIZE = 100;
int width_temp = o.outWidth;
int height_temp = o.outHeight;
int scale = 1;
while (true)
{
if(width_temp/2 < REQUIRED_SIZE || height_temp/2<REQUIRED_SIZE)
{
break;
}
width_temp/=2;
height_temp/=2;
scale*=2;
}
BitmapFactory.Options o1 =new BitmapFactory.Options();
o1.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(path),null,o1);
}
you can covert your image path to Uri as follows
decodeUri(Uri.fromFile(new File("your file path")))

NullPointerException on startAnimation(anim)

I'm getting a NullPointerException on blah.startAnimation(anim), which is inside a LongClickListener. What I'm trying to do is get the number of children in a GridLayout on a DragListener, and set an animation to all of the children when you start to drag an imageview. For some reason this returns a NullPointerException,
Where it's coming from is:
#Override
public boolean onLongClick(View v) {
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(null, shadowBuilder, v, 0);
deleteAreaForAdapter.setVisibility(View.VISIBLE);
deleteAreaForAdapter.startAnimation(slide_in);
for(int i=0; i<middleViewForAdapter.getChildCount(); i++) {
int middleChildCount = middleViewForAdapter.getChildCount();
int middleChildCount1 = middleViewForAdapter.getChildCount();
int topChildCount = middleViewForAdapter.getChildCount();
int topChildCount1 = middleViewForAdapter.getChildCount();
int bottomChildCount = middleViewForAdapter.getChildCount();
LinearLayout topChild = (LinearLayout)topViewForAdapter.getChildAt(i);
LinearLayout topChild1 = (LinearLayout)topViewForAdapter1.getChildAt(i);
LinearLayout bottomChild = (LinearLayout)bottomViewForAdapter.getChildAt(i);
Context context = mContext;
Animation shakeAnim = AnimationUtils.loadAnimation(context, R.anim.shake);
// do stuff with child view
//ll.clearAnimation();
/*middleChild1.startAnimation(shakeAnim);
topChild.startAnimation(shakeAnim);
topChild1.startAnimation(shakeAnim);
bottomChild.startAnimation(shakeAnim);*/
if(middleChildCount > 0)
{
GridLayout hjk = middleViewForAdapter;
LinearLayout middleChild = (LinearLayout)hjk.getChildAt(i);
middleChild.startAnimation(shakeAnim);
ll.clearAnimation();
}
if(middleChildCount1 > 0)
{
GridLayout hjs = middleLayoutForAdapter1;
LinearLayout middleChild1 = (LinearLayout)hjs.getChildAt(i);
middleChild1.startAnimation(shakeAnim); //Line it's coming from!
ll.clearAnimation();
}
if(topChildCount > 0)
{
topChild.startAnimation(shakeAnim);
ll.clearAnimation();
}
if(topChildCount1 > 0)
{
topChild1.startAnimation(shakeAnim);
ll.clearAnimation();
}
}
v.setVisibility(View.INVISIBLE);
return true;
}
});
LogCat:
08-14 07:47:18.281 2078-2078/com.matt.cards.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.matt.cards.app, PID: 2078
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.startAnimation(android.view.animation.Animation)' on a null object reference
at com.matt.cards.app.DrawerLongClickListener$1.onLongClick(DrawerLongClickListener.java:169)
at android.view.View.performLongClick(View.java:4474)
at android.view.View$CheckForLongPress.run(View.java:18401)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
Thanks!
EDIT: Can anyone Help!?!?!?
you just have to use
Animation shakeAnim = AnimationUtils.loadAnimation(v.getContext(), R.anim.shake);
in place of
Animation shakeAnim = AnimationUtils.loadAnimation(context, R.anim.shake);
Answer was simple, I just had to create an instance of
for(int i=0; i<middleViewForAdapter.getChildCount(); i++) for every RelativeLayout I wanted it to work on (I was using RelativeLayout.getChildAt(i); for every relativeLayout I had).

Categories

Resources