I'm trying to follow the video series on YouTube by "The New Boston".
I'm getting an error when trying to display a variable on a toast.
Heres' what I did..
First off, I created a textView..
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/CountView"
android:text="Number Value is 0"
/>
Then,
public class MainActivity extends ActionBarActivity {
int Counter;
TextView countView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Counter = 0;
countView= (TextView)findViewById(R.id.CountView);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void Button1Click(View view) {
Counter+=1;
Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
countView.setText(String.valueOf(Counter));
}
It says that the program has stopped working. LogCat Log ->
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3601)
... 11 more
Caused by: java.lang.NullPointerException
at com.BreadApplications.program1.MainActivity.Button1Click(MainActivity.java:36)
... 14 more
I just started learning Android.. Any help?
Try this:
Toast.makeText(this, ""+Counter, Toast.LENGTH_SHORT).show();//auto type conversion really convinent
You pass integer value in the toast parameter; that is the error. You have to remember that you just pass String value in the Toast parameter so make the Integer value into String and then show this value by using Toast. See this example:
public void Button1Click(View v){
Counter+=1;
Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
//convering integer value to String
Toast.makeText(this, Counter+"", Toast.LENGTH_SHORT).show();
}
Change to
Toast.makeText(this, String.valueOf(Counter), Toast.LENGTH_SHORT).show();
Counter is a int value ( should be named according to java naming conventions. c should be small not ins caps).
It looks for resource with the id if not found you get ResourceNotFoundException. There is one that takes int which is a resource id.
What you want is the one that takes CharacterSequence. If you look at the docs the second param is a CharacterSequence. So use String.valueOf(intvlaue)
public static Toast makeText (Context context, CharSequence text, int duration)
Added in API level 1
Make a standard toast that just contains a text view.
Parameters
context The context to use. Usually your Application or Activity object.
text The text to show. Can be formatted text.
duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG
Edit:
To the Edited post
The views belong to the fragment. So you initialize views in onCreateView of Fragment using rootView.findViewById
Or if you set fragment_main.xmlto activity get rid of the if block and the fragment related code.
Your tutorial seems to be outdated. Follow
NullPointerException accessing views in onCreate()
Edit 2:
Get rid of android:onClick="Button1Click" in fragment_main.xml for button
Remove
public void Button1Click(View view) {
Counter+=1;
Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
countView.setText(String.valueOf(Counter));
}
Then in Fragment
public static class PlaceholderFragment extends Fragment {
TextView countView;
int Countter;
public PlaceholderFragment() {
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView countView = (TextView)(TrootView.findViewById(R.id.CountView);
Button button = (TextView)(TrootView.findViewById(R.id.buttonid);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Counter+=1;
Toast.makeText(getActivity(), "Added 1", Toast.LENGTH_SHORT).show();
countView.setText(String.valueOf(Counter));
}
});
return rootView; }
}
}
The method makeText of the class Toast is overloaded.
makeText(Context context, int resId, int duration)
makeText(Context context, CharSequence text, int duration)
You are using the first method because you are passing a int value as the second parameter. This method is searching for a resource id with the value of your counter and a resource not found exception is being thrown.
the solution is to make a cast to the integer value to String to invoke the correct makeTest method.
Toast.makeText(this, Integer.toString(Counter), Toast.LENGTH_SHORT).show();
You are using makeText (Context context, int resId, int duration) of Toast.In this function the resId should be the resource id of the string resource to use,But you pass just simple integer number.So it gives runtimeerror
So,Try below code
public void Button1Click(View view) {
Counter+=1;
Toast.makeText(YourActivity.this, "Added 1", Toast.LENGTH_SHORT).show();
//countView.setText(""+Counter);
Toast.makeText(YourActivity.this, String.valueOf(Counter), Toast.LENGTH_SHORT).show();
}
Related
Hi I am new to android if someone is able to help me to fix this issue it will be much appreciated. Now I am trying to go back to the previous view or the root view do anyone know how to go back to the previous view from static context(I am not sure static context is the correct way to say it do feel free to correct me if I am wrong)?
I have already tried creating FragmentManager the reason I use this is because the application I am trying to create used Fragment.
FragmentManager fragmentManager =
((FragmentActivity)mContext).getSupportFragmentManager();
fragmentManager.popBackStack();
`
public class SomeView1 extends View implements View.OnTouchListener {
public SomeView1(Context c) {
super(c);
mContext = c;
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
}
public SomeView1(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public void foodPortionCal() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Output");
builder.setMessage("Message here");
builder.setCancelable(true);
builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
sqLiteHelper.insertDataFood(GlobalVariable.mealTypeF, String.format("%.2f", totalProteinPer) + '%', String.format("%.2f", totalGrainsPer) + '%', String.format("%.2f", totalVegetablePer) + '%', String.format("%.2f", totalFruitPer) + '%', String.format("%.2f", totalDairyPer) + '%', GlobalVariable.dataF);
Toast.makeText(mContext, "Added", Toast.LENGTH_SHORT).show();
//this is where I want to set the feature to remove the view/static context?
FragmentManager fragmentManager = ((FragmentActivity)mContext).getSupportFragmentManager();
fragmentManager.popBackStack();
dialog.dismiss();
}
});
builder.show();
}
}
//Before going the code will move to someview1 we will be in a fragment class called FoodFragment and this is how it look like
public class Food_Cal extends Fragment {
private void mealTypeSelection()
{
//this is how I call the come view activity
getActivity().setContentView(new SomeView1(view.getContext()));
}
}
// here is a link to how this app was constructed Android: Free Cropping of Image
the only biggest different and the things that is giving me issue is that my app uses fragment and the code the the reference doesn't
The result wanted to get is either it will move to next view with fragment or go all the way back to the root view with fragment. the result I am getting are either the app keep crashing and not able to go back to root view then the app crash this is the error message I am getting
2019-04-27 00:35:36.599 624-624/apd.bii.diabetesappv1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: apd.bii.diabetesappv1, PID: 624
java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to android.support.v4.app.FragmentActivity
at apd.bii.diabetesappv1.FoodCalculation.SomeView1$1.onClick(SomeView1.java:437)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:173)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6894)
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:857)
This is a simple method used for adding fragment into your FragmentManger so it can be visible. All you need to do is pass in the fragment you want to add on the screen.
public void addScreen(Fragment fragment) {
getSupportManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
screensOnTheStack++;
}
And when you want to pop that fragment out of the stack and go to your parent view is
while (screensOnTheStack > 0) {
fragments.popBackStackImmediate();
}
Or simply by defining your fragment TAG for determining the root(parent) fragment, like
private static final String BACK_STACK_ROOT_TAG = "root_fragment";
then
// Pop off everything up to and including the current tab
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack(BACK_STACK_ROOT_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// Add the new tab fragment
fragmentManager.beginTransaction()
.replace(R.id.container, TabFragment.newInstance())
.addToBackStack(BACK_STACK_ROOT_TAG)
.commit();
Now, for the part you said
The result wanted to get is either it will move to next view with fragment or go all the way back to the root view with fragment.
you can put your own condition as to when you would like to go to the fragment you want to go or either go to your parent view instead.
I'm creating an app with one Mainactivity and two class. It contains Listview adapter to show list of name with images and details. when click upon any image ...Alert Dialog Box will pop up and from option ,i want user could able to call or send email.
Earlier I used the code for Mainactivity class and it pretty much works but with ListviewAdapter it crashes.
Here is my Class
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context,
List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Set the results into ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
final String email = worldpopulationlist.get(position).getRank().toString();
final String phone = worldpopulationlist.get(position).getCountry().toString();
// Listen for ListView Item Click
final View finalView = view;
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
CharSequence options[] = new CharSequence[]{"Email", "Call"};
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
mContext.startActivity(Intent.createChooser(intent, ""));
}
if(i == 1){
Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phone));
// callIntent.setData(Uri.parse("tel:"+uri));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(callIntent);
}
}
});
builder.show();
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
and error log is
Process: com.nepalpolice.test, PID: 30475
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:1123)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2309)
at android.content.res.Resources.getLayout(Resources.java:939)
at android.view.LayoutInflater.inflate(LayoutInflater.java:395)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:988)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:964)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:981)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:1005)
at com.nepalpolice.test.ListViewAdapter$1.onClick(ListViewAdapter.java:125)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5018)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Please help.
Thanks in advance.
Android has its normal classes, like AlertDialog, and then it has support versions of some of those classes, one being AlertDialog. This is to provide backwards compatibility with older Android versions that may not have these classes natively. However it can get confusing sometimes.
The tutorial you linked is using an Activity and the normal AlertDialog. However, you are using an Activity and the support AlertDialog. This won't work. AlertDialog depends on a theme or style to know what it should make itself look like. Since you're using a normal Activity, the support AlertDialog is unable to infer what it should look like because Activity doesn't use support package themes.
There are a few things you can do to fix this.
The simplest way to fix this would be to just change from using the support AlertDialog to using the native one. Delete import android.support.v7.app.AlertDialog; from your Adapter class and then reimport the AlertDialog, making sure you don't import the support version again.
The second simplest way would be to follow this answer and add a specific AppCompat theme for your AlertDialog. However, this won't fix any future issues you may run into by mixing AppCompat and normal classes.
The most involved (but also most compatible) way of fixing this is to convert to using AppCompatActivity. You'll have to change your Activity to extend AppCompatActivity instead, and also change your theme (in styles.xml) to have a parent of Theme.AppCompat.Light (remove .Light if you want a dark theme).
This question already has answers here:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
(12 answers)
Closed 8 years ago.
I'm trying to create my own custom AlertDialog in a DialogFragment for a simple alarm clock application, and the code for the onCreateDialog method is below.
public class CreateAlarmSetting extends DialogFragment implements View.OnClickListener, AlertDialog.OnClickListener, TimePicker.OnTimeChangedListener, NumberPicker.OnValueChangeListener {
/*
the isEdit variable is set to true when an existing alarm time is clicked, this will add the
"delete" button to the dialog, to possibly delete the item from the listview
*/
private boolean isEdit = false;
public static final String ISEDIT_PARAM = "isEdit";
public static final String ALARMSETTING_PARAM = "AlarmSetting";
public AlarmSetting alarmSetting;
private TimePicker timePicker;
private NumberPicker numberPicker;
//private Button cancelButton, createButton, deleteButton;
//View of the dialog layout that will be inflated
private View main;
private OnFragmentInteractionListener mListener;
public CreateAlarmSetting() {
}
/*
Below are a few of the Fragment lifecycle methods
*/
public void setArguments(Bundle bundle) {
isEdit = bundle.getBoolean(ISEDIT_PARAM);
alarmSetting = (AlarmSetting) bundle.get(ALARMSETTING_PARAM);
}
#Override
public void onCreate(Bundle savedInstanceState) {
getActivity().requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
/*
Not doing anything yet, because findViewById() doesn't work at this point in the lifecycle
*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: check if this is to edit a current alarmSetting and add the save button and delete button
main = inflater.inflate(R.layout.fragment_create_alarm_setting, null);
//Initialize views and their listeners
timePicker = (TimePicker) main.findViewById(R.id.alarm_fragment_dialog_timepicker);
numberPicker = (NumberPicker) main.findViewById(R.id.alarm_fragment_dialog_numberpicker);
// cancelButton = (Button) main.findViewById(R.id.alarm_fragment_dialog_cancel_button);
// createButton = (Button) main.findViewById(R.id.alarm_fragment_dialog_create_button);
timePicker.setOnTimeChangedListener(this);
numberPicker.setOnValueChangedListener(this);
//cancelButton.setOnClickListener(this);
//createButton.setOnClickListener(this);
numberPicker.setMaxValue(45);
numberPicker.setMinValue(0);
//create display based on given parameters
/*
if (isEdit) {
// ViewGroup parent= (ViewGroup) main.findViewById(R.id.alarm_fragment_dialog_button_container);
deleteButton= (Button) main.findViewById(R.id.alarm_fragment_dialog_delete_button);
deleteButton.setText("Delete");
deleteButton.getLayoutParams().height= LinearLayout.LayoutParams.WRAP_CONTENT;
deleteButton.getLayoutParams().width= LinearLayout.LayoutParams.WRAP_CONTENT;
deleteButton.setOnClickListener(this);
createButton.setText("Save");
//TODO: Set Display Settings to current alarm settings, includes having cancel, delete, save buttons
timePicker.setCurrentHour(alarmSetting.getHours());
timePicker.setCurrentMinute(alarmSetting.getMinutes());
//Replace create button with the save add the delete button
ViewGroup parent= (ViewGroup) main.findViewById(R.id.alarm_fragment_dialog_button_container);
ViewGroup v=(ViewGroup) edit.findViewById(R.id.miscellaneous_items_container);
//v.removeView(edit.findViewById(R.id.alarm_fragment_dialog_delete_button));
parent.addView(edit.findViewById(R.id.alarm_fragment_dialog_delete_button), 1);
//Replace create button with save button
parent = (ViewGroup) createButton.getParent();
int index = parent.indexOfChild(createButton);
parent.removeView(createButton);
parent.addView(parent.findViewById(R.id.alarm_fragment_dialog_save_button), index);
}*/
return main;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
if (main == null) {
main = getActivity().getLayoutInflater().inflate(R.layout.fragment_create_alarm_setting, null);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(main);
builder.setNegativeButton("Cancel", this);
builder.setPositiveButton("Create", this);
builder.setTitle("Create a new Alarm Setting");
AlertDialog alertDialog=builder.create();
//show or create?
return alertDialog;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/*
Below are listeners for the actions in the dialog
*/
#Override
public void onClick(DialogInterface dialogInterface, int id) {
switch (id) {
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEUTRAL:
case DialogInterface.BUTTON_POSITIVE:
}
}
#Override
public void onValueChange(NumberPicker picker, int val, int num) {
//Do something
}
#Override
public void onTimeChanged(TimePicker picker, int hours, int minutes) {
if (alarmSetting != null) {
alarmSetting.setHours(hours);
alarmSetting.setMinutes(minutes);
} else alarmSetting = new AlarmSetting(hours, minutes, false);
}
#Override
public void onClick(View v) {
//do stuff for each button
switch (v.getId()) {
}
}
When I run this code in the emulator, I receive an exception saying
01-22 20:32:39.489 1883-1883/com.stanfordude.ryan.snooze E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:215)
at com.android.internal.app.AlertController.installContent(AlertController.java:234)
at android.app.AlertDialog.onCreate(AlertDialog.java:336)
at android.app.Dialog.dispatchOnCreate(Dialog.java:351)
at android.app.Dialog.show(Dialog.java:256)
at android.app.DialogFragment.onStart(DialogFragment.java:490)
at android.app.Fragment.performStart(Fragment.java:1570)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:863)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.BackStackRecord.run(BackStackRecord.java:635)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
How do I fix this?
Btw, sorry for my messy code and comments, I'm new to java
Its not the code as I can see from the error, its the requestWindowsFeature or something you have called before setContentView on the top. You should call the request before setting the contentView like this :
super.onCreate(savedInstanceState);
// Hiding title bar using code
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Hiding status bar using code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Hers is my code
public static class DetailFragment extends Fragment {
private String forecastData;
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG ="#SunshineApp";
public DetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
//receive forecast data from the ForeCast Fragment
Intent intent=getActivity().getIntent();
forecastData=intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v(LOG_TAG,"data is "+forecastData);
TextView textView=(TextView)rootView.findViewById(R.id.detail_text);
textView.setText(forecastData);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_detailfragment,menu);
MenuItem menuItem=menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
ShareActionProvider mShareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent to this ShareActionProvider. You can update this at any time,
// like when the user selects a new piece of data they might like to share.
if (mShareActionProvider!= null ) {
mShareActionProvider.setShareIntent(createShareIntent());
}
else
{
Log.v(LOG_TAG,"Share Action Provider is null");
}
}
public Intent createShareIntent()
{
Log.v(LOG_TAG,"data is "+forecastData);
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,forecastData+DetailFragment.FORECAST_SHARE_HASHTAG);
Log.v(LOG_TAG,"data is "+forecastData);
return intent;
}
I am absolutely sure the intent is fired correctly because i can share with other apps and it works ,It's clear if you see the logs below
01-04 18:36:02.370 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in optionMenu method data is null
01-04 18:36:02.380 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in create intent data is null
01-04 18:36:02.380 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in create intent data is null
01-04 18:36:02.650 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in view method data is Wed, Jan 7 - Clear - 27/24
Why is this , i thought OnCreate() view method was called before OnCreateOptionsMenu()
?what do i do to rectify this?
Here's an idea:
According to your logs, the outputs are FIRST displayed from the onCreateOptionsMenu() method and only the last one is from the onCreateView(). That would mean that onCreateOptionsMenu() is called before onCreateView which would explain why everything is null.
Try moving setHasOptionsMenu(true) somewhere else, maybe in the constructor That should make sure that onCreateOptionsMenu() is called after onCreate and onCreateView. Try it.
imho you should move your code from onCreateView() to onActvivityCreated().
onCreateView is meant to return the view.
onActivityCreated means that the associated activity has completed its method onCreate() and is set up.
I am quite new to Java and Android programming, and just working on my 3rd App - however I am encountering a Problem which I am not able to solve (I already tried and researched for days).
I have a list of Elements in a LinearLayout inside a Fragment - the Elements have a OnLongClickListener attached, with a popup showing up when the User long-presses the Element. That works fine. However, one of the Buttons in the Popup is "Edit", and when a user presses this Button, I want to start another Activity with Editing Options for this Element.
So there comes my Problem: when I want to start the new Activity with an Intent, I get following Error:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3370)
at android.app.Activity.startActivityForResult(Activity.java:3331)
at android.app.Activity.startActivity(Activity.java:3566)
at android.app.Activity.startActivity(Activity.java:3534)
at at.fekle.zipmanager.start.startzipinfo(start.java:299)
at at.fekle.zipmanager.start$2.onLongClick(start.java:277)
at android.view.View.performLongClick(View.java:4247)
at android.view.View$CheckForLongPress.run(View.java:17341)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
But, if i start the same Activity with the same Intent from a simple Button defined in the Layout, the Activity Starts fine without any Errors... weird, isn't it?
So, does anyone have an Idea how I can solve this problem?
Here are some extractions from my code:
The Creation of the Elements with the OnLongClickListener:
ScrollView parent = (ScrollView) maininflater.inflate(R.layout.start_ziplist_fragment_superwrapper, null, false);
inf = maininflater;
LinearLayout ll = (LinearLayout) maininflater.inflate(R.layout.start_ziplist_fragment_wrapper, parent, false);
for (Integer i = 0; i < count; i++) {
ArrayList<String> data = new DB(cont).getAllZips().get(i);
View custom = maininflater.inflate(R.layout.start_ziplist_fragment_inner, ll, false);
TextView tv = (TextView) custom.findViewById(R.id.ziplist_name);
TextView tv2 = (TextView) custom.findViewById(R.id.ziplist_text);
tv.setText(data.get(2));
tv2.setText(data.get(1));
Integer id = Integer.valueOf(data.get(0));
custom.setId(id);
custom.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Integer id = view.getId();
startzipinfo(id);
return true;
}
});
ll.addView(custom);
}
parent.addView(ll);
The void which starts the Activity:
public void startzipinfo(Integer id){
Intent in = new Intent(getApplicationContext(), zipinfo.class);
startActivity(in);
}
I'm looking forward to your Answers,
Felix
EDIT: This is the Activity which is about to be started:
package at.fekle.zipmanager;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by felix on 27.06.13.
*/
public class zipinfo extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zipinfo);
}
}
Try to use YourActivityName.this instead of getApplicationContext() :
public void startzipinfo(Integer id){
Intent in = new Intent(YourActivityName.this, zipinfo.class);
startActivity(in);
}
Check whether your new intent class is mentioned in android manifest file if it does not exists then type:<activity name=".YourClassName>
</activity>
I just solved the problem!
I had to start the activity from the parent Fragment (passed to the method by the FragmentManager) - now everything works like a charm :)
custom.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Integer id = view.getId();
id = 2;
Intent intent = new Intent(cont, zipinfo.class);
fragment.startActivity(intent);
return true;
}
});
Thanks for all answers!
Cheers,
Felix