I'm trying to modify the back button navigation for a specific activity but I'm having an error
UNCAUGHT EXCEPTION CURRENT ACTIVITY : BookmarksActivity
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.unparcel()' on a null object reference
at android.os.Bundle.putAll(Bundle.java:250)
at android.content.Intent.putExtras(Intent.java:8597)
at usb.terminal.view.fragment.BookmarksFragment$2.onItemClick(BookmarksFragment.java:162)
I've tried two approach, I've modified the back button function in my ActionBarFragment. The problem with my second approach is that it goes to required activity as expected but it's keeps crashing with the error specified above when I'm clicking on an item in my list.
private void initListeners() {
btnBackListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.d("Back Button", "Back button pressed");
int flag = BookmarksFragment.getFlag();
Log.d("Flag Number", String.valueOf(flag));
if (flag == 1){
BookmarksFragment class2 = new BookmarksFragment();
class2.fetchBookmarkCategories();
}
else {
if(getActivity()!=null) {
getActivity().finish();
}
}
}
return true;
}
};
and secondly instead of calling the function of the other class , I've tried to reload the activity using :
BookmarksFragment class2 = new BookmarksFragment();
class2.fetchBookmarkCategories();
This is my bookmark activity which I'm trying to get my desired function.
public class BookmarksActivity extends EmptyActivity {
public BookmarksActivity() {
super(new BookmarksFragment());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
((ActionBarFragment) actionBarFragment).updateTitle(R.string.bookmark_activity_title);
}
}
This is my BookmarkFragment (only part of the code):
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.userId = PreferencesHelper.getPrefsUserId(ctx);
categoriesListView = (NonScrollListView) view.findViewById(R.id.bookmark_categories_list);
recipesListView = (NonScrollListView) view.findViewById(R.id.bookmark_recipes_list);
noResultLayout = (LinearLayout)this.getView().findViewById(R.id.bookmark_recipes_empty_panel);
scrollButton = (CardView) this.getView().findViewById(R.id.load_more_button);
scrollAction = (LinearLayout) this.getView().findViewById(R.id.load_more_action_layout);
scrollLoading = (LinearLayout) this.getView().findViewById(R.id.load_more_loading_layout);
scrollLoadingImage = (ImageView) this.getView().findViewById(R.id.load_more_loading_icon);
recipesAdapter = new RecipesAdapter(ctx, recipesLinkedList);
categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Category category = categoriesLinkedList.get(position);
fetchBookmarksFromCategory(category.getId());
}
});
recipesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ctx, RecipePagerActivity.class);
Bundle extras = activity.getIntent().getExtras();
intent.putExtra("Check_Status", 1);
intent.putExtras(extras);
int recipeId = recipesLinkedList.get(position).getId();
int recipeCount = recipesLinkedList.get(position).getNbFavorite();
boolean recipeStatus = recipesLinkedList.get(position).isFavorite();
intent.putExtra("Recipe Status", recipeStatus);
intent.putExtra("Recipe_Count", recipeCount);
intent.putExtra(RecipesManager.KEY_ID_RECIPE, recipeId);
}
});
setSpinner(view);
fetchBookmarkLists();
}
Both approaches are giving me the same errors. Can someone help with a solution here please?
It seems like your activity.getIntent().getExtras() is returning null value.
Please try to null check before using extras and assign new Bundle() if needed, something like...
int recipeId = recipesLinkedList.get(position).getId();
int recipeCount = recipesLinkedList.get(position).getNbFavorite();
boolean recipeStatus = recipesLinkedList.get(position).isFavorite();
Intent intent = new Intent(ctx, RecipePagerActivity.class);
Bundle extras = activity.getIntent().getExtras();
if (extras == null) extras = new Bundle(); //solution
extras.putInt("Check_Status", 1);
extras.putInt(RecipesManager.KEY_ID_RECIPE, recipeId);
extras.putInt("Recipe_Count", recipeCount);
extras.putBoolean("Recipe Status", recipeStatus);
intent.putExtras(extras);
Related
When I run my app and go to the "EditProfile" activity. And then, I will immediately receive the toast message "Something is wrong" which means, the variables "selectedCountry", "selectedAge", and "selectedGender" are null.
public class EditProfile extends AppCompatActivity {
UserInfo userInfo;
UserInfo profileDetails;
Spinner spinnerFrom;
Spinner spinnerAge;
Spinner spinnerGender;
EditText hobbyEdit;
Button btnDone;
TextView textView;
String selectedCountry;
String selectedAge;
String selectedGender;
DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Profile.class);
intent.putExtra("id", userInfo.getId());
intent.putExtra("username", userInfo.getUsername());
startActivity(intent);
}
});
Bundle extras = getIntent().getExtras();
int id = extras.getInt("id");
final String username = extras.getString("username");
// Username
userInfo = new UserInfo(id, username);
textView = (TextView) findViewById(R.id.usernameUnedit);
textView.setText(username);
// Country
spinnerFrom = (Spinner) findViewById(R.id.spinnerFrom);
Locale[] locales = Locale.getAvailableLocales();
final ArrayList<String> countries = new ArrayList<String>();
countries.add("-");
for (Locale locale : locales) {
String country = locale.getDisplayCountry();
if (country.trim().length() > 0 && !countries.contains(country)) {
countries.add(country);
}
}
Collections.sort(countries);
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, countries);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom.setAdapter(countryAdapter);
spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCountry = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Age
spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
final ArrayList<String> ages = new ArrayList<String>();
ages.add("-");
for (int i = 18; i < 100; i++) {
ages.add(String.valueOf(i));
}
ArrayAdapter<String> ageAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ages);
ageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAge.setAdapter(ageAdapter);
spinnerAge.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedAge = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Gender
spinnerGender = (Spinner) findViewById(R.id.spinnerGender);
final ArrayList<String> genders = new ArrayList<String>();
genders.add("-");
genders.add("Male ♂");
genders.add("Female ♀");
genders.add("Other");
ArrayAdapter<String> genderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genders);
genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(genderAdapter);
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Hobby
hobbyEdit = (EditText) findViewById(R.id.hobbyEdit);
// Button done
btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setEnabled(false);
/* Stuck at this if statement below */
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileDetails = new UserInfo(selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString());
mydb.updateTable(username, profileDetails);
}
});
} else {
Toast.makeText(this, "Something is wrong 2.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Something is wrong.", Toast.LENGTH_LONG).show();
}
}
}
I expect that after choosing an item from those 3 dropdown lists (spinners) and the values of the chosen items do not exist in database, then the "Done" button would be clickable. Once the button is clicked, it would store the selected values from the dropdown lists (spinners) into database by updating it.
Unfortunately, I am stuck at the if statement as stated in the given code as it keeps returning the "else" statement.
Set your variable as...
String selectedCountry = "";
String selectedAge = "";
String selectedGender = "";
And check condition as...
if (!selectedCountry.equals("") && !selectedAge.equals("") && !selectedGender.equals("")) {
//your code goes here
}
You have to check your both conditions in Spinner's OnItemSelectedListener, If both conditions will return true then enable your button. and call setonClickListener on button in onCreateView, like this.
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
//Conditions to enable button
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
add these lines in all spinners.
In your onCreate method, you have instantiated the views and attached listeners to them. That is perfectly fine. However, this does not mean that the logic in those listeners will be execute at the same time and order. You have just defined the behaviour of the listeners. After all that initialisation, your code directly checks the values of the three Strings mentioned in your question. It does not wait for a user to interact with the spinners.
What you want is to trigger the change in the "done" button when a user selects something from the spinner. So the logic of setting the strings and thereby checking if you could enable the "done" button must go in the listeners of the spinners.
I am not giving you a direct code solution to the problem, but an approach which you could employ.
Im developing and App and I need to pass int data from a fragment to Another Activity. The problem its that it returns 0 or false.
First I start ActivityForResult putting a Bundle.
Then I pass a boolean and it works fine but when I try to put the int into the bundle from the fragment and comeback to onActivityResult it retuns 0 or false.
Can someone help please? I have tried with putExtras too and still false
public void newcampeon(View view) {
Intent i = new Intent(getApplicationContext(), Campeones.class);
b = new Bundle();
Boolean vengodraft = true;
b.putBoolean("vengodraft",vengodraft);
i.putExtras(b);
startActivityForResult(i,01);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
int res = b.getInt("idcampeon");
aban1.setImageResource(res);
Toast.makeText(getApplicationContext(),String.valueOf(res),
Toast.LENGTH_SHORT).show();
}
------ Fragment on Another Acivity
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_top_lane, container, false);
b = getArguments();
if(b!=null){
Boolean vengodraft = b.getBoolean("vengodraft");
if(vengodraft==true){
final ImageView aatrox = v.findViewById(R.id.aatrox);
aatrox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = aatrox.getId();
getActivity().setResult(Activity.RESULT_OK);
b.putInt("idcampeon",id);
getActivity().finish();
}
});
}
}
return v;
It should return the current id of the Img
Finally I got what its wrong. Its very simple.
I just put correctly the sintax here. Just make a new intent and pass the arguments .
#Override
public void onClick(View v) {
String nombrecampeon = String.valueOf(aatrox.getTag());
Intent i = new Intent();
i.putExtra("nombrecampeon",nombrecampeon);
getActivity().setResult(Activity.RESULT_OK,i);
getActivity().finish();
}
});
And on ActivityResult
String uri = "#drawable/"+data.getExtras().getString("nombrecampeon");
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
aban1.setImageDrawable(res);
Anyway, thanks all for the help :)
I know it's probably very simple, but my app is not working. I need to input weight in Edittext and use its value, and the total distance value from the method CalculateDistance and the value of the CalculateCalories method.
With this code, I'm not able to click on Start Button.
Where do I have to add code which gets the value from Edittext and how can I make it work?
My code currently looks like this:
public class RunningModeFragment extends Fragment implements IGPSActivity
{
MyLocation myLocation=null;
Button btnRunningModeStart=null;
EditText txtWeight=null;
TextView txtTotalDistance=null;
TextView txtCalories=null;
Button btnShowRunningHistory = null;
String weight;
Float weightInKg;
Float caloriesBurned;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.running_mode_fragment, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
txtTotalDistance=(TextView) getView().findViewById(R.id.txtTotalDistance);
txtWeight=(EditText) getView().findViewById(R.id.txtWeight);
txtCalories=(TextView) getView().findViewById(R.id.txtCalories);
if (txtWeight.getText().toString().isEmpty())
{
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
}
btnRunningModeStart = (Button) getView().findViewById(R.id.btnRunningModeStart);
btnRunningModeStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
onClick_StartRunningMode(v);
}
});
btnShowRunningHistory = (Button) getView().findViewById(R.id.btnShowRunningHistory);
btnShowRunningHistory.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClick_ShowRunningHistory(v);
}
});
}
private void onClick_ShowRunningHistory(View v) {
Fragment fragment = new RunningHistoryFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment, "Running History");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
private void onClick_StartRunningMode(View v)
{
if(myLocation ==null)
{
new Thread(new Runnable() {
public void run() {
DatabaseFacade dbfacade = new DatabaseFacade(getView().getContext());
Activity activity = new Activity(ActivityMode.RUNNING);
activity.setActivityId(activity.getActivityId());
activity.setStart(new Timestamp(new Date().getTime()));
dbfacade.saveActivity(activity);
}
}).start();
Toast.makeText(this.getActivity(), "Start Running mode", Toast.LENGTH_SHORT).show();
myLocation = new MyLocation();
myLocation.LocationStart(this);
btnRunningModeStart.setText("Stop");
}
else
{
Toast.makeText(this.getActivity(), "Stop Running mode", Toast.LENGTH_SHORT).show();
myLocation.LocationListenerStop();
myLocation = null;
btnRunningModeStart.setText("Start");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
Location lastPoint = null;
float totalDistance = 0;
public static float CalculateDistance(Location startPoint, Location endPoint)
{
return (startPoint.distanceTo(endPoint) / ((float)1000));
}
public static float CalculateCalories(float a, float b){
return ((float)1.036)*a*b;
}
#Override
public void locationChanged(Location location)
{
try
{
if(lastPoint==null)lastPoint = location;
totalDistance += CalculateDistance(lastPoint, location);
lastPoint=location;
txtTotalDistance.setText(totalDistance + " km");
caloriesBurned=CalculateCalories(totalDistance,weightInKg);
txtCalories.setText(caloriesBurned + " kcal");
DatabaseFacade dbf = new DatabaseFacade(getView().getContext());
Activity activity = new Activity(ActivityMode.RUNNING);
dbf.saveLocation(new GpsLocation(activity.getActivityId(), location.getLongitude(), location.getLatitude(), location.getAccuracy()));
}catch (Exception E)
{
E.printStackTrace();
}
}
public void onResume(){
super.onResume();
((Main) getActivity()).setActionBarTitle("Running mode");
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
// navigationView.setNavigationItemSelectedListener((Main) getActivity());
navigationView.setCheckedItem(R.id.runningMode);
}
}
I need to do the following:
get the value from EditText txtWeight, parse it to float and use in CalculateCalories method
public static float CalculateCalories(float a, float b){
return ((float)1.036)*a*b;
}
I tried with this, but it's not working
if (txtWeight.getText().toString().isEmpty())
{
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
}
first of all create a view than initialize textview inside onCreateView like this,
View view = inflater.inflate(R.layout.fg_unapproved_leave, container, false);
Textview tv= view.findViewById(R.id.tv);
the code your have written in onViewCreated() should be in onCreateVIew(). remove it from onViewCreated().
You can put it on your onCreateView() as #jitendra purohit told to you, as follows :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fg_unapproved_leave, container, false);
txtTotalDistance=(TextView) view.findViewById(R.id.txtTotalDistance);
txtWeight=(EditText) view.findViewById(R.id.txtWeight);
txtCalories=(TextView) view.findViewById(R.id.txtCalories);
...
return view;
}
Or you can keep your code in your onViewCreated() but instead of getView() you can do getActivity() something like this :
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
txtTotalDistance=(TextView) getActivity().findViewById(R.id.txtTotalDistance);
txtWeight=(EditText) getActivity().findViewById(R.id.txtWeight);
txtCalories=(TextView) getActivity().findViewById(R.id.txtCalories);
...
See this question/answers aswell...
You can do that in an onClick() or if you do want to show the changes dynamically use TextWatcher.
Using TextWatchers
TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
if (txtWeight.getText().toString().isEmpty()) {
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
//Call your CalculateCalories method
}
}
};
}
Using onClick I'm not going to implement it, but you can do it with a Button or on the same EditText and do the same stuff that in afterChangedText() on TextWatcher.
Remember in onCreateView() you'll have to do this :
txtWeight.addTextChangedListener(textWatcher);
Put that line ==> weight = txtWeight.getText().toString(); in the onCLick method
btnShowRunningHistory = (Button) getView().findViewById(R.id.btnShowRunningHistory);
btnShowRunningHistory.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (txtWeight.getText().toString().isEmpty())
{
return;
}
else {
weight = txtWeight.getText().toString();
weightInKg = Float.parseFloat(weight);
}
onClick_ShowRunningHistory(v);
}
});
*If you are using View binding*
Add this line under onViewCreated
val binding=<BindingFile>.bind(<binding.root from onCreate View>)
and try accessing values now using local binding variable.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentSigninBinding.inflate(layoutInflater, container, false)
val udata = "don't have a account ?"
val content = SpannableString(udata)
content.setSpan(UnderlineSpan(), 0, udata.length, 0)
binding.textView5.text = content
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val root = FragmentSigninBinding.bind(binding.root)
// Navigate to signup fragment
binding.signup.setOnClickListener {
view.findNavController().navigate(R.id.action_signin_to_signup)
}
I've been scouring youtube for hours and I cant seem to find one that works. So far I have this in my code but it wont let me start a new activity.
public class MainActivity extends ActionBarActivity {
ArrayList<PerMoney> PeepList = new ArrayList<PerMoney>();
int pos = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView people = (ListView)findViewById(R.id.peopleList);
setContentView(R.layout.activity_main);
if(PeepList.size() != 0)
UpdateList();
people.setOnItemClickListener(onListClick);
}
and then here is the onitemclick part
private AdapterView.OnClickListener onListClick=new AdapterView.OnItemClickListener()
{
ListView people = (ListView) findViewById(R.id.peopleList);
int res;
people.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
pos = position;
Intent intent = new Intent(this,SecondActivity.class);
startActivityForResult(intent, 0);
}
};
}
Shouldn't it be:
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
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");