Android app keep crashing to OutOfMemoryError - java

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;
}

Related

Trying to write a string to a file on Android app crashes on opening [duplicate]

This question already has an answer here:
getFileDir() cause NullPointer exception
(1 answer)
Closed 5 years ago.
I'm writing a simple journal app. I've currently got it to the point where I can open it, type stuff into a text box, and click the button to save it (but not yet actually save it). If I run it as is below (with the /commented out/ parts comment out) then it works, but if I make the comments be code, it crashes on launch. I've narrowed it down to the first commented line of code: File path = this.getFilesDir(); as causing the crash, though there may be more problems elsewhere that I haven't found yet.
Any idea why it's crashing? Or a better way for me to save text to a file?
public class MainActivity extends AppCompatActivity {
/* File path = this.getFilesDir();
File file = new File(path, "dreamWritings.txt");
FileOutputStream stream;*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = (TextView)findViewById(dreamText);
final Button button = (Button) findViewById(R.id.recordDream);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String dreamWords = tv.getText().toString();
/* try {
stream = new FileOutputStream(file, true);
}
catch(FileNotFoundException ex2){
System.out.println(ex2);
}
try {
stream.write(dreamWords.getBytes());
stream.close();
tv.setText("Hey I think we wrote that to a file!");
}
catch(IOException ex) {
System.out.println(ex);
}*/
tv.setText("Your dream has been recorded");
}
});
}
}
And here is the crash log:
08-11 22:23:22.772 1443-1443/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sixpencegames.www.dreamjournal, PID: 1443
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.sixpencegames.www.dreamjournal/com.sixpencegames.www.dreamjournal.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2568)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:223)
at com.sixpencegames.www.dreamjournal.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2558)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6121) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) 
Problem is you can't access this globally as context won't be assigned and hence returns null.
Try below
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = (TextView)findViewById(dreamText);
final Button button = (Button) findViewById(R.id.recordDream);
File path = this.getFilesDir();
File file = new File(path, "dreamWritings.txt");
FileOutputStream stream;
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String dreamWords = tv.getText().toString();
try {
stream = new FileOutputStream(file, true);
}
catch(FileNotFoundException ex2){
System.out.println(ex2);
}
try {
stream.write(dreamWords.getBytes());
tv.setText("Hey I think we wrote that to a file!");
}
catch(IOException ex) {
System.out.println(ex);
}finally{
stream.close();
}
tv.setText("Your dream has been recorded");
}
});
}

Getting a "android.os.NetworkOnMainThreadException" even though I am running it in a separate thread

Have very little experience in Android Development, and am trying to pull HTML directly from a website. I have written code that works fine when running it just straight java, but i get an "android.os.NetworkOnMainThreadException" when I try to run it through my app. Some googling has told me that I have to put it in a separate thread, which I believe I have done, but it's not helping. Here are my two different java class files, the first being the MainActivity and the second being my thread that is supposed to deal with getting the info from the website.
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
public static TextView main = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
main = (TextView) findViewById(R.id.main);
WebsiteDealerino jbae = new WebsiteDealerino();
jbae.start();
}
}
And here's my thread file:
public class WebsiteDealerino extends Thread {
public void run(){
try{
WebsiteDealerino jbae = new WebsiteDealerino();
String[] stuff = jbae.getQuestion();
MainActivity.main.setText(stuff[0]);
}catch(Exception e){}
}
public String[] getQuestion() {
try {
return parseHTML(getHTML("http://jbae.po8.org"));
} catch (IOException error) {
return new String[]{"Ran into an error" };
}
}
public String getHTML(String websiteURL) {
String content = null;
URLConnection connection = null;
try {
connection = new URL(websiteURL).openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
} catch (Exception ex) {
ex.printStackTrace();
}
return content;
}
public String[] parseHTML(String rawHTML) throws IOException {
String parsed = "";
boolean relevant;
String[] lines = rawHTML.split(System.getProperty("line.separator"));
for(String line : lines) {
relevant = true;
for (char piece : line.toCharArray()) {
if (piece == '<')
relevant = false;
}
if (relevant)
parsed += "SPLIT" + line;
}
String old = parsed;
parsed = "";
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./,+­ *!?|() :^~=";
for (int i = 1; i < old.length(); i++) {
int j = i - 1;
if ((old.toCharArray()[i] == ' ' && !characters.contains(old.toCharArray()[j] + "")))
parsed += "";
else
parsed += old.toCharArray()[i];
}
String fixed = "";
for (char Char : parsed.toCharArray()) {
if (characters.contains(Char + ""))
fixed += Char;
}
String[] parts = fixed.split("SPLIT");
int leng = parts.length;
int lengt = leng - 2;
String[] fixeds = new String[lengt];
int i = 0;
int empties = 0;
for (String part : parts) {
if (i + 2 < parts.length)
if (part.length() <= 1)
i++;
fixeds[i] = parts[i + 2];
empties++;
}
String[] finalized;
if (empties > 0) {
int len = fixeds.length;
finalized = new String[len - empties];
i = 0;
for (String fixe : fixeds) {
if (fixe.length() > 1) {
finalized[i] = fixe;
i++;
}
}
} else
finalized = fixeds;
i = 0;
for (String finale : finalized) {
if (finale.contains("Answer")) {
String answer = "";
String sensible = "0123456789.-";
for (char Char : finale.toCharArray()) {
if (sensible.contains(Char + ""))
answer += Char;
}
finalized[i] = answer;
}
i++;
}
return finalized;
}
}
Any help would be very much appreciated. Tried a bunch of things so far and no luck. Wish I'd have kept track of what I've done better so I could tell you what hasn't worked better but it's probably something obvious anyways.
Here's what I believe to be the relevant part of the logcat:
07-20 21:56:59.919 21503-21503/com.bmassey.android.jbaeapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bmassey.android.jbaeapp, PID: 21503
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bmassey.android.jbaeapp/com.bmassey.android.jbaeapp.MainActivity}: android.os.NetworkOnMainThreadException
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.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.bmassey.android.jbaeapp.WebsiteDealerino.getHtml(WebsiteDealerino.java:53)
at com.bmassey.android.jbaeapp.MainActivity.onPostCreate(MainActivity.java:36)
at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1188)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2398)
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) 
PS: The majority of this code is my awkward parsing through the HTML, and I know that most of it will not be helpful but I thought I might as well just put it all in here.

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")))

Android: java.lang.IllegalStateException: Could not execute method of the activity

Why am i getting this error??
04-27 16:09:19.823 32255-32255/com.example.myapplication D/AndroidRuntime﹕ Shutting down VM
04-27 16:09:19.823 32255-32255/com.example.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41597db8)
04-27 16:09:19.823 32255-32255/com.example.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 32255
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3830)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
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:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            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:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.myapplication.MainActivity.storeImage(MainActivity.java:139)
at com.example.myapplication.MainActivity.save_btn(MainActivity.java:150)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            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:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
What my application does is, opens up the camera application via an intent. Then loads the image/bitmao into an imageview. Whenever i click the save_btn button it gives me this error. Could anybody tell me why and give me a solution? Thank you.
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
private static final String TAG = "MyActivity";
Bitmap image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCamera();
setContentView(R.layout.activity_main);
findViewById(R.id.captureImage).bringToFront();
findViewById(R.id.saveImage).bringToFront();
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onSaveInstanceState(Bundle outState){
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
file.delete();
}
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(image);
}
}
// Reduce the amount of dynamic heap used by expanding the JPEG into a memory array that's already scaled to match the size of the destination view
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float) height / (float) reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float) width / (float) reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
public void capture_btn(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Pictures/Wiki_Camera"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="camera_wiki"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
public void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
public void save_btn(View v) {
storeImage(image);
}
}
Just guessing but it seems you store taken image only for local variable
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
While later in the code you try to store image from class variable with the same name
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
public void storeImage(Bitmap image) {
imageView.buildDrawingCache();
Bitmap bm_img = imageView.getDrawingCache();
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bm_img.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}

Cannot save files to SDcard android app

Im having a problem saving/ creating a file on my sdcard to save text to, i am trying to check if the file is created and if not create it, then write certain data to it on button click. Here is my code and error output:
This is the error output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds/ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity}: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2187)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ContextImpl.makeFilename(ContextImpl.java:2165)
at android.app.ContextImpl.getFileStreamPath(ContextImpl.java:964)
at android.content.ContextWrapper.getFileStreamPath(ContextWrapper.java:195)
at ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity.onCreate(MainActivity.java:207)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
            at android.app.ActivityThread.access$800(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5034)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
and here is the code for the file saving:
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = getFileStreamPath(SDRoot + "/output.txt");
if(!output.exists()){
try {
output.createNewFile();
Context context = getApplicationContext();
CharSequence text = "Output File Created!";
int duration = Toast.LENGTH_LONG;
Toast fileCreated = Toast.makeText(context, text, duration);
fileCreated.show();
} catch (IOException e) {
Context context = getApplicationContext();
CharSequence text = "Output File Not Created!";
int duration = Toast.LENGTH_LONG;
Toast fileNotCreated = Toast.makeText(context, text, duration);
fileNotCreated.show();
e.printStackTrace();
}
}
Button addbutton = (Button)findViewById(R.id.addMeds);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputLine = medOut.toString() + doseOut.getText() + dayout.getText() + timeOut.getText();
try {
FileOutputStream fOut = new FileOutputStream(output);
OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(fOut);
myOutputStreamWriter.append(outputLine);
myOutputStreamWriter.flush();
myOutputStreamWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
http://developer.android.com/reference/android/content/Context.html#getFileStreamPath(java.lang.String)
Parameters : name The name of the file for which you would like to get its path.
If you give a path (containing "/") instead, it will crash as you have already noticed.
Besides, this function applies only for your application private files, created with openFileOuput for instance.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
Just do like this :
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File(SDRoot + "/output.txt");

Categories

Resources