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)
Related
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.
My app crashes when I press a button to open another activity that contains a fragment. I am new to Android Studio and I can't seem to find any solution.
In the activity_main.xml I removed the other buttons for this question because I want to focus mainly on this monday_btn.
I researched this type of error and tried many tips but none of them seemed to work.
MainActivity.java
package com.example.dietmanagement;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Intent i = getIntent();
String current_user = i.getStringExtra("current_user");
TextView current_user_txtview = findViewById(R.id.current_user);
current_user_txtview.setText("Welcome, " + current_user);*/
Button monday = findViewById(R.id.monday_btn);
monday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent day = new Intent(MainActivity.this, DayActivity.class);
startActivity(day);
}
});
}
}
DayActivity.java
package com.example.dietmanagement;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
public class DayActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day);
FragmentTransaction fragmentTransaction;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
DayFragment dayFragment = new DayFragment();
fragmentTransaction.add(R.id.dayfragment, dayFragment);
fragmentTransaction.commit();
}
}
DayFragment.java
package com.example.dietmanagement;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DayFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_day, container, false);
return view;
}
}
fragment_day.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:background="#color/background_green"
tools:context=".DayFragment">
<TextView
android:id="#+id/day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/day" />
</FrameLayout>
activity_day.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"
android:background="#color/background_green"
tools:context=".DayActivity">
<fragment
android:id="#+id/dayfragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</fragment>
</androidx.constraintlayout.widget.ConstraintLayout>
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"
android:background="#color/background_green"
tools:context=".MainActivity">
<Button
android:id="#+id/monday_btn"
android:layout_width="140dp"
android:layout_height="86dp"
android:text="#string/monday"
android:textColor="#6FED84"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.091"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/main_title"
app:layout_constraintVertical_bias="0.082" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the error message I get:
2021-03-21 23:34:35.459 29479-29479/com.example.dietmanagement E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dietmanagement, PID: 29479
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dietmanagement/com.example.dietmanagement.DayActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
Caused by: java.lang.NullPointerException
at java.lang.VMClassLoader.findLoadedClass(Native Method)
at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.Fragment.instantiate(Fragment.java:617)
at android.app.FragmentContainer.instantiate(FragmentContainer.java:49)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3602)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:6187)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:338)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
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 androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
at com.example.dietmanagement.DayActivity.onCreate(DayActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
You're attempting to load a fragment in two different ways - directly via the layout with the <fragment> tag, which requires you to specify which Fragment you actually want to load, and as a transaction in the activity which requires a layout in which to put the fragment.
// This says - "hey Android load up a fragment for me", but you don't say which
<fragment
android:id="#+id/dayfragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</fragment>
But ...
// This says - "hey Android, shove the new "dayFragment" into the view R.id.dayFragment".
// But based on your previous XML declaration, R.id.dayFragment is itself already a
// Fragment!
FragmentTransaction fragmentTransaction;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
DayFragment dayFragment = new DayFragment();
fragmentTransaction.add(R.id.dayfragment, dayFragment);
fragmentTransaction.commit();
The easiest solution for you, based on what you've posted is to replace the <fragment> element with a FragmentContainerView and either leave the code in your activity or declare the class in the xml. Please see the documentation for examples on how to do this in both ways.
Your <fragment> element does not say what fragment it is supposed to be loading. You need to add an android:name to <fragment>, where the value of android:name is the fully-qualified class name of the fragment:
<fragment
android:id="#+id/dayfragment"
android:name="com.example.dietmanagement.DayActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</fragment>
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);
}
There's nothing fancy or complicated here. I am just looking to open a new, blank, activity from when I press on the textview. From the projects completed files, I seem to have done it as it wants me to. However, every time I click on the textview to start the intent to open the other activity, it crashes. I cannot seem to find the cause either. In a separate app I've made that send a text string from an edit text field via a button, seems to work fine and that has some other more detailed code to perform that, so I am not entirely sure where the error is arising here.
MainActivity.java
package com.example.android.miwok;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
}
public void openNumbersList(View view) {
Intent i = new Intent(this, NumbersActivity.class);
startActivity(i);
}
}
NumbersActivity.java
package com.example.android.miwok;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class NumbersActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
}
}
activity_main.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:background="#color/tan_background"
android:orientation="vertical"
tools:context="com.example.android.miwok.MainActivity">
<TextView
android:id="#+id/numbers"
style="#style/CategoryStyle"
android:background="#color/category_numbers"
android:onClick="openNumbersList"
android:text="#string/category_numbers" />
<TextView
android:id="#+id/family"
style="#style/CategoryStyle"
android:background="#color/category_family"
android:text="#string/category_family" />
<TextView
android:id="#+id/colors"
style="#style/CategoryStyle"
android:background="#color/category_colors"
android:text="#string/category_colors" />
<TextView
android:id="#+id/phrases"
style="#style/CategoryStyle"
android:background="#color/category_phrases"
android:text="#string/category_phrases" />
</LinearLayout>
In logcat there's an error showing when the app crashes:
02-20 20:10:26.762 7582-7582/com.example.android.miwok E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.miwok, PID: 7582
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.miwok/com.example.android.miwok.NumbersActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class TextView
In your xml layout for the Text view with id numbers add
android:clickable="true"
Only if this attribute is set to true the text view's onclick handler will be called
And also add height and width to all your textviews.. like this
android:height="wrap_content"
android:width="wrap_content"
This must have caused the app crash
There is a post on how to set click listeners to textviews here .
"Error inflating class TextView" means that your xml in the next activity is faulty. Try removing all the views from the 2nd activity's layout, double check the layout and then try it. If it is just the intent launch you wanna confirm, this should work.
I am mainly looking for clarification and advice on this. In the app I am working on I setup a fragment for handling some basic controls and text, and moved the necessary XML from the activities layout file into the fragments layout file, without making any changes. However now when I run the app I get a NULLPOINTEREXCEPTION and it seems to be caused at line 19 in my GameStart activty when I try to set the textView by its ID. I have not changed the ID, only moved it to the fragment layout file, so I have two questions:
1) What exactly is the reason this is happening, because something similar happened before that I resolved but I don't see the reason it was happening in the reference docs on Android Developers
2) Any advice on how to fix this
Below is the GameStart activity, LogCat with the error, and the XML files in question. Thanks in advance, I've spent 2 hours now trying to find this answer.
EDITED FILES/LOGCAT BELOW
LogCat:
12-04 13:48:06.322 826-826/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.saphiric.simproject.GameStart.<init>(GameStart.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Starting Activity (The error occurs when the app tries to start the GameStart activity):
package com.saphiric.simproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class TitleMenu extends ActionBarActivity {
public void startGame(View view){
Intent gameStart = new Intent(this, GameStart.class);
startActivity(gameStart);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
setContentView(R.layout.activity_main_menu);
}
}
Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Relative layout to handle main interaction area -->
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:background="#drawable/bg_text">
<TextView
android:id="#id/storyText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="#string/story_opening_one"
android:textColor="#color/black" />
<Button
android:id="#+id/advanceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/controlsFragment"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#drawable/button_advance"
android:onClick="advanceGame" />
<Button
android:id="#+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#id/advanceButton"
android:background="#drawable/menu_button" />
</RelativeLayout>
</RelativeLayout>
Fragment Class:
package com.saphiric.simproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Saphiric on 12/4/14.
*/
public class ControlsFragment extends Fragment {
/**
* Fragment Lifecycle Methods
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Inflates the layout resource for the fragment
return inflater.inflate(R.layout.controls_fragment, container, false);
}
#Override
public void onPause(){
}
}
GameStart activity:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity{
/**
* Necessary activity variables
*/
protected int clickCount = 0;
TextView storyText = (TextView) findViewById(R.id.storyText);
/**
* Sets up and alert dialogue builder for making decisions
* This will need to be revised during production
*/
AlertDialog.Builder decisionTime = new AlertDialog.Builder(getApplicationContext());
/**
* Handles advancing non character based conversations at the beginning
* of the story.
* If the player decides to investigate the scream, then the app loads the appropriate activity, and the same with the
* decision to leave the scene.
*/
public void advanceGame(View view){
clickCount = clickCount + 1; // Increments clickCount by 1 per click
if (clickCount == 1){
storyText.setText(R.string.story_opening_two);
} else if(clickCount == 2){
decisionTime.setTitle("Decision Time!"); // Sets the title for the decision box
decisionTime.setCancelable(false); // Sets it so that the decision can not be cancelled.
decisionTime.setPositiveButton("Investigate",new DialogInterface.OnClickListener() { // Sets up the positive button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
decisionTime.setNegativeButton("Leave the scene.",new DialogInterface.OnClickListener() { // Sets up the negative button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
}
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
}
}
GameStart Layout 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"
android:background="#drawable/bg_school_gate"
android:orientation="vertical">
<fragment
android:id="#+id/controlsFragment"
android:name="com.saphiric.simproject.ControlsFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/controls_fragment" />
</RelativeLayout>
No, you don't have any fragment here, read more on How to use fragments.
But that's not your problem it should work the way you did it.
The only problem is that you're calling findViewById in your constructor, or even before that.
findViewById only works if you have a UI, so you must do all UI initialization after setContentView in onCreate!
TextView storyText;
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
}
Also don't forget to call show() on decisionTime.
TextView storyText = (TextView) findViewById(R.id.storyText);
This should only be called after you set your contentview.
The final result should be:
TextView storyText;
And then on onCreate
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
1) The reason this is happening is that the view has not yet been instantiated at the time you are trying to get it's reference.
2) How to fix it: if you have a Fragment, then you should get a reference to it's View's in the Fragment.onCreateView() method. Then you can setup the Activity to talk to the Fragment to do whatever changes you need to the View.