NextActivity onCreate() is skipped - java

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();
}

Related

getting error when i try to use switch button is differen class

So I defined a switch button in ProfileSettingsfragment but i am using that button in Explanation.class. What I am really trying to do is when switch button is checked i want start service else i don't want to star service from Explanation.class
SO I tried Some code and it showing me this error " java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.appcompat.widget.SwitchCompat.isChecked()' on a null object reference
at com.harsh.preacher.ui.Home.Explaination$1.onClick(Explaination.java:43)"
P.S I have designed switch button in ProfileSettingsfragment.xml
Here is ProfileSettingsfragment class code
public class ProfileSettingsFragment extends Fragment {
private GoogleSignInClient mGoogleSignInClient;
public SwitchCompat notePopUp;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_profilesettings, container, false);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(requireContext(), gso);
final ProfileSettingsFragment profileSettingsFragment =new ProfileSettingsFragment();
Button signOut1 = root.findViewById(R.id.signOut);
signOut1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO Custom Alert Dialog Bar
// signOut();
Intent intent = new Intent(getContext(), AndarAwoo.class);
startActivity(intent);
// Animation(signOut1);
}
});
notePopUp = (SwitchCompat) root.findViewById(R.id.notePopUp);
RelativeLayout EditName = root.findViewById(R.id.EditName);
RelativeLayout ProfileSettingsLayout= root.findViewById(R.id.profileSettingsCardView);
TextView EditNameText = root.findViewById(R.id.EditNameText);
EditNameText.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
if(EditName.getVisibility() == View.GONE){
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.VISIBLE);
}else {
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.GONE);
}
}
});
return root;
}
Here is my explanation class code
public class Explaination extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explaination);
Intent intent = getIntent();
String about = intent.getStringExtra("about");
TextView about1 = findViewById(R.id.about);
about1.setText(about);
Button resource = findViewById(R.id.Resource);
resource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String url = intent.getStringExtra("button");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
ProfileSettingsFragment checkNotePopUp = new ProfileSettingsFragment();
checkNotePopUp.notePopUp = findViewById(R.id.notePopUp);
if(checkNotePopUp.notePopUp.isChecked()){
startService(new Intent(Explaination.this, NotePopUpHead.class));
}
else{
stopService(new Intent(Explaination.this,NotePopUpHead.class));
}
finish();
startActivity(i);
}
});
}
}

How do I send data from fragment to another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
In my app, i have an activity that have recyclerview inside a fragment and the recycleview retrieve data from cloud store Firebase. I want to open new activity that will retrieve the data according to the link(that display on the recycler view) user has clicked.
How do i get the data and display it in new activity?
From ForumTitle.java > Show ReviewFragment.java > User click a value > Show ForumInterface.java
ForumTitle.java
public class ForumTitle extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
ImageButton IVReview,IVTechnical,IVHardware;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_title);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment selectedFragment = null;
if (v == findViewById(R.id.iBReview)){
selectedFragment = new ReviewFragment();
}
else if (v == findViewById(R.id.iBTech)){
selectedFragment = new TechnicalSupportFragment();
}
else if (v == findViewById(R.id.iBHardware)){
selectedFragment = new HardwareFragment();
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,selectedFragment);
transaction.commit();
}
};
IVReview = (ImageButton)findViewById(R.id.iBReview);
IVTechnical = (ImageButton)findViewById(R.id.iBTech);
IVHardware = (ImageButton)findViewById(R.id.iBHardware);
IVReview.setOnClickListener(listener);
IVTechnical.setOnClickListener(listener);
IVHardware.setOnClickListener(listener);
}
}
ReviewFragment.java
public class ReviewFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference userRef = db.collection("Review");
private ForumAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_review,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Query query = userRef.orderBy("DatePosted",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Forum> options = new
FirestoreRecyclerOptions.Builder<Forum>()
.setQuery(query,Forum.class)
.build();
adapter = new ForumAdapter(options);
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.rvReview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ForumAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Forum forum = documentSnapshot.toObject(Forum.class);
String title = forum.getTitle();
String id = documentSnapshot.getId();
Intent intent = new Intent(getActivity(), ForumInterface.class);
Bundle extras = intent.getExtras();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
startActivity(intent);
}
});
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
ForumInterface.java
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
private CollectionReference userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}
ForumAdapter.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
#Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
#NonNull
#Override
public ForumHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.title);
textViewDescription = itemView.findViewById(R.id.description);
timeStamp = itemView.findViewById(R.id.timestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
With the code above i run it, i got an error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putString(java.lang.String, java.lang.String)' on a null object reference
at my.edu.fsktm.um.finalproject.Fragment.ReviewFragment$1.onItemClick(ReviewFragment.java:61)
at my.edu.fsktm.um.finalproject.ForumTitle.ForumAdapter$ForumHolder$1.onClick(ForumAdapter.java:56)
The picture of my app
When I clicked the title "GTX 1660 Ti Gaming X"
You try to set content on a Bundle which is null in your ReviewFragment's onClick. Use new Bundle() instead of intent.getExtras(); to instantiate Bundle
Bundle extras = new Bundle();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
//You have to set the bundle to intent
intent.putExtras(extras);
startActivity(intent);
Beside this move below code inside onCreate of ForumInterface Activity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
And here is the complete Activity.
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db;
private CollectionReference userRef;
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
db = FirebaseFirestore.getInstance();
userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}

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;

Fragment returning null from intent

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");

Categories

Resources