Fragment Activity cannot be cast to app.Activity. - android

Okay i keep getting this error when i have a button click launch another Fragment..
07-30 20:54:05.950: ERROR/AndroidRuntime(7816): Caused by: java.lang.ClassCastException: com.fttech.gameIT.shopping_details_fragment cannot be cast to android.app.Activity
07-30 20:54:05.950: ERROR/AndroidRuntime(7816): at android.app.Instrumentation.newActivity(Instrumentation.java:1022)
07-30 20:54:05.950: ERROR/AndroidRuntime(7816): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1663)
Here is what i am trying to do, when the button findIt is clicked from this activity..
public class shoppingClass extends FragmentActivity{
Button findIT;
EditText game;
String item = null;
WebView browser;
RadioGroup site;
RadioGroup type;
String url;
String console;
shopping_details_fragment shopping;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping);
findIT = (Button)findViewById(R.id.findIT);
shop = (EditText)findViewById(R.id.item);
type = (RadioGroup)findViewById(R.id.console);
site = (RadioGroup)findViewById(R.id.shopping_group);
final Intent d = new Intent(this, shopping_details_fragment.class);
findIT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getUserPreference();
shopping.loadUrl(url);
startActivity(d);
}
});
}
I am launching another this Fragment into the view...
public class shopping_details_fragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
//Return the view for our WebView
return(inflater.inflate(R.id.browserFrag,container, false));
}
public void loadUrl(String url){
((WebView)getView().findViewById(R.id.browser)).loadUrl(url);
}
}
This uses the browser i have set up in the same xml that the first activitiy is set up in to launch a webbrowser and look up a URL in a fragment i have set..
Its getting the browser in loadUrl() from a webview layout i created and inflating it into the fragment.
But i keep getting the error above.

Fragment and Activity aren't directly related like that, you can't just cast between them. Use the getActivity() method on the fragment instead, to return its activity.

Related

Changing TextView Attributes from button onClick not working

So I have a xml fragment called fragment_home. Which has 2 buttons and a textview inside cardview. One of the button (tries to) change the value in the textview. On both the buttons I have an onClick. The tools:context for the fragment is set to .MainActivity. I also have a extend Fragment class which is associated with the xml fragment.
Whenever I try to call anything to change the TextView attributes such as setText,setTextSize I get an exception: java.lang.IllegalStateException: Could not execute method for android:onClick
If I do not have setText, setTextSize, the onClick works.
MainActivity:
public class MainActivity extends AppCompatActivity {
private int textViewData;
private TextView inputDataTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputDataTextView= (TextView)findViewById(R.id.focus_counter);
}
//onClick For One of the buttons
public void increaseNumber(View view) {
textViewData++;
// Crashes When I have This. Doesn't crash when I comment this.
inputDataTextView.setTextSize(60);
// Crashes When I have this. Doesn't crash when I comment this.
inputDataTextView.setText(String.valueOf(textViewData);
Toast.makeText(this, "TextView Value = " + textViewData, Toast.LENGTH_SHORT).show();
}
I feel like It's something to do with my fragment and activity. But I just do not know what the problem is. As soon as I call anything related to the textview in the onClick the app crashes. And the textview in the xml is set to 0 initially and when I increase the number, it increases, so thats working.
Thanks for the help!!
HomeFragment:
public class HomeFragment extends Fragment {
private int textViewData;
private static final String TAG = "MyActivity";
private TextView inputDataTextView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
inputDataTextView = view.findViewById(R.id.focus_counter);
return view;
}
public void increaseNumber(View view) {
textViewData++;
//inputDataTextView.setText("t");
inputDataTextView.setText(String.valueOf(inputViewData));
//Toast.makeText(getContext(), "Focus Vale = " + inputViewData, Toast.LENGTH_SHORT).show();
}
}
Your inputDataTextView is null because its in fragment but your instantiating it from MainActivity, which is wrong. Move both the onClick methods and view to the fragment java code.
Edit copy theses codes from MainActivity to HomeFragment before onCreateView:
private int textViewData;
private TextView inputDataTextView;
Then these inside onCreateView before the return statement:
inputDataTextView=
(TextView)findViewById(R.id.focus_counter);
Then these method inside your fragment:
public void increaseNumber(View view) {
textViewData++;
inputDataTextView.setTextSize(60);
inputDataTextView.setText(String.valueOf(textViewData);
Toast.makeText(this, "TextView Value = " + textViewData, Toast.LENGTH_SHORT).show();
}
It should work now

How to load Fragment using AlertDialog?

I'm trying to load fragment after alert Dialog response but when i attempt to load logcat shows "IllegalStateException: Fragment not attached to Activity". Generally IllegalStateException comes when you try to perform work after the Fragment is no longer attached to the Activity. but in my case every thing is fine i don't understand why fragment is not attached to an activity.
this is my MainActivity:
using this class i call DilogCreate which extends DialogFragment.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DilogCreate(view.getContext(),R.string.tilte,R.string.no,R.string.yes);
}
});
}
this is my DilogCreate class:
on the basis of dialog response decide fragment can be loaded or not if dialog response yes i call another activity name Second.java under this class i try to load fragment.
public class DilogCreate extends DialogFragment {
AlertDialog alertDialog;
public DilogCreate(final Context context, int tilte, int no, int yes) {
AlertDialog.Builder mAlertDilog = new AlertDialog.Builder(context);
mAlertDilog.setNegativeButton(yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(context, second.class);
startActivity(intent);
}
});
alertDialog = mAlertDilog.create();
alertDialog.show();
}
}
this is my my Second.java class:
this class is appear because of dialog response and under this class i tried to load fragment.
public class Second extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadFragment);
fragmentManager=getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
Myfragment myfragment=new Myfragment();
fragmentTransaction.replace(R.id.cont,myfragment);
fragmentTransaction.commit();
}
}
this is MyFragment.java extends Fragment :
public class Myfragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag,container,false);
}
}
Logcat status:
java.lang.IllegalStateException: Fragment DilogCreate{8aea1d4} not attached to Activity
please help me guys i have no idea why this error is coming.
new DilogCreate(view.getContext(),R.string.tilte,R.string.no,R.string.yes);
pass MainActivity.this instead of view.getContext().You need to pass activity context here.
fragment is load on the activity and one activity switch to another by using base reference that's why i need to call startActivity() method using base Activity refrence.
so i change startActivit() method in the DilogCreate class like this:
Intent intent=new Intent(context,Second.class);
context.startActivity(intent);//make sure context is the refrence of the base context

How to get values of edittext which is in fragment on button click which is in activity?

signup screen with of two different modules driver and customer
Hi everyone I am working in android from past one year but now I am creating an app in which am using fragments instead of activity even after serching from so many sites and blogs am unable to implement what I want.
My requirement is as you see on the image two radio button one for customer and one for driver so when user click on any one of options then signup screen appears which is on fragment and one button is there at bottom which is on activity so I want how to get all edittext value on button click so that i can send these values to the server. My main problem is getting the values of edittext fields on button click.
So any help will be appriciated.
thanks in advance
Try like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
this.initViews(rootView);
selectProfessionsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
whta_you_want_on_button_click();
}
});
}
private void initViews(View view) {
//define your edittext like FirstNameEditText = (EditText) view.findViewById(R.id.FirstNameEditText);
}
now define the whta_you_want_on_button_click() method
in your activity, put below code in your button's click event.
try {
Fragment rg = getSupportFragmentManager().findFragmentByTag("YourFragmentTag");
if (rg != null) {
EditText et = (EditText) ((YourFragment) rg).getView().findViewById(R.id.edittext);
String etValue = et.getText().toString();
}
} catch (Exception e) {
}
Your context will change from getApplicationContext() to getActivity.getApplicationContext() when you are referencing a fragment instead of an activity
You have to create your edittext in this fashion
While assigning the layout you need to assign in this way.
View view = inflater.inflate(R.layout.fragmentlayout,container,false);
And while assigning edittext you need to take it as below
EditText edt = (EditText) view.findViewById(R.id.yourid);
String str = edt.getText().toString();
So on button click you can get the edittext string easily from onClick method with above code.
You can use static keyword make all edittext static so you will get all edittext values in activity on button click.
in your fragment suppose MyFragment.java
public class MyFragment extends Fragment{
View rootView;
public static EditText edt;
public MyFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
init();
return rootView;
}
protected void init(){
edt = (EditText) rootView.findViewById(R.id.edt);
}
}
in your activity suppose MainActivity.java
public class MainActivity extends Activity{
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewByid(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = MyFragment.edt.getText().toString().trim();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
});
}
}

Android: Button OnClick not working in SherlockFragment

I've tab activity in which i want to use a button, but when i click on button, it force closes the app. Can you please tell me what is going on, i am new to Android.
public class HomeActivity extends SherlockFragment {
private Button bt;
private Context con;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_layout, container, false);
bt = (Button)rootView.findViewById(R.id.btn);
bt.setOnClickListener(new View.OnClickListener(){
#Override public void onClick(View v)
{
Toast.makeText(con, "hello", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
when i click on button, it force closes the app
Because con object of Context is null. which is used for showing Toast message in Button onClick method.
Do it as:
Toast.makeText(v.getContext(), "hello", Toast.LENGTH_LONG).show();
And initialize con object by calling getActivity() in onCreateView as:
con=getActivity();
If you can avoid that, don't keep a reference to the context; instead of the
private Context con;
get the current Activity in the code, so use
Toast.makeText(getActivity(), "hello", Toast.LENGTH_LONG).show();
Btw, this seems to be the cause of your crash, as Context is null.

Exception when showing a dialog after orientation change

I have an activity and a fragment inside it.inside fragment, there is a button, and on click of button a dialog shows.
Everything works, until user do a orientation change and click button after it.
IllegalStateException(cannot perform this action after onsaveinstancestate) occurs when user clicks button after orientation change. I'm using android support framework.
Anybody have any idea regarfing this?
Activity Code
public void openMoreDialog(String shareData, String link) {
DialogFragment dialog = new MoreDialog(shareData, link);
dialog.show(getSupportFragmentManager(), "MoreDialog");
}
Fragment Code
public void onAttach(Activity activity) {
super.onAttach(activity);
mControl = (ActivityControl)activity;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ImageButton moreButton = (ImageButton)v.findViewById(R.id.moreButton);
moreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mControl.openMoreDialog(shareData, link);
}
});
return rootView;
}
FragmentDialog code
public class MoreDialog extends DialogFragment {
private String mShareData;
private String mLink;
public MoreDialog(String shareData, String link){
mShareData = shareData;
mLink = link;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.more_dialog, null);
Button openBtn = (Button)dialogView.findViewById(R.id.openBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openLink(mLink);
}
});
Button shareBtn = (Button)dialogView.findViewById(R.id.shareBtn);
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
shareNews(mShareData);
}
});
builder.setView(dialogView);
return builder.create();
}
private void openLink(String link){
}
private void shareNews(String data){
}
}
Helpful link & solution how to:
https://stackoverflow.com/a/17413324/619673 and btw, constructor in fragment must be empty! Documentation:
http://developer.android.com/reference/android/app/Fragment.html
public Fragment ()
Added in API level 11
Default constructor.
Every fragment must have an empty constructor, so
it can be instantiated when restoring its activity's state. It is
strongly recommended that subclasses do not have other constructors
with parameters, since these constructors will not be called when the
fragment is re-instantiated; instead, arguments can be supplied by the
caller with setArguments(Bundle) and later retrieved by the Fragment
with getArguments().
Applications should generally not implement a constructor. The first
place application code an run where the fragment is ready to be used
is in onAttach(Activity), the point where the fragment is actually
associated with its activity. Some applications may also want to
implement onInflate(Activity, AttributeSet, Bundle) to retrieve
attributes from a layout resource, though should take care here
because this happens for the fragment is attached to its activity.

Categories

Resources