MainActivity cannot be cast to android.app.Activity - java

I know this has been asked multiple times, and I been trying to fix it, but I really can't seem to understand what the problem is. I'm really new to Android Studio and Android Room, so if I'm honest, I barely have a clue what I'm doing. I assume the error occurs in my "MainActivity.java" class based off what the logcat tells me. This is my logcat
2020-06-15 01:33:41.885 21773-21773/com.example.hoply5 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hoply5, PID: 21773
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hoply5/com.example.hoply5.MainActivity}: java.lang.ClassCastException: com.example.hoply5.MainActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3272)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3500)
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:2049)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
Caused by: java.lang.ClassCastException: com.example.hoply5.MainActivity cannot be cast to android.app.Activity
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3500) 
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:2049) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7523) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941) 
Here is my MainActivity class
public class SecondFragment extends Fragment {
EditText editTxtName, editTxtEmail, editTxtPwd, editTextCnfPwd;
Button backBtn, registerBtn;
private UserDao userDao;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
editTxtName = view.findViewById(R.id.editName);
editTxtEmail = view.findViewById(R.id.editEmail);
editTxtPwd = view.findViewById(R.id.editPwd);
registerBtn = view.findViewById(R.id.registerBtn2);
editTextCnfPwd = view.findViewById(R.id.editCnfPwd);
backBtn = view.findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);
}
});
userDao = Room.databaseBuilder(getActivity(), UserDatabase.class, "User").build().getUserDao();
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userName = editTxtName.getText().toString().trim();
String email = editTxtEmail.getText().toString().trim();
String password = editTxtPwd.getText().toString().trim();
String passwordCnf = editTextCnfPwd.getText().toString().trim();
if(password.equals(passwordCnf)) {
User user = new User(userName,password,email);
userDao.insert(user);
Intent transitionLogin = new Intent(getActivity(), MainActivity.class);
startActivity(transitionLogin);
} else {
Toast.makeText(getActivity(), "Password is not matching", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}

Your MainActivity is Fragment,so you have to replace it

Related

I get java.lang.NullPointerException: Attempt to invoke virtual method when I save details in my app [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to enter details from EnterDetails class and view saved details in MainActivity.
public class MainActivity extends AppCompatActivity {
EditText nameBox ;
EditText sclBox;
Spinner genderMenu;
EditText ageBox;
SharedPreferences sharedPref;
TextView label ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameBox = findViewById(R.id.editText);
sclBox = findViewById(R.id.editText3);
ageBox = findViewById(R.id.editText2);
genderMenu = findViewById(R.id.spinner);
sharedPref = getSharedPreferences("mypref",Context.MODE_PRIVATE);
label = findViewById(R.id.textView);
if(isDetailsEmpty(0)){
label.setText("Enter new Details");
}else{
setDetails();
}
}
public boolean isDetailsEmpty(int i){
if(i ==0) {
if (sharedPref.getString("txtName", "").isEmpty() || sharedPref.getString("txtAge", "").isEmpty() || sharedPref.getString("txtScl", "").isEmpty()) {
return true;
} else {
return false;
}
}{
if(nameBox.getText().toString().isEmpty() || ageBox.getText().toString().isEmpty() || sclBox.getText().toString().isEmpty()){
return true;
}else{
return false;
}
}
}
public void setDetails(){
label.setText("Name : " +sharedPref.getString("txtName","Default")+"\n"+
"Age : " +sharedPref.getString("txtAge","Default")+"\n"+
"Gender : " +sharedPref.getString("optGender","Default")+"\n"+
"School : " +sharedPref.getString("txtScl","Default")+"\n");
}
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
startActivity(enterDet);
}
}
`public class EnterDetails extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
}
public void onClickSave(View v){
if(isDetailsEmpty(1)) {
Toast.makeText(EnterDetails.this,"Empty Details!", Toast.LENGTH_SHORT).show();
}else{
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("txtName", nameBox.getText().toString());
editor.putString("txtAge", ageBox.getText().toString());
editor.putString("optGender", genderMenu.getSelectedItem().toString());
editor.putString("txtScl", sclBox.getText().toString());
editor.commit();
Toast.makeText(EnterDetails.this,"Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this,MainActivity.class));
}
}
}
`
I want to enter details from EnterDetails class and view saved details in MainActivity. But I get the folloing error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.userdetails, PID: 31945
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5646) 
at android.view.View$PerformClick.run(View.java:22473) 
at android.os.Handler.handleCallback(Handler.java:761) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:156) 
at android.app.ActivityThread.main(ActivityThread.java:6517) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.userdetails.MainActivity.isDetailsEmpty(MainActivity.java:64)
at com.example.userdetails.EnterDetails.onClickSave(EnterDetails.java:20)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:5646) 
at android.view.View$PerformClick.run(View.java:22473) 
at android.os.Handler.handleCallback(Handler.java:761) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:156) 
at android.app.ActivityThread.main(ActivityThread.java:6517) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 
How to fix this? I have already extended EnterDetails to MainActivity.
Similar Question : What is a NullPointerException, and how do I fix it?
What you are doing is wrong. EnterDetails has its own layout called R.layout. enter_details, so when you set setContentView(R.layout.enter_details);, it will override the whole content so all views and layouts in MainActivity is no longer accessible. What you need to do is implement EnterDetails normally and use Intent to send data between activities.
public class EnterDetails extends AppCompatActivity {
private boolean isDetailsEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
isDetailsEmpty = getIntent().getBooleanExtra("test1", false)
}
public void onClickSave(View v){
if(isDetailsEmpty) {
...
}
}
And pass data from your MainActivity
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
enterDet.putExtra("test1", isDetailsEmpty(1))
startActivity(enterDet);
}
Finally, please do more research on how Activity works https://medium.com/#peterekeneeze/passing-data-between-activities-2d0ef122f19d

Button Click Intent crashes App

I have a problem,
I can't get my button to work
On click it should switch from MainActivity to Login
Both classes work fine without the Button,
but now, as I brought in the Button, it keeps crashing.
What am I doing wrong?
This Button, which brings me from login to Mainactivity, works just fine:
public class login extends Activity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.login);
b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
b2 = (Button)findViewById(R.id.button2);
tx1 = (TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") && ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(),"Redirecting...",Toast.LENGTH_SHORT).show();
Intent i = new Intent(login.this, MainActivity.class);
startActivity(i);
}
else{
Toast.makeText(getApplicationContext(), "Fehlerhafte Eingabe",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
Button code
StrgS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
Toast.makeText(getApplicationContext(), "Goodbye", Toast.LENGTH_LONG).show();
Intent j = new Intent(MainActivity.this, login.class);
startActivity(j);
}
}
});
}
}
Error Code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cris.zeiterfassungv2, PID: 10555
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cris.zeiterfassungv2/com.example.cris.zeiterfassungv2.MainActivity}: android.view.InflateException: Binary XML file line #0: Can't convert value at index 6 to dimension: type=0x12
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: android.view.InflateException: Binary XML file line #0: Can't convert value at index 6 to dimension: type=0x12
Caused by: java.lang.UnsupportedOperationException: Can't convert value at index 6 to dimension: type=0x12
at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:730)
at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:7797)
at android.widget.LinearLayout$LayoutParams.<init>(LinearLayout.java:1976)
at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1874)
at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1872)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
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 android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.cris.zeiterfassungv2.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Thank you

Error passing custom object between activities through intent

I tried passing this simple object from MainActivity to Main2Activity by implementing Serializable on the CustomObject. It results in Error. I referred the similar stack overflow questions. Nothing helped.
public class MainActivity extends Activity {
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,Main2Activity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("data",new CustomObject());
//I tried i.putExtra(bundle);
i.putExtra("data",new CustomObject());
startActivity(i);
Log.d(TAG, "onCreate: ");
}
public class CustomObject implements Serializable{
public int i = 0;
public int j = 9;
CustomObject(){
}
}
}
Main2Activity
public class Main2Activity extends Activity {
String TAG = "Main2Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent i = getIntent();
MainActivity.CustomObject c = (MainActivity.CustomObject)i.getSerializableExtra("data");
Log.d(TAG, "onCreate: "+c.i+" "+c.j);
}
}
Error Message:
07-30 13:58:58.352 26489-26489/? E/AndroidRuntime: FATAL EXCEPTION:
main
Process: gct.venkatesh.com.scrshtrebuilt, PID: 26489
java.lang.RuntimeException: Unable to start activity
ComponentInfo{gct.venkatesh.com.scrshtrebuilt/gct.venkatesh.com.scrshtrebuilt.MainActivity}:
java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object (name =
gct.venkatesh.com.scrshtrebuilt.MainActivity$CustomObject)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object (name =
gct.venkatesh.com.scrshtrebuilt.MainActivity$CustomObject)
at android.os.Parcel.writeSerializable(Parcel.java:1527)
at android.os.Parcel.writeValue(Parcel.java:1475)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:724)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1417)
at android.os.Bundle.writeToParcel(Bundle.java:1157)
at android.os.Parcel.writeBundle(Parcel.java:764)
at android.content.Intent.writeToParcel(Intent.java:8703)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3082)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520)
at android.app.Activity.startActivityForResult(Activity.java:4229)
at android.app.Activity.startActivityForResult(Activity.java:4187)
at android.app.Activity.startActivity(Activity.java:4526)
at android.app.Activity.startActivity(Activity.java:4494)
at gct.venkatesh.com.scrshtrebuilt.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6684)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6186) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) 
Caused by: java.io.NotSerializableException:
gct.venkatesh.com.scrshtrebuilt.MainActivity
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1224)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at android.os.Parcel.writeSerializable(Parcel.java:1522)
at android.os.Parcel.writeValue(Parcel.java:1475) 
at android.os.Parcel.writeArrayMapInternal(Parcel.java:724) 
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1417) 
at android.os.Bundle.writeToParcel(Bundle.java:1157) 
at android.os.Parcel.writeBundle(Parcel.java:764) 
at android.content.Intent.writeToParcel(Intent.java:8703) 
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3082) 
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520) 
at android.app.Activity.startActivityForResult(Activity.java:4229) 
at android.app.Activity.startActivityForResult(Activity.java:4187) 
at android.app.Activity.startActivity(Activity.java:4526) 
at android.app.Activity.startActivity(Activity.java:4494) 
at gct.venkatesh.com.scrshtrebuilt.MainActivity.onCreate(MainActivity.java:21) 
at android.app.Activity.performCreate(Activity.java:6684) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6186) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
by this error in logs:
java.io.NotSerializableException: gct.venkatesh.com.scrshtrebuilt.MainActivity at
MainActivity is not Serializable, i think platform wants MainActivity to be serializable because CustomObject is inner class in MainActivity ,
try to define your CustomObject in a separate local class (separate file)

app crashes when creating view (android.view.InflateException)

public class ChildrensList extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.childrens_list,container,false);
//return rootView;
ImageButton pigsButton = (ImageButton) rootView.findViewById(R.id.pigsButton);
ImageButton jackButton = (ImageButton) rootView.findViewById(R.id.jacksButton);
ImageButton hansgretButton = (ImageButton) rootView.findViewById(R.id.hansgretButton);
ImageButton mermadButton = (ImageButton) rootView.findViewById(R.id.mermaidButton);
ImageButton rapButton = (ImageButton) rootView.findViewById(R.id.rapunzalButton);
ImageButton redRidButton = (ImageButton) rootView.findViewById(R.id.ridingButton);
ImageButton threeBearsButton = (ImageButton) rootView.findViewById(R.id.bearsButton);
ImageButton ugduckButton = (ImageButton) rootView.findViewById(R.id.duckButton);
final MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.xlophone);
pigsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(),pigs_story.class);
mp.start();
startActivity(i);
}
});
jackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), jack_beanstalk.class);
mp.start();
startActivity(i);
}
});
hansgretButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), hansel_and_gretal.class);
mp.start();
startActivity(i);
}
});
mermadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), mermaid.class);
mp.start();
startActivity(i);
}
});
rapButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), rapunzal.class);
mp.start();
startActivity(i);
}
});
redRidButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), RedRidingHood.class);
mp.start();
startActivity(i);
}
});
threeBearsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), ThreeBears.class);
mp.start();
startActivity(i);
}
});
ugduckButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChildrensList.this.getActivity(), UglyDuckling.class);
mp.start();
startActivity(i);
}
});
return rootView; //return rootview
}
}
I am having some errors appear in the console and struggling with how to resolve them, one of them is a fatal out of memory exception but there is a long list! could someone shed some light on this and help to rid the errors
04-19 18:47:29.392 19101-19101/com.j2d.com.bedtimestories E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.j2d.com.bedtimestories, PID: 19101
android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.widget.ScrollView
at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
at com.j2d.com.bedtimestories.ChildrensList.onCreateView(ChildrensList.java:25)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.widget.ScrollView
at android.view.LayoutInflater.createView(LayoutInflater.java:657)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:706)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:774)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.j2d.com.bedtimestories.ChildrensList.onCreateView(ChildrensList.java:25) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:631)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58) 
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:706) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:774) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:498) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.j2d.com.bedtimestories.ChildrensList.onCreateView(ChildrensList.java:25) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 22075212 byte allocation with 16777216 free bytes and 17MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2228)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:4211)
at android.content.res.Resources.loadDrawable(Resources.java:4085)
at android.content.res.Resources.loadDrawable(Resources.java:3935)
at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
at android.view.View.<init>(View.java:4225)
at android.view.ViewGroup.<init>(ViewGroup.java:589)
at android.widget.FrameLayout.<init>(FrameLayout.java:97)
at android.widget.ScrollView.<init>(ScrollView.java:347)
at android.widget.ScrollView.<init>(ScrollView.java:343)
at android.widget.ScrollView.<init>(ScrollView.java:339)
at java.lang.reflect.Constructor.newInstance(Native Method) 
at android.view.LayoutInflater.createView(LayoutInflater.java:631) 
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58) 
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:706) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:774) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:498) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.j2d.com.bedtimestories.ChildrensList.onCreateView(ChildrensList.java:25) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
The key part of the error you posted is this:
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 22075212 byte allocation with 16777216 free bytes and 17MB until OOM
[...]
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2228)
[...]
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.j2d.com.bedtimestories.ChildrensList.onCreateView(ChildrensList.java:25) 
[...]
This says your app ran out of memory. It ran out of memory while trying to load an image, which it did when your ChildrensList class, in the onCreateView() method, called .inflate().
As someone else noted in a comment on your question, it is likely that you have very large image file(s) in your app. You should scale the images to an appropriate size to avoid this issue.
The Android documentation has an article discussing image sizes.

How to display passed intent data in a TextView - NullPointerException error

I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)

Categories

Resources