Opening activity from fragment force close error - java

So today I created tab view bar and fragments and added some image buttons to one of the fragments.
When I add android:onClick="name"on the button code and write Intent in .java file, it gives me force close error when I click on that button.
Here's my code:
fragment.xml
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnProgramiPL5x5"
android:minHeight="80dp"
android:background="#mipmap/btn_programi_pl_5x5"
android:onClick="ProgramiPowerlifting5x5"/>
fragment.java
package hr.app.liftme.liftmehr;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
/**
* A simple {#link Fragment} subclass.
*/
public class FragmentPowerlifting extends Fragment {
public FragmentPowerlifting() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_powerlifting, container, false);
}
ProgramiPowerlifting5x5.java
package hr.app.liftme.liftmehr;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_programi_powerlifting5x5);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
}
}
Error i get is this:
01-26 23:00:44.766 14491-14491/hr.app.liftme.liftmehr E/AndroidRuntime: FATAL EXCEPTION: main
Process: hr.app.liftme.liftmehr, PID: 14491
java.lang.IllegalStateException: Could not find method ProgramiPowerlifting5x5(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'btnProgramiPL5x5'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
I don't know what is the problem, when I link two activities I use this, name.class, but that didn't worked in this case so i used getActivity and it still does not work.
I would really appreciate help!
Thanks!

The problem here is:
Could not find method ProgramiPowerlifting5x5(View) in a parent or ancestor Context
The onClick attribute refers to the parent Context (as parent Activity) so the fragment's method is not triggered and not handled by this attribute.
You have to handle the click in the Activity:
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
...
// change the method's name to avoid confusion with constuctor
public void ProgramiPowerLifting(View view){
Intent intent = new Intent(this, ProgramiPowerlifting5x5.class);
startActivity(intent);
}
}
Or trigger the same method into your fragment:
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
private ProgramPowerFragment fragment;
...
public void ProgramiPowerLifting(View view){
fragment.ProgramiPowerLifting(view);
}
}
This great answer uses a callback interface which, personally, I'd suggest. Or you can easily forget the onClick xml attribute and do it dynamically with setOnClickListener().
So, let's try the easy way:
public class FragmentPowerlifting extends Fragment {
public FragmentPowerlifting() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// store the layout in a view variable
View v = inflater.inflate(R.layout.fragment_powerlifting, container, false);
// use this view ("v") to retrieve elements on the layout by its id
ImageButton imgButton = (ImageButton) v.findViewById(R.id.btnProgramiPL5x5);
// set a listener to the button
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open a new activity when onClick is triggered
Intent intent = new Intent(getActivity(), ProgramiPowerLiftingActivity.class);
startActivity(intent);
}
}
// return the inflated view to display it
return v;
}
}

Related

Android app crashes after RatingBar DialogFragment closes

The purpose of my app is to retrieve a value out of 5 from a rating bar through a custom dialog and display it in a TextView in the main activity. When I tap the button I've outlined in red in the image below, the app crashes and shuts down.
The app consists of 2 classes/activities. The main activity and the custom dialog activity.
The code for both files can be found below:
MainActivity.java:
package com.example.mealrater;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements MealRaterDialog.SaveRating {
public EditText restaurant, dish;
public TextView ratingDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
restaurant = findViewById(R.id.etRestaurant);
dish = findViewById(R.id.etDish);
RateMealButton();
}
#Override
public void finishMealRaterDialog(String rating) {
ratingDisplay = findViewById(R.id.tvRatingDisplay);
ratingDisplay.setText(rating);
}
private void RateMealButton() {
Button rate = findViewById(R.id.btnRate);
rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
MealRaterDialog mealRaterDialog = new MealRaterDialog();
mealRaterDialog.show(fm, "RateMeal");
}
});
}
}
MealRaterDialog.java:
package com.example.mealrater;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import androidx.fragment.app.DialogFragment;
public class MealRaterDialog extends DialogFragment {
String rating;
public interface SaveRating {
void finishMealRaterDialog(String rating);
}
public MealRaterDialog() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.meal_rater, container);
getDialog().setTitle("Rate your meal");
Button save = view.findViewById(R.id.btnSaveRating);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RatingBar ratingBar = view.findViewById(R.id.rbMeal);
rating = String.valueOf(ratingBar.getRating());
SaveItem(String.valueOf(rating));
}
});
return view;
}
private void SaveItem(String rating) {
MealRaterDialog.SaveRating activity = (MealRaterDialog.SaveRating) getActivity();
activity.finishMealRaterDialog(rating);
getDialog().dismiss();
}
}
I'm new to Android Studio and would also like to receive tips on how to improve this question. Thank you.
Logcat error:
2021-04-28 16:04:35.240 18144-18144/com.example.mealrater E/libc: Access denied finding property "ro.serialno"
2021-04-28 16:04:42.709 18144-18144/com.example.mealrater E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mealrater, PID: 18144
java.lang.NullPointerException: Attempt to invoke virtual method 'float android.widget.RatingBar.getRating()' on a null object reference
at com.example.mealrater.MealRaterDialog$1.onClick(MealRaterDialog.java:35)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
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:947)
There are severall fixes for this.
First of all, You should define the ratingBar widget before the onClick. Right now it is creating the variable each time you click on the button. Define it after Button save = view.findViewById(R.id.btnSaveRating); line.
Second of all, As you are using a Dialog fragment, all the logic of the click should be called on the override funtion called onViewCreated(). Not in the OnCreateView() as you are doing right now. Let me know if it works for you.
I've tried to reproduce this error and I find a solution that works for me.
You have to create the rating bar with the view (outside of the listener).
This should be your onCreateView in your MealRaterDialog.java class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.meal_rater, container);
getDialog().setTitle("Rate your meal");
Button save = view.findViewById(R.id.btnSaveRating);
RatingBar ratingBar = view.findViewById(R.id.rbMeal);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rating = String.valueOf(ratingBar.getRating());
SaveItem(String.valueOf(rating));
}
});
return view;
}
Hope it works!

I get this error when I run the app on my device [duplicate]

This question already has answers here:
I'm having problems with running the code on my device [duplicate]
(3 answers)
Closed 4 years ago.
I am currently getting these errors when running my code on a device
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 9401
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:46)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
now based on what I see here are the libraries for the code its stating in the error. Please help im a beginner
Events.java
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.FragmentManager;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events,
container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long id) {
Intent intent = new Intent(view.getContext(),
AddEvent.class);
Uri currentVehicleUri =
ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton)
getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),
AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity
context
EventContract.EventEntry.CONTENT_URI, // Provider
content URI to query
projection, // Columns to include in the
resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
Fragment Java(it says im getting an error around here:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
if (mHost != null) {
writer.print(prefix); writer.print("mHost=");
writer.println(mHost);
}
if (mParentFragment != null) {
writer.print(prefix); writer.print("mParentFragment=");
writer.println(mParentFragment);
In conclusion I'm trying to run the app but everytime I go into a certain section, in this case being Events.java being nav_events.xml layout, I keep getting the error and don't know how to fix it
Your error is found on line 46 of your Events.java file.
You're inflating a view and declaring it a ListView in Java (on line 46) when it seems to be a LinearLayout in your XML file.
Also right after that you're using getView(). You can only use that function correctly after onCreateView() has returned a View, definitely not within it.
EDIT after comment:
You haven't returned the View yet as you can't execute any code after a return statement.
Now without your layout file I can only speculate but probably replace
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
with
View rootView = (LinearLayout) inflater.inflate(R.layout.nav_events, container, false);
Then replace all occurrences of getView() in that code block with rootView.
And at the very end
return rootView;

Different behavior of android.app.Fragment and android.support.v4.app.Fragment while using backstack

I've created Activity and added a fragment to it using FragmentManeger. When i use android.app.Fragment and press the back button my application closes. When i use android.support.v4.app.Fragment and press the back button, the fragment is removed from the activity, but application is still working. I can't really understand why is that happening.
Here is the code i used:
Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(R.id.content_fragment, new Fragment1())
.addToBackStack("first")
.commit();
}
}
Fragment:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
When i simply replace import in Activity and Fragment to same classes, but in the support library, the result is different...
EDIT:
I also replaced getFragemetManeger() to getSupportFragmentMeneger() and it still works different
if you're only looking to change the back behavior, you can try overriding
onBackPressed with something like:
if(backstackCount() > 0)
{
super.onBackPressed
}
The issue occured because i used android.support.v7.app.AppCompatActivity and android.app.Fragment. I should've used android.app.Fragment with android.app.Activity or AppCompatActivity with support fragment.

Open activity on button click in NavigationDrawer

I have created project in Android Studio with Navigation Drawer Activity and I have successfully created it,On navigation drawer activity I have created 3 section, In 1st section I put Button and I want to setOnClickListener method on that button which lead to start new Activity (ex. "xyz.class") I have used code
startActivity(new Intent(this,xyz.class));
but "this" keyword is not working and gives me error.
So, I changed code like
Context c;
startActivity(new Intent(c,xyz.class));
which gives NullPointerException,
My Section1 code is
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.pratik.crm50.R;
import com.gc.materialdesign.views.ButtonFloat;
public class Dashboard extends Fragment implements View.OnClickListener {
View rootView;
Context c;
private ButtonFloat float_btn;
private Button but;
private Button btn;
Context c;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View v;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
v = inflater.inflate(R.layout.dashboard_layout,container, false);
} else {
v = super.onCreateView(inflater,container, savedInstanceState);
}
View vv=v.findViewById(R.id.button_simple);
vv.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
// Toast.makeText(c,"Float Button",Toast.LENGTH_SHORT).show();
Log.e("ssas","sasafa");
//startActivity(new Intent(c,xyz.class));
}
}
and I can get successfully log Log.e("ssas","sasafa") on above code.
So how to do this?
Fragment does not extend Context while the Intent constructor expects the first parameter to be exactly that.
The Context c variable is redundant because a Fragment saves the parent activity by default.
You need to use the activity (class that extends Context) that the fragment is attached to:
startActivity(new Intent(getActivity(), xyz.class));
You get a NullPointerException, because you´re never assining a value to Context c.
So as user3249477 also mentioned use the method getActivity() to assign a value to c like c=getActivity();
Or call it directly while starting the Intent. This would look like this: startActivity(new Intent(getActivity(),xyz.class));

tabhost inside actionbar using fragment

I have used actionbar and it is working fine. I have four fragment in the actionbar. I want to implement tabhost in one of the fragment. I have used the following code.
package com.main.udebate;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class Info extends Fragment {
public Info() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
private TabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent i = new Intent(Info.this, about.class);
View view = inflater.inflate(R.layout.info, container, false);
mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
mTabHost.setup();
TabHost.TabSpec tab = mTabHost.newTabSpec("my tab content");
tab.setIndicator("my tab content");
tab.setContent(i);
mTabHost.addTab(tab);
mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
return view;
}
}
I am getting error on Intent i = new Intent(Info.this, about.class); line as The constructor Intent(Info, Class) is undefined.
About.java
package com.main.udebate;
import android.app.Activity;
import android.os.Bundle;
public class about extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
}
Can someone pls help me to set tabhost inside fragment.
Thanks,
try to use this
Intent i = new Intent(getActivity(), about.class);
instead of this line
Intent i = new Intent(Info.this, about.class);
As Info.this does not mean any context thats why you get "The constructor Intent(Info, Class) is undefined." this error.
In fragment where you use this reference you should instead use getActivity() reference

Categories