I am trying to use Text-To-Speech but get the following error:
2020-07-26 22:58:51.876 15964-15964/ch.yourclick.kitt
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ch.yourclick.kitt, PID: 15964
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.String, int,
java.util.HashMap)' on a null object reference
at ch.yourclick.kitt.MainActivity.speak(MainActivity.java:61)
at ch.yourclick.kitt.fragments.GeneralFragment$1.onClick(GeneralFragment.java:59)
MainActivity.java
package ch.yourclick.kitt;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import java.util.Locale;
import ch.yourclick.kitt.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity {
public TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
// Text to speech
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) { // <-- I never get into that if statement
int result = tts.setLanguage(Locale.getDefault());
// Language is not supported
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
}
else {
Log.e("TTS", "" + status); // Returns -1
Log.e("TTS", "" + TextToSpeech.SUCCESS); // Returns 0
}
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
/**
* Speak
*/
public void speak() {
String text = "Hello";
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
/**
* Turn off
*/
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
GeneralFragment.java
package ch.yourclick.kitt.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import ch.yourclick.kitt.MainActivity;
import ch.yourclick.kitt.R;
/**
* A simple {#link Fragment} subclass.
* Use the {#link GeneralFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GeneralFragment extends Fragment {
public GeneralFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment General.
*/
// TODO: Rename and change types and number of parameters
public static GeneralFragment newInstance() {
GeneralFragment fragment = new GeneralFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_general, container, false);
Button hello = view.findViewById(R.id.hello);
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity mainActivity = new MainActivity();
mainActivity.speak();
}
});
return view;
}
}
It seems like tts returns null but why?
Consider the following two snippets from your post:
// Code found in onCreate(...) in MainActivity.java
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
// A bunch of code here
}
and
// Code found in an OnClickListener in GeneralFragment.java
MainActivity mainActivity = new MainActivity();
mainActivity.speak();
You're probably getting a NullPointerException due to the fact that tts is null when you call through to mainActivity.speak().
While your intentions were good, the reason for this not working as planned is that you're actually creating a new instance of MainActivity that hasn't gone through the appropriate lifecycle steps, meaning that onCreate(...) was never called and thus tts was never assigned... in that specific activity instance. Worth mentioning is that the "real" activity instance your fragment is running in however should have it set-up correctly.
So, what's the fastest way to get it working? Well, I'd say get the current activity, cast it to MainActivity if possible and try to call speak() on that instance instead:
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Activity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).speak();
}
}
});
Related
I have a custom viewPagerAdapter in this activity, when the first launch of the activity (When the main activity starts it with the intent) the pager displays the fragments correctly, but when I rotate the device, the recipe is got from the savedInstantState, and the adapter is started, but the fragments are not displayed and the getItem method doesn't get callled!
Here's the code for the Activity:
package com.ameer.bake.activities;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.ameer.bake.Constants;
import com.ameer.bake.fragments.IngredientsFragment;
import com.ameer.bake.fragments.StepDetailsFragment;
import com.ameer.bake.fragments.StepsFragment;
import com.ameer.bake.R;
import com.ameer.bake.models.Recipe;
import com.ameer.bake.models.Step;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
public class DetailsActivity extends AppCompatActivity implements StepsFragment.StepCallback{
private Recipe recipe;
private IngredientsFragment ingredientsFragment;
private StepsFragment stepsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState != null){
recipe = new Gson().fromJson(savedInstanceState.getString(Constants.RECIPE), Recipe.class);
setupViewPager();
} else if (getIntent().hasExtra(Constants.CURRENT_RECIPE_KEY) ) {
Gson gson = new Gson();
recipe = gson.fromJson(getIntent().getStringExtra(Constants.CURRENT_RECIPE_KEY), Recipe.class);
setTitle(recipe.getName());
setupViewPager();
}
}
#Override
public void onStepClicked(Step step) {
Intent intent = new Intent(DetailsActivity.this, StepActivity.class);
intent.putExtra(Constants.STEP_KEY, new Gson().toJson(step));
startActivity(intent);
}
private class RecipePagerAdapter extends FragmentPagerAdapter {
private static final int NUM_ITEMS = 2;
private final String[] titles = new String[]{
getString(R.string.ingredients), getString(R.string.steps)};
private RecipePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
if (ingredientsFragment == null && stepsFragment == null) {
ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setIngredients(recipe.getIngredients());
stepsFragment = new StepsFragment();
stepsFragment.setSteps(recipe.getSteps());
stepsFragment.setCallback(DetailsActivity.this);
}
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ingredientsFragment;
case 1:
return stepsFragment;
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(Constants.RECIPE, new Gson().toJson(recipe));
super.onSaveInstanceState(savedInstanceState);
}
private void setupViewPager(){
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
FragmentPagerAdapter pagerAdapter = new RecipePagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(pagerAdapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpager_tab);
viewPagerTab.setViewPager(vpPager);
}
}
Switch to a FragmentStatePagerAdapter rather than using FragmentPagerAdapter. Also use getChildFragmentManager() instead of getSupportFragmentManager()
The solution was as Pedro Varela mentioned in the comments:
"Hope this works. Add setRetainInstance(true); in onCreate of your internal fragments of the view pager "Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated""
Thanks
I have two fragments and one activity.
DataFragment passes info succesfuly to MainActivity and that's why there is no point providing you the code of it. My issue is , that bundle isn't effective on MyMapFragment which extends SupportMapFragment when I am trying to pass data from MainActivity. Of course I've searched a lot for many days but the only solutions given are for a fragment and not for SupportMapFragment which I think it's different.
MainActivity
package com.manuelpap.mapapp;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.os.Handler;
import com.google.android.gms.maps.SupportMapFragment;
import com.parse.Parse;
public class MainActivity extends AppCompatActivity {
public String mapLocation="EMPTY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
Intent intent = getIntent();
if (getIntent().getExtras() != null) {
mapLocation = intent.getExtras().getString("mapLocation");
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
MyMapFragment fragobj=new MyMapFragment();
fragobj.setArguments(bundle);
Log.d("MAPLOCATION", "----MainActivity---- " + mapLocation);
finish(); //I am using this because on DataFragment it's starting again , so I don't need multiple instances of MainActivity
}
}
public class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i){
if(i==0){
return new DataFragment();
}
else {
return new MyMapFragment();
}
}
#Override
public int getCount(){
return 2; //posa scrolls dexia (pages) theloume
}
#Override
public CharSequence getPageTitle(int position) {
if(position==0){
return "DATA";
}
else {
return "MAP";
}
}
}
}
MyMapFragment
package com.manuelpap.mapapp;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.os.Handler;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MyMapFragment extends SupportMapFragment { //kanei extend thn hdh uparxousa class gia to maps ths google alla den mpoorume na thn doume giati einai kleidomenh
public String location="EMPTY";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Handler handler=new Handler();
handler.post(new Runnable() {
#Override
public void run() {
if (getArguments() == null)
location = "------NOTHING RECIEVED------";
else
location =getArguments().getString("message");
Log.d("MAPFRAGMENTLOCATION", location);
handler.postDelayed(this, 200); // set time here to refresh textView
}
});
GoogleMap googleMap = getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(40.416775, -3.70379));
googleMap.addMarker(markerOptions);
}
}
It looks like you are finishing your main activity
//I am using this because on DataFragment it's starting again , so I don't need multiple instances of MainActivity
Your DataFragment is in the viewpager so it is supposed to start along with your map fragment. You are not starting multiple instances of main activity that I can see here.
When you call finish() on your main activity that means that the map and pager and everything goes away. Not sure what exactly your looking for but I assume you are trying to pass the location string to the map so I have tailored my answer to fit that use case.
The problem is that you are using new MyMapFragment() without the bundle in the view pager. The other logic that you have in MainActivity pertaining to the Map fragment is not going anything to the one that is displayed with the view pager. Essentially you are just creating another instance of the map fragment that is not displayed anywhere. The view pager is the class that needs the data passed to it.
I thought this link might be helpful here to explain the newInstance Method.
Creating a Fragment: constructor vs newInstance()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (getIntent().getExtras() != null) {
mapLocation = intent.getExtras().getString("mapLocation");
}
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), mapLocation));
}
public class MyAdapter extends FragmentPagerAdapter{
private String mMapLocation;
public MyAdapter(FragmentManager fm, String mapLocation) {
super(fm);
mMapLoaction = mapLocation;
}
#Override
public android.support.v4.app.Fragment getItem(int i){
if(i==0){
return new DataFragment();
}
else {
Bundle bndl = new Bundle();
if(!TextUtils.isEmpty(mapLocation))
bndl.putString("message", mapLocation);
return new MyMapFragment.newInstance(bndl);
}
}
public class MyMapFragment extends SupportMapFragment { //kanei extend thn hdh uparxousa class gia to maps ths google alla den mpoorume na thn doume giati einai kleidomenh
public String location="EMPTY";
public static MyMapFragment newInstance(Bundle bundle) {
MyMapFragment myMapFragment= new MyMapFragment ();
if (bundle != null) {
myMapFragment.setArguments(bundle);
}
return myMapFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(getArguments()!=null)
location =getArguments().getString("message");
}
So as you can see in the onCreate method i call getView on the 0th fragment in the "fragments" list. It returns null. I've tried putting a timer in the code and have it run every second and check if the view is null. And on the second tick of the timer the view is NOT null. Basically
MainActivity.java
package com.axinite.standapp;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
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.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
public class MainActivity extends AppCompatActivity {
int i = 0;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
int standUpSeconds = 4000;
List<android.support.v4.app.Fragment> fragments = new Vector<android.support.v4.app.Fragment>();
NumberPicker SUPickerH;
NumberPicker SUPickerM;
NumberPicker SUPickerS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragments.add(Fragment.instantiate(this, BlankFragment.class.getName()));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), fragments);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
final int[] ICONS = new int[] {
R.drawable.walking,
R.drawable.iris
};
for (int i=0; i < tabLayout.getTabCount(); i++)
{
tabLayout.getTabAt(i).setIcon(getDrawable(ICONS[i]));
}//endfor)
View view = ((BlankFragment) fragments.get(0)).getView();
if(view != null) {
TextView tv = (TextView) view.findViewById(R.id.glupost);
tv.setText("dasdas");
//Toast.makeText(getApplicationContext(), ((Fragment) fragments.get(0)).toString(), Toast.LENGTH_SHORT).show();
}
}
void Setup() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return "";
}
}
}
BlankFragment.java
package com.axinite.standapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BlankFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
protected View mView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mView = view;
return view;
}
// 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) {
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
The typical method for an Activity to communicate with its Fragments is as follows:
MyFragment frag = (MyFragment) getFragmentManager().findFragmentById(R.id.container_of_fragment);
frag.getMyTextView().setText("New text");
or (often preferred IMO)
MyFragment frag = (MyFragment) getFragmentManager().findFragmentByTag("fragment_tag_string_value");
frag.getMyTextView().setText("New text");
This is rendered more difficult with a ViewPager however, as the "id" of the container is the ViewPager itself, which contains multiple fragments. In addition, there isn't an in built adapter mechanism (that I'm aware of) to set tags to fragments.
There are two methods I can think of that circumvent this. First, you can use an EventBus, such as GreenRobot's EventBus, or LocalBroadcastManager from the Android API. GreenRobot's EventBus is also the recommended technique in the answer to this similar question.
An alternative would leverage the fact that a Fragment always has a reference to its host Activity, which means the Fragment could request the text from the Activity via an interface, which returns it to the Fragment:
public class MainActivity implements FragmentOne.Callbacks {
//...
#Override
public String requestTextViewString() {
return "Text to send to Fragment"
}
And inside your hypothetical FragmentOne:
public class FragmentOne extends Fragment {
private Callbacks mCallback;
private TextView mTextView;
public interface Callbacks {
String requestTextViewString();
}
#Override
public void onAttach(Activity activity) {
if (activity instanceof Callbacks) {
mCallback = (Callbacks) activity;
}
}
/*
*Later in your Fragment, when you want to get text from your MainActivity
* i.e. in onCreateView()
*/
mTextView.setText(mCallback.requestTextViewString());
Edit: Also keep in mind that attempting to access your Fragment from onCreate() in your Activity is likely to result in a NullPointerException. This diagram shows both lifecycles alongside each other. This shouldn't be a problem however, as anything required during the "set-up" lifecycle events of the Fragment can just be passed as an argument in the Fragment's newInstance() method:
public class FragmentOne extends Fragment {
private static final String KEY = "text_for_text_view_key";
public static FragmentOne newInstance(String textForTextView) {
Bundle args = new Bundle();
FragmentOne frag = new FragmentOne();
args.putString(KEY, textForTextView);
frag.setArguments(args);
return frag;
}
//And when required...
mTextView.setText(getArguments().getString(KEY));
I am trying to call a DialogFragment from my Fragment class. I have an EditText, and would like to call my DialogFragment class in the onClickListener of the EditText I have set up.
I am getting an error in the onClick with the code I have set up trying to call the DialogFragment.
I am getting an error on "show" stating "The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)" and an error on "new Instance" stating "The method newInstance() is undefined for the type MyDialogFragment"
Here's my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.fragment_profile_fragment, container, false);
setListenerOnWeight(root);
button(root);
return root;
}
public void setListenerOnWeight(View v) {
EditText Weight = (EditText) v.findViewById(R.id.Weight_up);
Weight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
weight_frag dialog = new weight_frag.newInstance();
dialog.show(getFragmentManager(), "fragmentDialog");
}
});
}
for my DialogFragment class:
package com.the.healthescort;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class weight_frag extends DialogFragment {
Context mContext;
public weight_frag() {
mContext = getActivity();
}
public static weight_frag newInstance() {
weight_frag f = new weight_frag();
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Set Wallpaper?");
alertDialogBuilder.setMessage("Are you sure?");
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", null);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
i think you should replace
import android.app.Fragment;
with
import android.support.v4.app.Fragment;
in your "my Fragment" class
and you should also provide a method with name newInstance in your dialogfragment class like below :
public static weight_frag newInstance(){
weight_frag frag = new weight_frag();
return frag;
}
please follow java naming conventions by using capital letter for the starting letter (WeightFragment)
here is my big problem:
http://www.bilder-space.de/show_img.php?img=7371f3-1333218887.jpg&size=original
and the code:
package org.madmax.sudoku;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class SudokuActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set up Click Listener for all Buttons
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
public void onClick(View v) {
switch(v.getId()) {
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
}
}
}
}
The error is:
-void is an invalid type for the variable onCLick()
Why does eclipse give me this errors?
you can use onclick inside your onCreate method like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
}
});
}
You need to bring onClick out from onCreate method. Nested method declarations are not allowed in programming.
package org.madmax.sudoku;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class SudokuActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set up Click Listener for all Buttons
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
}
}
}
You have defined onClick method inside of the onCreate method.
You can't have a method inside another method in Java. Put the onClick() after onCreate(), not inside it.