Fragment returning null from intent - java

So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"
Class sending the intent
public class Intennt extends ActionBarActivity {
Button bt1,bt2,bt3,bt4;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intennt);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
startActivity(i);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,
ItemDetailFragment.ACTION_2);
startActivity(i);
}
});
}
Fragment receiving the intent and extras
public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem =
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(getActivity(), "id is null!",
Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(getActivity(), "Aloha from button 1!",
Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_3) {
Log.i("TAG", "Hello from button 3");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_4) {
Log.i("TAG", "Hello from button 4");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
return rootView;
}
}

To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :
FragmentClass fragment = new FragmentClass();
getFragmentManager()
.beginTransaction()
.replace(R.id.your_fragment_view, fragment)
.commit();
You can proceed to every action right in the current activity (as it stays the main activity).

public class Questions extends DialogFragment {
private static Button Submit;
public int count = 0;
public interface DialogListener {
void onQuestionsFinish(ArrayList<xmlQuestion> l);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Submit = (Button) rootView.findViewById(R.id.SubmitButton);
Submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
for(int i = 0; i<questionList.size(); i++)
{
questionList.get(i).setAnswer();
}
DialogListener activity = (DialogListener) getActivity();
activity.onQuestionsFinish(questionList);
Questions.this.dismiss();
}
});
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
yInch = metrics.ydpi;
pixHeight = metrics.heightPixels;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point(); display.getSize(size);
screenWidth=size.x; screenHeight=size.y;
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
BodyLayout.setLayoutParams(bodyParams);
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.height=screenHeight; wmlp.width=screenWidth;
getDialog().getWindow().setAttributes(wmlp);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.dimAmount=0.4f;
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getDialog().setCanceledOnTouchOutside(true);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
}
public Questions()
{
}
}
You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...
Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");

Related

How can i pass data from custom dialog box to Fragment in android studio using java?

I am new to android studio and Java. I have create custom dialog box with input textbox. I want to pass data from custom dialog to fragment layout. How can I achieve that ?
I saw this post but didn't get it. Please help me out !
Passing a data from Dialog to Fragment in android
Edited
Here's my code >>
public class IncomeFragment extends Fragment{
TextView title, textRsTotal;
Dialog dialog;
int total = 0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
title = view.findViewById(R.id.totalIncomeTitle);
Button button = view.findViewById(R.id.addIncomeBtn);
textRsTotal = view.findViewById(R.id.totalExpenseTitle);
dialog = new Dialog(getActivity());
if (getActivity() != null) {
if (!CheckInternet.isNetworkAvailable(getActivity())) {
//show no internet connection !
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.setContentView(R.layout.income_custom_dialog);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
RadioGroup radioGroup = dialog.findViewById(R.id.radioGroup);
Button buttonAdd = dialog.findViewById(R.id.addBtn);
TextInputEditText editText = dialog.findViewById(R.id.editText);
radioGroup.clearCheck();
radioGroup.animate();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(checkedId);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(getActivity(), "Please select your income type", Toast.LENGTH_SHORT).show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String getIncome = editText.getText().toString();
Toast.makeText(getActivity(), radioButton.getText() + " is selected & total is Rs."+ total, Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
}
});
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
// Inflate the layout for this fragment
return view;
}
}
Ok, try this :
public class IncomeFragment extends Fragment {
TextView title, textRsTotal;
Dialog dialog;
int total = 0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
title = view.findViewById(R.id.totalIncomeTitle);
Button button = view.findViewById(R.id.addIncomeBtn);
textRsTotal = view.findViewById(R.id.totalExpenseTitle);
dialog = new Dialog(getActivity());
if (getActivity() != null) {
if (!CheckInternet.isNetworkAvailable(getActivity())) {
//show no internet connection !
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(new MyCallback() {
#Override
public void setText(String text) {
textRsTotal.setText(text);
}
});
}
});
super.onViewCreated(view, savedInstanceState);
}
private void showDialog(MyCallback myCallback) {
dialog.setContentView(R.layout.income_custom_dialog);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
RadioGroup radioGroup = dialog.findViewById(R.id.radioGroup);
Button buttonAdd = dialog.findViewById(R.id.addBtn);
TextInputEditText editText = dialog.findViewById(R.id.editText);
radioGroup.clearCheck();
radioGroup.animate();
radioGroup.setOnCheckedChangeListener((radioGroup1, checkedId) -> {
RadioButton radioButton = (RadioButton) radioGroup1.findViewById(checkedId);
});
buttonAdd.setOnClickListener(view1 -> {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(getActivity(), "Please select your income type", Toast.LENGTH_SHORT).show();
} else {
RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId);
String getIncome = editText.getText().toString();
myCallback.setText(getIncome);
Toast.makeText(getActivity(), radioButton.getText() + " is selected & total is Rs." + total, Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_income, container, false);
return view;
}
public interface MyCallback {
void setText(String text);
}
}
There are more than one method to achieve that, the one mentioned in the url you provided is suggesting to use a simple callback to forward event and data back to the calling fragment. So the pieces you are needing are all there:
Write a callback interface: public interface Callback1{ public void onInteraction(String thingToCommunicateBack); }
In your fragment: and while building the instance of your dialog, pass an instance you've built of Callback1 to that dialog like this Callback1 mCallback = new Callback1() { public void onInteraction(String thingToCommunicateBack) { /*TODO receive data, handle and update layout*/ }; (the whole fragment could be that instance using the keyword this if you decide to implement the interface there instead, like this
class Fragment1 extends Fragment implements Callback1 and implement its method within fragment's class after the keyword override)
In your Dialog class: when the interaction (click) that should trigger the event and send data back happens, invoke callback's method like this: mCallback1.onInteraction("text from your EditText to pass")
Now, you passed some data from custom dialog back to a fragment.

NextActivity onCreate() is skipped

I am creating a social app and the users can upload an image and then write a caption on the next screen right after. My problem is that the activity where the user creates the caption, gets completely skipped over and goes to the profile page. The image goes to the firebase storage but I can't write a caption.
07-10 15:23:21.150 30970-31309/tabian.com.hash E/ImageLoader: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
java.lang.UnsupportedOperationException: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromOtherSource(BaseImageDownloader.java:280)
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:99)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.downloadImage(LoadAndDisplayImageTask.java:291)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryCacheImageOnDisk(LoadAndDisplayImageTask.java:274)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:230)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:136)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
GalleryFragment.Java
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: Started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the gallery screen.");
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
if (isTaskRoot()) {
Intent intent = new Intent(GalleryFragment.this.getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
GalleryFragment.this.startActivity(intent);
} else {
Intent intent = new Intent(GalleryFragment.this.getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
GalleryFragment.this.startActivity(intent);
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
}
});
init();
return view;
}
NextActivity.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = (EditText) findViewById(R.id.caption) ;
setupFirebaseAuth();
ImageView backArrow = (ImageView) findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the activity");
finish();
}
});
TextView share = (TextView) findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
ProfileActivity.Java :
public class ProfileActivity extends AppCompatActivity implements
ProfileFragment.OnGridImageSelectedListener ,
ViewPostFragment.OnCommentThreadSelectedListener,
ViewProfileFragment.OnGridImageSelectedListener{
private static final String TAG = "ProfileActivity";
#Override
public void onCommentThreadSelectedListener(Photo photo) {
Log.d(TAG, "onCommentThreadSelectedListener: selected a comment thread");
ViewCommentsFragment fragment = new ViewCommentsFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_comments_fragment));
transaction.commit();
}
#Override
public void onGridImageSelected(Photo photo, int activityNumber) {
Log.d(TAG, "onGridImageSelected: selected an image gridview: " + photo.toString());
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
args.putInt(getString(R.string.activity_number), activityNumber);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_post_fragment));
transaction.commit();
}
private static final int ACTIVITY_NUM = 4;
private static final int NUM_GRID_COLUMNS = 3;
private Context mContext = ProfileActivity.this;
private ProgressBar mProgressBar;
private ImageView profilePhoto;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d(TAG, "onCreate: started.");
init();
}

Progress Dialog does not appear

I have a fragment that, when is pressed a button should show a Progress Dialog and execute a method that contains an AsyncTask but when I press the button, the Progess Dialog does not appear on the screen but the async task is executed. This is the code of the fragment
public class ParcheggiaFragment extends Fragment {
private Button button;
ProgressDialog progressDialog1;
SharedPreferences prefs;
HttpGetNoleggio httpGetNoleggio;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View layout = inflater.inflate(R.layout.fragment_parcheggia, container, false);
button = (Button) layout.findViewById(R.id.button);
prefs = this.getActivity().getSharedPreferences(Keys.SHARED_PREFERENCES, Context.MODE_PRIVATE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog1.show();
int a = checkNoleggioCompletato();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_principale, new ResultFragment());
fragmentTransaction.commit();
}
});
return layout;
}
private int checkNoleggioCompletato() {
final int id = prefs.getInt(Keys.ID_UTENTE, -1);
Integer[] noleggio;
int idNoleggio = -1;
try {
String str = "here i put the url that i have to use" + id;
URL url = new URL(str);
noleggio = httpGetNoleggio.execute(url).get();
idNoleggio = noleggio[0];
int idBici = noleggio[1];
int noleggioResult = idNoleggio;
} catch (MalformedURLException | ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return idNoleggio;
}
#Override
public void onStart() {
progressDialog1 = new ProgressDialog(this.getActivity());
progressDialog1.setIndeterminate(true);
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
httpGetNoleggio = new HttpGetNoleggio(this.getActivity());
}
#Override
public void onResume() {
super.onResume();
}
}
The code seems correct and I can't understand why the ProgressDialog does not appear.
HttpNoleggio is another class that extends AsyncTask and implements the doInBackground method
As per your code you are displaying the progress bar in ParcheggiaFragment and then replacing this fragment with ResultFragment. As ResultFragment replaced ParcheggiaFragment so that progress bar is not displaying. Just comment the following code:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_principale, new ResultFragment());
fragmentTransaction.commit();
Then, progressbar will be visible.

How to send data from DialogFragment to DialogFragment?

I have a problem with sending data from fragment to fragment. I have DialogFragment named fmonday, it is Viewpager's fragment.
I call other DialogFragment, named AlertDFragment to add some data to my fragment. I can read the data from spinner, it's working good.
Now I need to send one variable, type string, from AlertDFragment to fmonday.
Here is the code of fmonday:
public class fmonday extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor> {
DB db;
Button button12;
DialogFragment dlg1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fmonday, container, false);
button12 = (Button) rootView.findViewById(R.id.button12);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dlg1.show(getFragmentManager(), "dlg1");
}
});
return rootView;
}
And code of AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
getDialog().dismiss();
}
});
return adb.create();
}
I can't find the way to send this string1 variable to my fmonday DialogFragment, because simple intent doesn't work with non-activity things. Also read some advices about bundle, but couldn't find out how to work with it.
Thanks
UPDATE
fmonday:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dlg1 = new AlertDFragment();
string1 = getArguments().getString("latitude");
}
AlertDFragment:
public class AlertDFragment extends DialogFragment {
Spinner spin;
DB db;
String string1;
Button button13;
private String namestr;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater li = LayoutInflater.from(getActivity());
View fdfS = li.inflate(R.layout.fdf, null);
adb.setView(fdfS);
spin=(Spinner)fdfS.findViewById(R.id.spinner);
db = new DB(getActivity());
db.open();
spin.setOnItemSelectedListener(new OnSpinnerItemClicked());
loadSpinnerData();
button13 = (Button) fdfS.findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Clicked : " +
string1, Toast.LENGTH_LONG).show();
Bundle bundle = new Bundle();
bundle.putString("latitude", string1);
fmonday alertdfragment= new fmonday();
alertdfragment.setArguments(bundle);
getDialog().dismiss();
}
});
return adb.create();
}
To Set Data:
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
To Get Data
String latitude = getArguments().getString("latitude")
You can crate a setter to your second dialogFragment ex:
public void setSmth(String value)
{
this.myData = value;
}
, than on your first dialog
DialogFragment dlg1 = new AlertDFragment();
dlg1.setSmth(your data here);
before showing the second one;

Why is this TextView null?

So I'm trying to update a textview from another class. However,whenever I'm calling the method, It seems the textview is null?
I have no idea why that would be the case.
Here is the relevant code
MediaPlayerService:
#Override
public void onPrepared(MediaPlayer mp) {
UI = new MediaPlayerUI();
mp.start();
int minutesDuration = mp.getDuration() / 6000;
int secondsDuration = (mp.getDuration() % 6000) / 1000;
UI.setDurationText(minutesDuration,secondsDuration);
UI.setProgressBarVisibility(0);
UI.setPauseButtonVisibility(1);
UI.playback();
}
MediaPlayerUI:
public class MediaPlayerUI extends MediaPlayerFragment {
public MediaPlayerUI(){
}
public void setSeekBarProgress(int position){
seekBar.setProgress(position);
}
public void setSeekBarMax(int max){
seekBar.setMax(max);
}
public int getSeekBarProgress(){
return seekBar.getProgress();
}
public void setDurationText(int minutes, int seconds){
}
public void setProgressBarVisibility(int code){
if(code == 0){
progressBar.setVisibility(ProgressBar.GONE);
}else{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
}
public void setPauseButtonVisibility(int code){
if(code == 0){
pauseButton.setVisibility(View.GONE);
}else{
pauseButton.setVisibility(View.VISIBLE);
}
}
MediaPlayerFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_media_player, container, false);
mSeriesImage = (ImageView) v.findViewById(R.id.series_image);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
seekBar = (SeekBar) v.findViewById(R.id.seek_bar);
playButton = (ImageButton) v.findViewById(R.id.play_button);
pauseButton = (ImageButton) v.findViewById(R.id.pause_button);
messageTitle = (TextView) v.findViewById(R.id.message_title);
seriesTitle = (TextView) v.findViewById(R.id.series_name);
mProgressText = (TextView) v.findViewById(R.id.progress_text);
mDurationText = (TextView) v.findViewById(R.id.duration_text);
mNoAudioText = (TextView) v.findViewById(R.id.no_audio_text);
mNoAudioText.setVisibility(v.GONE);
playButton.setVisibility(v.GONE);
pauseButton.setVisibility(v.GONE);
mAudioURL = getArguments().getString(Keys.AUDIO_URL_KEY);
mModel = getArguments().getParcelable(Keys.INTENT_SERIES_MODEL_OBJECT_KEY);
mPosition = getArguments().getInt(Keys.POSTION_KEY);
messageTitle.setText(mModel.getmMessageTitle().get(mPosition));
seriesTitle.setText(mModel.getmSeriesName());
Intent intent = new Intent(getActivity(), MediaPlayerService.class);
intent.putExtra(Keys.INTENT_SERIES_MODEL_OBJECT_KEY,mModel);
intent.putExtra(Keys.POSTION_KEY,mPosition);
intent.putExtra(Keys.AUDIO_URL_KEY,mAudioURL);
getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
seekBar.setEnabled(true);
return v;
}
public void setDurationTextView(int minutes,int seconds){
Log.i(TAG,"mDurationText...."+mDurationText);
}
Log Output:
10-29 20:25:00.091 26349-26349/com.tubbs.citychurchob I/MediaPlayerFragment: mDurationText....null
Also, if I call the method directly inside MediaPlayerFragment, the method does NOT return a null value.
I'm really just shooting in the dark on how to update the UI from a Service so any helpful advice on that would be great also. Thank you.
Because it's not guaranteed that the TextView is already created or not when you are calling setDurationText().
In that case you can register a broadcast receiver in your fragment and then send broadcast from the service
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("update_media_ui");
updateMediaUiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get the data here and then set the text if
// the TextView is not null or save the data first
// and set it later if the TextView is null.
}
};
registerReceiver(updateMediaUiReceiver, intentFilter);
and then you also need to unregister the receiver in Fragment onDestroy()
unregisterReceiver(updateMediaUiReceiver);
This is how to send broadcast from service
Intent serviceIntent = new Intent();
serviceIntent.setAction("update_media_ui");
this.sendBroadcast(serviceIntent);

Categories

Resources