Getting java.lang.OutOfMemoryError when trying to run android app - java

Hi I am trying to create an android application to display images so that you can click on a 'next' button and then the next image shows. So far I have this method
public void buttonClick(){
imgView = (ImageView)findViewById(R.id.imgView);
buttonS = (Button)findViewById(R.id.button);
buttonS.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % images.length;
imgView.setImageResource(images[current_image_index]);
}
}
);
}
However when I try to run this, I get a java.lang.OutOfMemoryError when I click the 'next' button twice. Am I doing something wrong? My image array looks like this:
int[] images = {R.drawable.img};
I have tried changing the Manifest file to include
android:largeHeap="true"
This is where I set the variables and call the method above
public class MainActivity extends AppCompatActivity {
private static ImageView imgView;
private static Button buttonS;
private int current_image_index;
int[] images = {R.drawable.dog,R.drawable.img};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
}
The stack trace is:
08-29 23:17:34.781 15450-15450/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.daniel.firstapp, PID: 15450
java.lang.OutOfMemoryError: Failed to allocate a 2070252108 byte allocation with 16777216 free bytes and 482MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:816)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:637)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1019)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:3778)
at android.content.res.Resources.loadDrawable(Resources.java:3651)
at android.content.res.Resources.getDrawable(Resources.java:1865)
at android.content.Context.getDrawable(Context.java:408)
at android.widget.ImageView.resolveUri(ImageView.java:752)
at android.widget.ImageView.setImageResource(ImageView.java:408)
at com.example.daniel.firstapp.MainActivity$1.onClick(MainActivity.java:40)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
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:6141)
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)

It is because the assigned heap for the application to handle the memory for all the images is low. You can increase it in the Android manifest file.
specify
android:largeHeap="true"
as a property of <application> tag
eg:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:largeHeap="true"
android:theme="#style/AppTheme" >
and see if that fixes the issue.
One option is to scale down the images before you display it.
Recycle the ImageView before you add the new image (But this will not hold up if the image is very large).

Related

Hi! I am new to android app development. I tried to create a simple counter but after build getting error "Unable to instantiate activity"

public abstract class MainActivity extends AppCompatActivity {
Button decrement;
Button increment;
TextView counter_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Log.i("tag", "onCreate: Created Successfully");
increment=findViewById(R.id.inc_btn);
decrement=findViewById(R.id.dec_btn);
counter_view=findViewById(R.id.counter);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cnt_text=counter_view.getText().toString();
int cnt_no= Integer.parseInt(cnt_text);
cnt_no=cnt_no+1;
counter_view.setText(cnt_no+"");
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cnt_text=counter_view.getText().toString();
int cnt_no=Integer.parseInt(cnt_text);
cnt_no=cnt_no-1;
counter_view.setText(cnt_no+"");
}
});
}
Error:
2021-02-10 00:29:06.870 16714-16714/? E/Zygote: v2
2021-02-10 00:29:06.871 16714-16714/? E/Zygote: accessInfo : 0
2021-02-10 00:29:07.017 16714-16714/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.counter_app, PID: 16714
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.counter_app/com.example.counter_app.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.counter_app.MainActivity> cannot be instantiated
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2849)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.counter_app.MainActivity> cannot be instantiated
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1086)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2839)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 
I suppose this is your first screen/activity/class that is displayed on launch i.e it is your launcher activity. If yes,
the launcher activity cannot be abstract. Because when an app is launched from the home screen on an Android device, the Android OS creates an instance of the activity in the application you have declared to be the launcher activity. And abstract classes can not be instantiated, they can only be sub-classed.
Please remove the word abstract before your class name.
add to your manifest file this line
<activity android:name="your.package.name.MainActivity"/>

splash screen is not working in android 6

I have added splash screen in my app but the app crashes when is run on Android 6. The interesting thing is that the app runs fine on Android 9.
Don't know what to do.
Target SDK - 28.
min SDK= 19
it is showing error on oncreate method while run app on android 6
splash.java
import android.os.Bundle;
import android.os.Handler;
public class splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // it showing error here.
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 4000;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent splashintent=new Intent(splash.this,MainActivity.class);
startActivity(splashintent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
logs
06-22 16:17:30.930 10294-10294/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.napps.wallpaper, PID: 10294
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.napps.wallpaper/com.napps.wallpaper.splash}: android.content.res.Resources$NotFoundException: Resource ID #0x7f07009e
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5896)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f07009e
at android.content.res.Resources.getValue(Resources.java:1595)
at androidx.appcompat.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:331)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:198)
at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:260)
at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
at com.napps.wallpaper.splash.onCreate(splash.java:13)
at android.app.Activity.performCreate(Activity.java:6298)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5896) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
There might be problem with your drawable Image. While copying image Please check the folder in which you are copying.
Try to add the image in drawable folder not drawable-21
I would suggest to remove old image and Add Image again to proper directory.

easiest way to play mp3 from storage

I'm a newbie. I just want to play mp3 in my app.
I've read the documentation and I browsed through many websites including this one.
The steps should be
MediaPlayer.setDataSource(String) or (context, Uri)
.prepare();
.start();
My file is in /storage/emulated/0/New Folder/ztz3.mp3 ..
if i use External.getExternalDirectory().getPath() the result is /storage/emulated/0/
but it just won't play.
I've browsed many sites.. trying many things but it just didn't work.
I've used permission to read external storage.
and the sites I'm browsing has too many different answers which only confused me more.
some use AudioManager.STREAM.. some use MediaPlayer.create.
and I followed that too.. but it just won't play.
public class MainActivity extends AppCompatActivity {
Button buttonPlay;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.buttonPlay);
// String filePath = Environment.getExternalStorageDirectory()+
// "/New Folder/ztz_3_adding.mp3";
// String filePath = "/storage/emulated/0/New Folder/ztz_3_adding.mp3";
Log.e("Dir", Environment.getExternalStorageDirectory().toString());
Log.e("Directory", Environment.getExternalStorageDirectory().getPath());
mediaPlayer = new MediaPlayer();
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// mediaPlayer.setDataSource("/storage/emulated/0/New Folder/ztz_3_adding.mp3");
// mediaPlayer.setDataSource("file://storage/emulated/0/New Folder/ztz_3_adding.mp3");
mediaPlayer.setDataSource(getApplicationContext(),
Uri.parse(Environment.getExternalStorageDirectory().getPath()+
"/New Folder/ztz_3_adding.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
//mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
I think the problem is in the prepare() method.. but I don't know how to fix it.
I've read and tried a site that said to use static MediaPlayer.create or something.
I just want a simple media player that use a string value that I can change anytime to play mp3 files based on the layout.
thanks for the help before...
the log...
02-25 22:10:08.546 17345-17345/com.echo.tesmediaplayer E/Dir:
/storage/emulated/0 02-25 22:10:08.548
17345-17345/com.echo.tesmediaplayer E/Directory: /storage/emulated/0
02-25 22:10:08.563 17345-17345/? E/MediaPlayer: prepareAsync called in
state 1 02-25 22:10:08.564 17345-17345/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.echo.tesmediaplayer, PID: 17345
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.echo.tesmediaplayer/com.echo.tesmediaplayer.MainActivity}:java.lang.IllegalStateException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)at
android.app.ActivityThread.access$900(ActivityThread.java:163)at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)at
android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.app.ActivityThread.main(ActivityThread.java:5585) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.IllegalStateExceptionat
android.media.MediaPlayer._prepare(Native Method) at
android.media.MediaPlayer.prepare(MediaPlayer.java:1158) at
com.echo.tesmediaplayer.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:6279) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
at android.app.ActivityThread.access$900(ActivityThread.java:163) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.app.ActivityThread.main(ActivityThread.java:5585) at
java.lang.reflect.Method.invoke(Native Method) at
.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Do you have the permissions set correctly?
You need:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
See: https://developer.android.com/guide/topics/media/mediaplayer.html#manifest

Android recieving classcastexception despite being in correct class

I have an activity with a viewpager containing 2 fragments, inside each fragment contains a list, from this list a button can be pressed that creates a new fragment in the viewpager, this works fine until I create a new activity and close it, after the new activity is closed and I return to the previous activity pressing the button to create a new fragment again now gives a classcastexception, almost as if the closed activity is still open, but it is not, I have tried searching this issue and cant find any examples of this being encountered by anyone else which makes me wonder how this could be happening, I will post some code examples below, any help will go a long way thanks.
Click listener in ListAdapter:
holder.rlStatusContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add new comment fragment and set page
try {
((HomeFragmentActivity) activity).addCommentFragment(data.get(finalPosition));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Method in activity:
public void addCommentFragment(ArrayList<Object> fragmentExtras) {
list.add(NavigationFragment.newInstance(9, getApplicationContext(), this, fragmentExtras));
adapter.notifyDataSetChanged();
pager.setCurrentItem(list.size());
}
Error received:
12-13 13:37:50.177 17262-17262/test.test.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: test.test.com.test, PID: 17262
java.lang.ClassCastException: test.test.com.test.activities.NewPostActivity cannot be cast to test.test.com.test.activities.HomeFragmentActivity
at test.test.com.test.adapters.ListHomeAdapter$4.onClick(ListHomeAdapter.java:462)
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)

Button to set different activity colour

I am trying to set the background colour of a different activity from the activity main but I am getting a null pointer.
This is the main:
View activity;
activity = findViewById(R.layout.activity_connect_four);
The button:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
// null pointer on below line
activity.findViewById(android.R.id.content)
.setBackgroundColor(Color.BLACK);
}
});
The logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.con4.MainActivity$4.onClick(MainActivity.java:80)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Where the logCat is pointing to, I don't know what to change. Any help I would be grateful
You're receiving a NPE because that activity and view is not inflated, therefore it returns as null. The way you're setting the background color is flawed by nature. By setting it as you are, even without the NPE, you're storing a setting in the memory of the device. The moment that the device kills your activity, you'll lose that information. As an alternative, you need to store this setting on the device for later retrieval. For what you're attempting to do, I would recommend using SharedPreferences.
In your settings Activity:
Button highScoreButton1 = (Button) findViewById(R.id.bgc);
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
highScoreButton1.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
prefs.edit().putInt(BACKGROUND_COLOR, Color.BLACK).commit();
}
});
BACKGROUND_COLOR is a key variable that could be set to "background_color". Then when you start you other activity:
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
int color = prefs.getInt(BACKGROUND_COLOR, Color.WHITE);
And use that color to set the background. Using this method, the background color will be saved to the device until it gets overridden (settings change) or the app is uninstalled.
If you want this to be the background of all of your activity, I suggest having all activities extending a base activity and implementing that code there.
You can check out other storage methods here: http://developer.android.com/guide/topics/data/data-storage.html

Categories

Resources