Cannot use value from edittext in android fragment, where to place it? - java

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

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.

Trying to modifiy back button for an activity

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

Trying to call method from MainActivity in Another Activity it is me leading to error

I have Recycler ListView which I show in MainActivity and the first item it is as selected, I have done to click for another items but the last stays clicked and when I try to take this recycler view to show me in next Activity it doesn't work.
The first item it is selected but I have a click method which when click an image makes as selected but when I click a new image this works but the first item stays as selected so continues for others images. I want only a image to be selected.
I don't want to write twice the same code.
Is it good if I have a class only for this method which I can use everytime I want.
The id of recycler view list it is the same on both xml's.
If you have any suggestion for my question please let me know.
This is the adapter for the RecyclerView.
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
This is the method in MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
This is the button which takes to another activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
Cursor data = mDatabaseHelper.getData();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("name", newEntry);
intent.putExtra("test", mSearchUrl.get(0));
startActivityForResult(intent, 2);
}
});
This is the another activity
public class ActivitySearchEngine extends Activity implements
SwipeRefreshLayout.OnRefreshListener {
public ImageView mHome;
public EditText searchPlugin;
public WebView webView;
Button btnSearch;
public ImageButton clearSearch, exitButton;
public ImageView favIcon;
public ProgressBar loadIcon;
String text;
SwipeRefreshLayout refreshLayout;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
private String selectedSearchUrl;
RecyclerView mListView;
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
mHome = findViewById(R.id.imgBtnHome);
searchPlugin = findViewById(R.id.etSearch);
webView = findViewById(R.id.webView);
clearSearch = findViewById(R.id.btnClearSearch);
btnSearch = findViewById(R.id.btnSearch);
favIcon = findViewById(R.id.imgViewFavIcon);
loadIcon = findViewById(R.id.progressBarIcon);
exitButton = findViewById(R.id.imgBtnStopLoad);
refreshLayout = findViewById(R.id.refreshLayout);
mListView = findViewById(R.id.lvEngines);
refreshLayout.setOnRefreshListener(this);
mDatabaseHelper = new DatabaseHelper(this);
mainActivity.intSearch(); // Here it is the error
Activity.ActivitySearchEngine}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("test");
searchPlugin.setText(selectedName);
loadIcon.setVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.bing.com/search?=" + selectedName);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
favIcon.setImageBitmap(icon);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadIcon.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
try {
if (loadIcon.getVisibility() == View.VISIBLE) {
loadIcon.setVisibility(View.GONE);
favIcon.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
exitButton.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRefresh();
}
});
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
searchPlugin.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
processButtonByTextLength();
}
});
mHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText(null);
finish();
}
});
clearSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText("");
}
});
public void processButtonByTextLength() {
String inputText = searchPlugin.getText().toString();
if(inputText.length() > 0) {
btnSearch.setVisibility(View.VISIBLE);
mHome.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.VISIBLE);
loadIcon.setVisibility(View.GONE);
exitButton.setVisibility(View.GONE);
} else if(inputText.length() == 0) {
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
clearSearch.setVisibility(View.GONE);
}
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
}
This is the photo with RecyclerView at MainActivity.class
Photo of another Activity

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.

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