I am learning how to make a simple camera app on Android Studio at the moment. When I click the 'camera' button, the app crashes. I can't seem to pinpoint what is causing the app to crash. In logcat, it states that 'startActivityForResult' might be the cause...but it looks normal to me.
I made sure that the camera button id matches the java file. Any help is greatly appreciated!
Here is my code so far.
Main_Activity.java:
public class MainActivity extends AppCompatActivity {
Button cam_button;
ImageView imageView;
static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cam_button = (Button) findViewById(R.id.cam_button);
imageView = (ImageView) findViewById(R.id.imageV);
cam_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFile();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
});
}
private File getFile() {
File folder = new File("sdcard/camera_app");
if(folder.exists())
folder.mkdir();
File imageFile = new File("cameraImage.jpg");
return imageFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String path = "sdcard/camera_app/cameraImage.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}}
activity_main.xml:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera"
android:id="#+id/cam_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageV"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
This is what I copied from the logcat:
06-24 21:30:45.769 21481-21481/com.sugarcoder.cameraapp
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sugarcoder.cameraapp, PID: 21481
java.lang.SecurityException: Permission Denial: starting Intent {
act=android.media.action.IMAGE_CAPTURE flg=0x3
cmp=com.motorola.camera/.Camera clip={text/uri-list
U:file:///cameraImage.jpg} (has extras) } from ProcessRecord{b5b85f2
21481:com.sugarcoder.cameraapp/u0a121} (pid=21481, uid=10121) with
revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at
android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2696)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1574)
at android.app.Activity.startActivityForResult(Activity.java:3921)
at
android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:3881)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
at
com.sugarcoder.cameraapp.MainActivity$1.onClick(MainActivity.java:40)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
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)
Solved! I found out the issue is that I had to actually go into the app info for the app on the phone, and turn on the permission. Thanks for all your help, folks! :)
Related
i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.
content_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/beer_btn"
android:id="#+id/button"
android:layout_below="#+id/color"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickFindBeer"/>
JAVA FILE
public class FindBeerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
}
public void onClickFindBeer(View view){
TextView brands=(TextView)findViewById(R.id.brands);
Spinner color=(Spinner)findViewById(R.id.color);
String beerType=String.valueOf(color.getSelectedItem());
brands.setText(beerType);
}
Hello there. While running this code The Button action is not working..
The app crashes. I cant find any error. I got this code from Head First android development tutorial.
Somebody please find the error and help me
here is the error log
05-26 09:34:30.929 19451-19451/com.example.devan.layouttut E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.devan.layouttut, PID: 19451
java.lang.IllegalStateException: Could not find method onClickFindBeer(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Your question is not very ideal for SO and there are a lot of tutorials here and there regarding how to work with button click in Android.
But anyway, here's how you can implement the onClick on a button.
In your FindBeerActivity remove the onClickFindBeer function.
public class FindBeerActivity extends Activity {
// Get the Button variable first
private Button myButton;
private TextView brands;
private Spinner color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
myButton = (Button) findViewById(R.id.my_button);
brands = (TextView) findViewById(R.id.brands);
color = (Spinner) findViewById(R.id.color);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String beerType=String.valueOf(color.getSelectedItem());
brands.setText(beerType);
Toast.makeText(this,"Clicked", Toast.LENGTH_LONG).show();
}
});
}
}
From your content_main.xml remove the onClick="onClickFindBeer" too.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/beer_btn"
android:id="#+id/my_button"
android:layout_below="#+id/color"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
There are of course other ways to implement onClick of a button, but I think this is the simplest.
I have made updates to this Llama or Duck game (a recreation of an already-existing game) and the app very inconsistently closes out due to an outOfMemory error. I have made multiple attempts to clear up memory such as using addFlags from Intent and researching different solutions and yet the errors keep coming. By the way, this is one of the two screens (essentially identical) that will be constantly recreated throughout the game as the user is playing. The goal is for the user to select which animal is being shown on the screen, and if correct they will keep playing. Any help is appreciated, thank you.
package com.example.ryan.llamaorduck;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class DuckScreen extends AppCompatActivity {
boolean isLlamaScreen = false; //false because this is the Duck screen
int duck_score;
Intent intent;
int screen; // variable used just for finding the next random screen
int pic; //not currently implemented
SharedPreferences pref; //used for storing score
SharedPreferences.Editor editor;
Timer timer; //used to change window if time runs out
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duck_screen);
pref = getApplicationContext().getSharedPreferences("MY_PREF",MODE_PRIVATE);
editor=pref.edit();
duck_score=pref.getInt("tempDuckScore",0);
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
timer.cancel();
//below are my attempts to clear up memory space to make
//the app perform better.
intent = new Intent(DuckScreen.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
};
timer.schedule(timerTask,2000);
}
// user clicked on the llama button.
//method implementation decides if they are correct and either ends the
//game or moves them onto the next random page.
public void llamaClick(View view){
timer.cancel();
if (isLlamaScreen){
Random r = new Random();
screen = r.nextInt(2);
if (screen == 1){ //DUCK
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,DuckScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,LlamaScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
//user clicked on the button indicating that they think the animal is a
//duck. Same idea as method before, testing other button.
public void duckClick(View view){
timer.cancel();
if (!isLlamaScreen){
Random r = new Random();
screen = r.nextInt(2);
if (screen == 1){ //DUCK
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,DuckScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,LlamaScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}else{
int tempDuckScore = duck_score;
editor.putInt("tempDuckScore",tempDuckScore);
intent = new Intent(DuckScreen.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
public int getDuckScore(){
return duck_score;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ryan.llamaorduck.DuckScreen">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:src="#drawable/duck"
android:scaleType="centerCrop"
android:id="#+id/duck"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/duck"
android:orientation="vertical"
>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Duck"
android:textSize="40sp"
android:textColor="#ffffff"
android:onClick="duckClick"
/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Llama"
android:textSize="40sp"
android:textColor="#ffffff"
android:onClick="llamaClick"
/>
</RadioGroup>
</RelativeLayout>
ERROR MSG:
04-05 11:57:59.451 6438-6438/com.example.ryan.llamaorduck E/dalvikvm-heap: Out of memory on a 8748016-byte allocation.
04-05 11:57:59.601 6438-6438/com.example.ryan.llamaorduck E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)
at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
at android.content.res.Resources.loadDrawable(Resources.java:1940)
at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
at android.widget.ImageView.<init>(ImageView.java:119)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:57)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:53)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:972)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1031)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:668)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.ryan.llamaorduck.DuckScreen.onCreate(DuckScreen.java:28)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Try setting
android:largeHeap="true"
Inside of the <application> tag of your manifest; this will launch the application with more memory allocated to the heap.
Android Docs.
Note: Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.
If you are gettin an OOM, you have a fundamental issue with your code - this is simply a bandaid.
I have created a dialog class that i would like to use in several other classes and depending in what class they should display different info. I have no problem displaying the dialog itself with working button and an already set text from the xml. But when i try to set my own text with setText the app crashes and give me java.lang.NullPointerException. What can be the problem ?
Here is my custom dialog class
public class CustomDialogInfoClass extends Dialog implements View.OnClickListener {
Button ok;
TextView myTextView;
Typeface myFont;
public CustomDialogInfoClass(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog_not_demo);
CustomDialogInfoClass c = new CustomDialogInfoClass(getContext());
ok = (Button)findViewById(R.id.btnOk);
myTextView = (TextView) c.findViewById(R.id.textViewDialog);
ok.setOnClickListener(this);
myFont = Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
ok.setTypeface(myFont);
myTextView.setTypeface(myFont);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnOk:
dismiss();
break;
default:
}
dismiss();
}
}
And here is my main where I try to call it;
public class MainActivity extends ActionBarActivity {
TextView myTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomDialogInfoClass dialogInfo = new CustomDialogInfoClass(this);
myTextview = (TextView) findViewById(R.id.textViewDialog);
myTextview.setText("Lorem ipsum dolor sit amet"); <----Null.pointer error
dialogInfo.show();
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:orientation="vertical"
android:background="#drawable/diabox"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textViewDialog"
android:layout_margin="15dp"
android:textColor="#android:color/white"
android:text="Test text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ok"
android:id="#+id/btnOk"
android:layout_gravity="center_horizontal" />
and logcat if that helps?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.name.appname/com.example.name.appname.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2221)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.access$800(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5064)
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:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.name.appnamne.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:6084)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.access$800(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5064)
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:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
at dalvik.system.NativeStart.main(Native Method)
you shouldn't access your text view from activity
in your dialog you have this constructor
public CustomDialogInfoClass(Context context) {
super(context);
}
so make this one too:
public CustomDialogInfoClass(Context context,String text) {
CustomDialogInfoClass(context);
this.text = text;
}
and make a String field in your dialog class
String text;
and setup your TextView in the dialog
myTextView = (TextView) c.findViewById(R.id.textViewDialog);
myTextView.setText(text);
and in your activity pass your text here:
CustomDialogInfoClass c = new CustomDialogInfoClass(getContext(), "MY TEXT");
You need to set the value of the TextView from inside your dialog during onCreate method.
To pass parameters to the dialog the proper way would be to have a static method in you Dialog class that return a new instance of the Object.
This method can accept paramaters and put them in a Bundle. Now you can set this bundle as argument to the created Dialog
public static YourDialog getInstance(String par1, int par2) {
YourDialog dialog = new YourDialog()
Bundle bundle = new Bundle();
bundle.putString(TAG, par1);
bundle.putInt(TAG2, par2);
dialog.setArguments(bundle);
return dialog;
}
At this point in the OnCreate method of your dialog you can get the Bundle using getArguments() using the tag you provided before and set your TextView
Once you have done in your MainActivity get an Instance of the dialog and call show() to show it
Hope it helps
Right now I have two activities, activity_bustracking and activity_main
When the button in the main activity is pressed it is supposed to move to the bustracking activity; however, right now it when I click the button the application crashes with the error:
05-28 16:34:32.680 26130-26130/com.example.robertloggia.test1 D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
05-28 16:34:32.770 26130-26130/com.example.robertloggia.test1 D/AndroidRuntime﹕ Shutting down VM
05-28 16:34:32.770 26130-26130/com.example.robertloggia.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.robertloggia.test1, PID: 26130
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4562)
at com.example.robertloggia.test1.MainActivity$1.onClick(MainActivity.java:67)
at android.view.View.performClick(View.java:5162)
at android.view.View$PerformClick.run(View.java:20873)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
My MainActivity.class looks like:
package com.example.robertloggia.test1;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener{
//GPS Specific variables
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
boolean gps_enabled, network_enabled;
Spinner routeChoice;
Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
routeChoice = (Spinner) findViewById(R.id.route_choices);
btnSubmit = (Button) findViewById(R.id.btn_submit);
txtLat = (TextView) findViewById(R.id.textView1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//get location and make sure it is enabled
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Toast.makeText(MainActivity.this, "Please enable GPS", Toast.LENGTH_LONG).show();
}
addListenerOnButton();
}
public void addListenerOnButton() {
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this,
// "OnClickListener : " +
// "\nSpinner 1 : " + String.valueOf(routeChoice.getSelectedItem()),
// Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, BusTrackingActivity.class);
startActivity(intent);
}
});
}
/*
* METHODS FOR GETTING LOCATION
*/
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textView1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude", "enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
}
My BusTrackingActivity.class looks like:
package com.example.robertloggia.test1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
/**
* Created by RobertLoggia on 5/28/15.
*/
public class BusTrackingActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bustracking);
}
}
My activity_main.xml:
<ImageView
android:layout_width="330dp"
android:layout_height="200.5dp"
android:layout_marginTop="110dp"
android:id="#+id/imageView"
android:src="#drawable/ripta_logo"
android:layout_gravity="center_horizontal"
android:contentDescription="#string/logo" />
<Spinner
android:layout_width="290dp"
android:layout_height="50dp"
android:id="#+id/route_choices"
android:entries="#array/route_array"
android:prompt="#string/route_prompt"
android:layout_gravity="center_vertical"
android:layout_below="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit_text"
android:id="#+id/btn_submit"
android:layout_gravity="center_vertical"
android:layout_alignBottom="#+id/route_choices"
android:layout_toRightOf="#id/route_choices"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please make sure GPS is enabled"
android:id="#+id/textView1"
android:layout_below="#+id/route_choices"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
activity_bustracking.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
And my android manifest looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.robertloggia.test1" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".BusTrackingActivity" >
</activity>
</application>
</manifest>
The problem is that you never assign context to this.
However, there is no reason to save off a Context in an Activity, just use MainActivity.this instead of context:
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this,
// "OnClickListener : " +
// "\nSpinner 1 : " + String.valueOf(routeChoice.getSelectedItem()),
// Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, BusTrackingActivity.class);
startActivity(intent);
}
When you are starting the new intent in this line:
Intent intent = new Intent(context, BusTrackingActivity.class);
The context object has not been initiated yet. You declared it earlier:
protected Context context;
Inside your onCreate() method, use this code:
context = this;
context in MainActivity is null.Either initialize it or use MainActivity.this in place of context.
Add the line of code from the 67th line in the MainActivity, as this is the line with the error.
However without this, I am guessing something went wrong with the button listener.
This being said, try removing all of this:
public void addListenerOnButton() {
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, BusTrackingActivity.class);
startActivity(intent);
}
});
}
Listeners are better put in the method they are used, or in this case on create. This can be done by putting this line of code:
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, BusTrackingActivity.class);
startActivity(intent);
}
});
Really though, if this doesn't work I just need to like of code at the error. If you click the first blue thing in the logcat (the rest will be grey), I can help more.
this could be because of using card view in first activity or that activity on which your app got crashed while running.
used this code to implement card view in dependencies
implementation 'androidx.cardview:cardview:1.0.0'