hello I am making a bmi calculator i want it to work based on 3 variables, weight height and gender.
The gender in on a spinner which lets the user choose:
final Spinner spinner = view.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),R.array.gender, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
The problem is the spinner uses a whole new method for it to work:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String gendertext = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), gendertext,Toast.LENGTH_SHORT).show();
}
i want to take that variable gendertext and use it on this part of code which is inside the onCreateView
edit_height = (EditText) view.findViewById(R.id.edit_height);
edit_weight = (EditText) view.findViewById(R.id.edit_weight);
button_calculate_bmi = (Button) view.findViewById(R.id.button_calculate_bmi);
text_results = (TextView) view.findViewById(R.id.text_results);
button_calculate_bmi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
String results = "Results:";
float height = 0;
float weight = 0;
try {
height = Float.parseFloat(edit_height.getText().toString());
weight = Float.parseFloat(edit_weight.getText().toString());
} catch (Exception ex) {
Context context = getActivity();
CharSequence text = "You forgot to enter something";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
height = height/100;
float bmi = weight / (height * height);
text_results.setText(results+bmi);
}
});
return view;
}
thank you in advance!
You can create the genderText variable outside of all methods in the Activity and initialize it to the first item in your R.array.gender. When the value in spinner is changed, onItemSelected is called and you get the updated value which you can set to the variable genderText.
Then in the button OnClickListener you can use the genderText variable.
Related
Intent i = getIntent();
Bundle myBundle = i.getExtras();
date1 = myBundle.getString("Date1");
date2 = myBundle.getString("Date2");
user = myBundle.getString("UserName");
chain = myBundle.getString("ChainName");
shop = myBundle.getString("ShopName");
product_g = myBundle.getString("ProductGroup");
product_c = myBundle.getString("ProductCategory");
product = myBundle.getString("Product");
count = myBundle.getInt("Count");
type_c = myBundle.getInt("CountType");
price = myBundle.getInt("Price");
type_p = myBundle.getInt("PriceType");
inch = myBundle.getInt("Inch");
promotor = myBundle.getInt("Promotor");
I need these variables in recycler adapter to make retrofit request in RecyclerView adapter.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
android.app.AlertDialog.Builder mBuilder = new android.app.AlertDialog.Builder(context);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mView = li.inflate(R.layout.sales_filtered_shop_pop_up, null);
final RecyclerView rd3 = (RecyclerView) mView.findViewById(R.id.sales_rv);
Button mClose = (Button) mView.findViewById(R.id.sales_pop_up_btn_close);
mBuilder.setView(mView);
final android.app.AlertDialog dialog = mBuilder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(false);
// here
dialog.show();
mClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
This is my RecyclerView adapter item click. I need the variables in // here to make Retrofit api call.
Intents are for communication between activity, what you need to do is to create a simple function in your adapter, and then call in the activity.
Adapter:
private String date1;
private String date2;
public void setData(String date1, String date2, ...) {
this.date1 = date1;
this.date2 = date2;
...
}
Activity:
adapter.setData(date1, date2, ..);
(I can't use the comment yet but)
The idea which #DoubleD wrote is the right one, all you need to do is to create a function (much like a constructor) that will receive your data in the adapter class.
The NullPointerException you are getting isn't from the function, check your data.
And I will suggest to create a custom object that will hold those things (depend on your goal).
Check this answer. Here you will have your onClickListener() in your Activity.
Simple Android RecyclerView example
I googled alot for this with no result. I have a custom ListView, every element has few TextViews and 3 Spinners and button. When I set values on spinners and press a button I want to get selcted values from those spinners and send them to a server. Everything works fine for list elements from top to the last visible element but on items that are not visible or visible in half 2 bad things happen.
If I change value on spinner, press button to save, 2 things happen depedning on which element I work on:
If element was half, or a little visible on activity load and I do those steps on it the value that is passed is the value that was set before I changed it.
If element wasn't visible at all and I do steps on it app crashes with NullPointerException linking the error to the declaration of a Spinner.
Code:
Adapter:
public View getView(final int position, View convertView, final ViewGroup parent) {
StudentList students = studentList.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.student_list, null);
TextView id = (TextView) view.findViewById(R.id.list_id);
TextView name = (TextView) view.findViewById(R.id.list_name);
TextView surname = (TextView) view.findViewById(R.id.list_surname);
Spinner t1 = (Spinner) view.findViewById(R.id.list_t1);
Spinner t2 = (Spinner) view.findViewById(R.id.list_t2);
Spinner t3 = (Spinner) view.findViewById(R.id.list_t3);
TextView final = (TextView) view.findViewById(R.id.list_final);
Button save = (Button) view.findViewById(R.id.save);
id.setText(students.getId());
name.setText(students.getName());
surname.setText(students.getSurname());
final.setText(students.getFinal());
for (int i=0;i<t1.getCount();i++){
if (t1.getItemAtPosition(i).toString().equalsIgnoreCase(students.getT1())){
t1.setSelection(i);
}
}
for (int i=0;i<t2.getCount();i++) {
if (t2.getItemAtPosition(i).toString().equalsIgnoreCase(students.getT2())) {
t2.setSelection(i);
}
}
for (int i=0;i<t3.getCount();i++){
if (t3.getItemAtPosition(i).toString().equalsIgnoreCase(students.getT3())){
t3.setSelection(i);
}
}
if(t1.getSelectedItemPosition() > 1){
t2.setEnabled(false);
t3.setEnabled(false);
} else if (t2.getSelectedItemPosition() > 1){
t3.setEnabled(false);
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
if(studentList.get(position).getProtokol().equals("open")){
} else {
t1.setEnabled(false);
t2.setEnabled(false);
t3.setEnabled(false);
save.setEnabled(false);
}
return view;
}
onCreate:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long viewId = view.getId();
Spinner t1 = (Spinner) parent.getChildAt(position).findViewById(R.id.lista_termin1);//There the app crashes if I do things I described above
Spinner t2 = (Spinner) parent.getChildAt(position).findViewById(R.id.lista_termin2);
Spinner t3 = (Spinner) parent.getChildAt(position).findViewById(R.id.lista_termin3);
if (viewId == R.id.save) {
String t1Itemn = t1.getSelectedItem());
String t2Itemn = t2.getSelectedItem());
String t3Itemn = t3.getSelectedItem());
//Code that sends those string to the server based on urlConnection - works perfectly fine)
}
}
});
I was googling for 2 days and finally decided to post here, but 1h later I found the solution here. Changed all spinners like this:
Spinner t1 = (Spinner) parent.getChildAt(position-parent.parent.getFirstVisiblePosition()).findViewById(R.id.lista_termin1);
I have no clue what I am doing wrong but when I print the text from the edit text (using getText().toString()), in the logcat it is always an empty string. I am wondering if it has to do with that it is being done inside the onClickfunction for the continue button. I'm putting the whole onCreate function because the code inside the onClick function seems to match exactly what countless tutorials have shown.
#Override
protected void onCreate(Bundle savedInstanceState)
{
Button add_test = new Button(this);
Button delete_test = new Button(this);
Button[] barray = new Button[100];
int trans_grey = Color.parseColor("#40000000");
final String[] test_types = new String[] {"Choose...","Terms", "Multiple choice", "Custom"};
final ArrayAdapter<String> type_adapter = new ArrayAdapter<String>(this,R.layout.spinner_item,test_types);
// Preliminary operations and display opening layouts
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout scroll_layout = (LinearLayout)findViewById(R.id.scroll_layout);
LayoutParams scroll_params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
// Add the add a dynamic button
for (int index = 0; index <= 4; index++)
{
barray[index] = new Button(this);
barray[index].setBackgroundColor(trans_grey);
barray[index].setText("Array buttons");
barray[index].setTextColor(Color.parseColor("#CCffffff"));
scroll_layout.addView(barray[index], scroll_params);
}
add_test.setTextColor(Color.parseColor("#CCffffff"));
add_test.setBackgroundColor(trans_grey);
add_test.setText("Add a Test");
scroll_layout.addView(add_test, scroll_params);
add_test.setOnClickListener(new View.OnClickListener()
{#Override
public void onClick(View v)
{
AlertDialog.Builder add_test_builder = new AlertDialog.Builder(TestActivity.this);
final View add_test_view = getLayoutInflater().inflate(R.layout.add_test_menu, null);
Spinner type_spinner = (Spinner) add_test_view.findViewById(R.id.type);
add_test_builder.setView(add_test_view);
final Button continue_button = (Button) add_test_view.findViewById(R.id.continue_button);
AlertDialog dialog = add_test_builder.create();
dialog.show();
dialog.getWindow().setLayout(950,900);
type_spinner.setAdapter(type_adapter);
continue_button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View add_test_view = getLayoutInflater().
inflate(R.layout.add_test_menu, null);
// The view of the test attribute dialog
EditText test_title = (EditText) add_test_view.
findViewById(R.id.testTitle);
// Test title widget to hold title of test
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title);
}
});
return;
}
});
// Add the delete a test button
delete_test.setTextColor(Color.parseColor("#CCffffff"));
delete_test.setBackgroundColor(trans_grey);
delete_test.setText("Delete a Test");
scroll_layout.addView(delete_test, scroll_params);
return;
}
}
Layout:
<EditText
android:id="#+id/testTitle"
android:maxLines="1"
android:lines="1"
android:inputType="textAutoCorrect"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#00000000"
android:hint="Test Title"/>
Don't inflate the view yiu are assigning to dialog multiple times as you are creating multiple instances of it you are writing to one view but trying to fetch the data from another....Try doing it like this...
AlertDialog.Builder add_test_builder = new AlertDialog.Builder(TestActivity.this);
final View add_test_view = getLayoutInflater().inflate(R.layout.add_test_menu, null);
final EditText test_title = (EditText) add_test_view. findViewById(R.id.testTitle);
continue_button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title); } });
I think you should define EditText before and outside of your onlick method. Or get string after your onlick method.
IMO you may call editText string outside of Click method like above
final EditText test_title;
continue_button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View add_test_view = getLayoutInflater().
inflate(R.layout.add_test_menu, null);
// The view of the test attribute dialog
EditText test_title = (EditText) add_test_view.
findViewById(R.id.testTitle);
// Test title widget to hold title of test
}
});
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title);
I have numerous GeoPoints and when any GeoPoint is selected a layout is inflated above the GeoPoint giving the user details on that that location. Within the infalted layout there is an imageButton but I can't seem to click it and I don't know the reason why! Below shows the code that I have created, the code adds points of interests to the maps and also populates the inflated layout with information.
//show the place markers on map.
for (int i = 0; i<mListPlaceData.size(); i++){
PlaceData data = mListPlaceData.get(i);
data.marker = mMap.addMarker(new MarkerOptions().position(new LatLng(data.lat, data.lon)).
icon(BitmapDescriptorFactory.fromResource(R.drawable.place_mark))); //show place mark on map
data.marker.setSnippet(String.valueOf(i));//set index of the data
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.place_detail, null);
String pos = arg0.getSnippet(); //get index of the marker data
try{
int ipos = Integer.parseInt(pos);
PlaceData data = mListPlaceData.get(ipos); //get the data by index
((TextView)v.findViewById(R.id.txtName)).setText(data.name); //show name of the place
((TextView)v.findViewById(R.id.txtHours)).setText("Hours: "+data.hours); //show hours of the place
((TextView)v.findViewById(R.id.txtCountry)).setText("Country: "+data.country); //show country of the place
((TextView)v.findViewById(R.id.txtAddress)).setText("Address: "+data.address); //show address of the place
((TextView)v.findViewById(R.id.txtPostCode)).setText("Postcode: "+ data.postcode); //show postcode of the place
View.OnClickListener imageDirections = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(TrackingServiceActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();
}
};
imageButton = (ImageButton) v.findViewById(R.id.imageButton1);
imageButton.setOnClickListener(imageDirections);
}catch(Exception e){
}
return v;
}
});
}
Your ImageButton's declaration is wrong. Change
imageButton = (ImageButton) findViewById(R.id.imageButton1);
with
imageButton = (ImageButton) v.findViewById(R.id.imageButton1);
I would like to take the value of a spinner and convert it to a String to play about with.
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
s1.setOnItemSelectedListener((OnItemSelectedListener) this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
I thought somthing like this would work....
private OnClickListener sendClickListener = new OnClickListener(){
public void onClick(View arg0) {
EditText dstName = (EditText) findViewById(R.id.destinationAddress);
EditText dstLanguage = (EditText) findViewById(R.id.spinner1);
String address = dstName.getText().toString();
String language = dstLanguage.getText().toString();
ops.createSocketConnection(language, address);
Notification notification = new Notification();
notification.vibrate = new long[] {100};
}};
Allas it does not....
I have looked at a few examples however I am not sure If they are directly related to my question.
Thanks in advance!
Try this:
OnItemSelectedListener itemSelectedHandler = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
String str = parent.getItemAtPosition(pos).toString();
// Do whatever you want with the string
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
};
//set the spinner's listener for select event
mSpinner.setOnItemSelectedListener(itemSelectedHandler);
Hmm, I'm not entirely sure what the question is, but if the issue is getting the value of a spinner, check out Spinner data to string:
You can use getSelectedItem to
get the currently selected item. If
you've bound to an
ArrayAdapter<String>, this will
be the value.
Of course, in this instance you're returning CharSequence, so you'd do
String strVal = getSelectedItem().toString();
Hope this helps,
Phil Lello