Why does this program crash when I try run it? - java

I have a basic understanding of Java, but am completely new to Android Studio. I tried making a program that increases a counter when a button is held down. I based it on two bits of code I found (one for a simple click counter and one that used onClickListener). Studio doesn't highlight any errors in the code, but the program crashes when I run it on the emulator.
Can someone tell me where I've gone wrong?
Thanks
Here is the xml code
```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="96dp"
android:onClick="onClick"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UsingOnClickInXml" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.524"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="314dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
Here is the MainActivity code
```
package com.example.clickcounter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int numberOfClicks = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View view){
TextView myText = findViewById(R.id.textView);
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent mEvent) {
if (mEvent.getAction() == MotionEvent.ACTION_DOWN)
numberOfClicks++;
myText.setText(numberOfClicks);
return false;
}
});
}
}
```
I tried making a counter that increases when a button is held down. I started with a click counter, which worked, but ran into problems when I modified the code to increase the counter when the button was held instead of clicked. The program simply crashed thereafter.
The error output was
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.clickcounter, PID: 22459
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:367)
at android.widget.TextView.setText(TextView.java:6370)
at com.example.clickcounter.MainActivity$1.onTouch(MainActivity.java:29)
at android.view.View.dispatchTouchEvent(View.java:13411)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:465)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1849)
at android.app.Activity.dispatchTouchEvent(Activity.java:3993)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:70)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:423)
at android.view.View.dispatchPointerEvent(View.java:13674)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5482)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5285)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4841)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4807)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4947)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4815)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5004)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4841)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4807)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4815)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7505)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7474)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7435)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7630)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:188)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 22459 SIG: 9

It looks like you called textView.setText with an integer instead of a string.
If you call textView.setText(1) you would get that error - you need to convert the integer to a string (e.g. with String.valueOf or similar code).
When you pass an integer, it treats that as a string resource identifier and fails with a ResourceNotFound exception when it cannot find that resource.

Related

android device showing "My application keeps stoping "

mainactivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private WebView mywebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebview=(WebView)findViewById(R.id.webView);
WebSettings webSettings=mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebview.loadUrl("file:///android_asset/myresource.html");
mywebview.setWebViewClient(new WebViewClient());
}
#Override
public void onBackPressed() {
if (mywebview.canGoBack()) {
mywebview.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="ExtraText">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<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=".MainActivity">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>12/13 23:40:42: Launching 'app' on Physical Device.
Install successfully finished in 14 s 668 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.SplashActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 25636 on device 'xiaomi-redmi_7a-2c5b9bbe0406'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Perf: Connecting to perf service.
I/FeatureParser: can't find pine.xml in assets/device_features/,it may be in /system/etc/device_features
E/Perf: Fail to get file list com.example.myapplication
E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
Fail to get file list com.example.myapplication
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 25636
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.example.myapplication:drawable/background with resource ID #0x7f07005f
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3304)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:221)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: android.content.res.Resources$NotFoundException: Drawable com.example.myapplication:drawable/background with resource ID #0x7f07005f
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/background.xml from drawable resource ID #0x7f07005f
at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:898)
at android.content.res.ResourcesImpl.originalLoadDrawable(ResourcesImpl.java:679)
at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:586)
at android.content.res.MiuiResourcesImpl.loadDrawable(MiuiResourcesImpl.java:307)
at android.content.res.Resources.getDrawableForDensity(Resources.java:920)
at android.content.res.Resources.getDrawable(Resources.java:859)
at android.content.Context.getDrawable(Context.java:696)
at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:454)
at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:144)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:411)
at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
at androidx.appcompat.app.AppCompatDelegateImpl.attachToWindow(AppCompatDelegateImpl.java:647)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureWindow(AppCompatDelegateImpl.java:623)
at androidx.appcompat.app.AppCompatDelegateImpl.onCreate(AppCompatDelegateImpl.java:350)
at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:105)
at com.example.myapplication.SplashActivity.onCreate(SplashActivity.java:11)
at android.app.Activity.performCreate(Activity.java:7893)
at android.app.Activity.performCreate(Activity.java:7880)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:221)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
E/AndroidRuntime: Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: tag requires a 'drawable' attribute or child tag defining a drawable
at android.graphics.drawable.LayerDrawable.inflateLayers(LayerDrawable.java:278)
at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:199)
at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:144)
at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1402)
at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1361)
at android.content.res.ResourcesImpl.createFromXmlForDensity(ResourcesImpl.java:1615)
at android.content.res.ResourcesImpl.loadXmlDrawable(ResourcesImpl.java:963)
at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:882)
... 30 more
I/Process: Sending signal. PID: 25636 SIG: 9
**splashactivity.java**
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
I think you have problems in your splashActivity not the main activity look for drawables that you use for your splash xml file you must import them correctly in your
res->drawable folder of your project weather they are vectors or pngs. Just try to import them in the right place.If it doesnt solve the the problem please put your splash xml file so I can help you.
Update:
Look at your splashactivity it doesnt have any content view
You must create layout for your splash activity .
Go to your project packages expand res folder then right click on layout and create a layout resource then name it as you prefere for example splash with lowercase then in your splash activity under oncreate method add:
setContentView(R.layout.splash.xml);
Put this line right after super.onCreate(savedinstancestate)

Getting Null Object reference on Edittext

I know that this question looks similar to others on SO but i have tried all the suggestions in the other similar questions and haven't had any success.
I'm getting this error:
2020-08-03 20:41:21.372 8916-8916/com.example.spacing E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.spacing, PID: 8916
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.spacing/com.example.spacing.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:159)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:675)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.spacing.MainActivity.<init>(MainActivity.java:15)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2020-08-03 20:41:21.411 8916-8916/com.example.spacing I/Process: Sending signal. PID: 8916 SIG: 9
on this code:
package com.example.spacing;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public int firstValue;
EditText first;
String firstString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first = (EditText)findViewById(R.id.firstNum);
firstString = first.getText().toString();
Button Go = (Button) findViewById(R.id.goButton);
Go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Integer.parseInt(firstString);
System.out.print(firstValue);
}
});
}
}
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/buttonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.898" />
<TextView
android:id="#+id/FirstAttribute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/spacedMaterial"
app:layout_constraintBottom_toTopOf="#+id/goButton"
app:layout_constraintEnd_toStartOf="#+id/firstNum"
app:layout_constraintHorizontal_bias="0.457"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.043" />
<EditText
android:id="#+id/firstNum"
android:layout_width="165dp"
android:layout_height="40dp"
android:ems="10"
android:hint="#string/inMM"
android:importantForAutofill="no"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="#+id/FirstAttribute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.934"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/FirstAttribute"
app:layout_constraintVertical_bias="0.476" />
<TextView
android:id="#+id/secondAttribute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/amount"
app:layout_constraintBottom_toTopOf="#+id/goButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.073"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.131" />
<EditText
android:id="#+id/secondNumber"
android:layout_width="165dp"
android:layout_height="40dp"
android:ems="10"
android:hint="#string/number"
android:importantForAutofill="no"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="#+id/secondAttribute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.934"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/secondAttribute" />
<TextView
android:id="#+id/thirdAttribute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/areaWidth"
app:layout_constraintBottom_toTopOf="#+id/goButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.068"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.218" />
<EditText
android:id="#+id/thirdNumber"
android:layout_height="40dp"
android:layout_width="165dp"
android:ems="10"
android:hint="#string/inMM"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="#+id/thirdAttribute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.934"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/thirdAttribute"
app:layout_constraintVertical_bias="0.476"
android:importantForAutofill="no" />
</androidx.constraintlayout.widget.ConstraintLayout>
Suggestions i have tried:
I have tried changing the init for the edit text to before and after on-create.
I have made sure that all ids are correct and are referencing the right thing.
And about 5 other things that i cant recall but none of them worked when i tried to build.
Any help is appreciated.
Problem is:
you are trying to initialize the "firstString" variable OUTSIDE of the click listener and as soon as the Activity is created, which means the variable will always be a null object because you did not actually write something in the EditText.
Simply initialize the String inside the ClickListener!
` package com.example.spacing;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public int firstValue;
EditText first;
String firstString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first = (EditText)findViewById(R.id.firstNum);
Button Go = (Button) findViewById(R.id.goButton);
Go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstString = first.getText().toString();
firstValue = Integer.parseInt(firstString);
System.out.print(firstValue);
}
});
}
}`

android.view.InflateException when switching to landscape mode

I am trying to make an app that involves two content mains, one being for portrait the other being for landscape, However, when I switch the orientation to landscape, the app crashes. Portrait and Landscape have different layouts, the only notable difference between the two is that landscape has one more fragment within its layout.
I want to iterate that this is my first time working with landscape mode in android studio so if I made any rookie mistakes, i'm sure you'll be forgiving.
Any input is appreciated, thanks in advance!
Settings Fragment.java
package com.example.celebquizapp;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
public class SettingsFragment extends Fragment implements View.OnClickListener {
private SharedPreferences preferences;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragment_view = inflater.inflate(R.layout.fragment_settings, container, false);
preferences = this.getActivity().getSharedPreferences("values", Context.MODE_PRIVATE);
return fragment_view;
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RadioGroup selectionOption = getActivity().findViewById(R.id.selection_option_setting);
setRadioButtonListener(selectionOption);
}
public void onClick(View v) {
RadioButton button = (RadioButton) v;
boolean checked = button.isChecked();
if (checked) {
int chosenVal = Integer.parseInt(String.valueOf(button.getText()));
Log.d("RADIOS", "Current value chosen: " + chosenVal);
preferences.edit().putInt("numofopt", chosenVal).apply();
}
}
public void setRadioButtonListener(RadioGroup radioGroup) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
radioGroup.getChildAt(i).setOnClickListener(this);
}
}
#Override
public void onStart() {
super.onStart();
// Not required to save data in preferences
// So delete on start up
preferences.edit().clear().apply();
}
}
Settings Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".SettingsFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/selectionOptionLabel"
android:textColor="#color/colorBlack"
android:textSize="20sp"
android:layout_marginTop="0dp"
android:padding="10dp"/>
<RadioGroup
android:id="#+id/selection_option_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textSize="20sp"
android:text="#string/_2"
android:layout_marginLeft="10dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:text="#string/_3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:text="#string/_4"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:text="#string/_5"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:text="#string/_6"/>
</RadioGroup>
</LinearLayout>
Error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.celebquizapp, PID: 11657
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.celebquizapp/com.example.celebquizapp.MainActivity}: android.view.InflateException: Binary XML file line #22 in com.example.celebquizapp:layout/activity_main: Binary XML file line #26 in com.example.celebquizapp:layout/content_main: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5279)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5187)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: android.view.InflateException: Binary XML file line #22 in com.example.celebquizapp:layout/activity_main: Binary XML file line #26 in com.example.celebquizapp:layout/content_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #26 in com.example.celebquizapp:layout/content_main: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getChildCount()' on a null object reference
at com.example.celebquizapp.SettingsFragment.setRadioButtonListener(SettingsFragment.java:50)
at com.example.celebquizapp.SettingsFragment.onViewCreated(SettingsFragment.java:32)
at androidx.fragment.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManagerImpl.java:1144)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:851)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1133)
at androidx.fragment.app.FragmentManagerImpl.addFragment(FragmentManagerImpl.java:1393)
at androidx.fragment.app.FragmentManagerImpl.onCreateView(FragmentManagerImpl.java:3205)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:134)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:336)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1263)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1119)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.example.celebquizapp.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:7802)
E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5279)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5187)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
RadioGroup selectionOption = getActivity().findViewById(R.id.selection_option_setting);
It should be
RadioGroup selectionOption = view.findViewById(R.id.selection_option_setting);

Why the application crashes when I add methods to run audio using MediaPlayer Class?

I've added an mp3 file to the resource "raw" directory in order to have a button that plays the audio file and another one that pauses it, but when I try to run it, it crashes
This is the MainAcitvity class file:-
package com.sefonia.mediaplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Define the Media file player with MediaPlayer Object
MediaPlayer mediaPlayer= MediaPlayer.create(MainActivity.this,R.raw.mine);
/**
* Starts playing the music file
*/
public void playButton(View view) {
mediaPlayer.start();
}
/**
* Pauses the music file
*/
public void pauseButton(View view) {
mediaPlayer.pause();
}
}
And that's the xml file associated
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="28dp"
android:onClick="playButton"
android:padding="16sp"
android:text="Play"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:onClick="pauseButton"
android:padding="16sp"
android:text="Pause"
app:layout_constraintEnd_toEndOf="#+id/button"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
That's the message printed to log:
E/ActivityThread: Exception when newActivity r=ActivityRecord{267cffd9 token=android.os.BinderProxy#34033d9e {com.sefonia.mediaplayer/com.sefonia.mediaplayer.MainActivity}} token=android.os.BinderProxy#34033d9e
D/ActivityThread: Dump mRelaunchingActivities:
Dump mActivities:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sefonia.mediaplayer, PID: 13318
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sefonia.mediaplayer/com.sefonia.mediaplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2531)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2706)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6102)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
at android.media.MediaPlayer.create(MediaPlayer.java:960)
at android.media.MediaPlayer.create(MediaPlayer.java:943)
at com.sefonia.mediaplayer.MainActivity.<init>(MainActivity.java:20)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1089)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2508)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2706) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:6102) 
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:1028) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
Application terminated.
Could anyone tell me where the problem is exactly?
Initialize the media player object in onCreate() Method , you are initializing MediaPlayer object outside on Create (). This will work because you are using MainActivty.this and Main activity is created only after onCreate() method has ran .
initializing the media player object inside the onCreate() method worked
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define the Media file player with MediaPlayer Object
mediaPlayer= MediaPlayer.create(MainActivity.this,R.raw.mine);
}

Android app unable to start activity componentinfo android.content.res.Resources$NotFound

Here's the entire logcat stack trace:
08-23 02:19:52.826 20628-20628/com.example.sham_tech.lastchance E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.sham_tech.lastchance, PID: 20628
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sham_tech.lastchance/com.example.sham_tech.lastchance.MainActivity}: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013
at android.content.res.Resources.loadDrawable(Resources.java:2152)
at android.content.res.Resources.getDrawable(Resources.java:710)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:193)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawable Manager.java:181)
at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:689)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:186)
at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java: 77)
at android.support.v7.app.AppCompatDelegateImplBase.<init> (AppCompatDelegateImplBase.java:83)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:193)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:173)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:511)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
at
com.example.sham_tech.lastchance.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)        
I cannot understand what's the problem!.
Here's the activity_main.xml
<LinearLayout
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"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView android:text="Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
/>
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginBottom="16dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="SubmitOrder"
/>
</LinearLayout>
Is there anything wrong in the code?
MainActivity.java
package com.example.sham_tech.lastchance;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
display(1);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
}
I have tried to solve it for more than 4 days and there is no result. Please help me!
The problem is that it's looking for a file named "abc_ic_ab_back_material.xml" in your res/drawable/ directory and it's not finding it. Make sure you have that file in that location.
The code you have pasted here did not have referenced the
abc_ic_ab_back_material
If you have used it in the other code, so find if you have the resource named abc_ic_ab_back_material under res/drawable/, if not found, just get one.
If you did not have used it anywhere, just clean you project and rebuild.

Categories

Resources