Although this question has already been discussed, I can't understand why I am getting this NullPointerException error. I am trying to get a selected RadioButton value from a RadioGroup in a Fragment as shown in below code. The error is in the line:
radioButton = (RadioButton) rootView.findViewById(selectedId);
I am getting NULL for radioButton. Can somebody clarify why?
public class Booking extends Fragment {
public Context _context = getActivity();
private String JSON_URL;
private SharedPrefManager sharedPrefManager;
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button getQuotes;
public Booking() {
// Required empty public constructor
}
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_booking, container, false);
sharedPrefManager = new SharedPrefManager(getActivity());
return rootView;
}
public void onViewCreated(View rootView, Bundle savedInstanceState){
super.onViewCreated(rootView, savedInstanceState);
final View v = rootView;
// Spinner element
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
radioGroup = (RadioGroup) rootView.findViewById(R.id.radio);
getQuotes = (Button) rootView.findViewById(R.id.getQuotes);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("4 Night / 5 Days");
categories.add("5 Night / 6 Days");
categories.add("6 Night / 7 Days");
categories.add("7 Night / 8 Days");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("tag", "String item="+position);
if(position == 0) {
JSON_URL = "http://kaushika.tigrimigri.com/gcmMulticast2/getPackages.php";
}
getJSON(JSON_URL, v);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String text = spinner.getSelectedItem().toString();
sharedPrefManager.addSpinner(text);
addListenerOnButton();
}
public void addListenerOnButton(){
getQuotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View rootView) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
Log.d("tag","selectId" + selectedId);
// find the radiobutton by returned id
radioButton = (RadioButton) rootView.findViewById(selectedId);
Log.d("tag","radioButton" + radioButton);
Log.d("tag","radioButton.getText()" + radioButton.getText());
//String radiovalue = ((RadioButton) rootView.findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
//sharedPrefManager.addRadio(radioButton.getText().toString());
Toast.makeText(
getActivity().getApplication(),
radioButton.getText(),
Toast.LENGTH_LONG)
.show();
}
});
}
The xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Booking Options"
android:layout_marginBottom="5dp"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true">
<TableLayout
android:id="#+id/table"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true">
</TableLayout>
</HorizontalScrollView>
</ScrollView>
<RadioGroup
android:id="#+id/radio"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Economy"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Standard"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delux"/>
<RadioButton
android:id="#+id/radio4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Super Delux"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select fare option" />
</RadioGroup>
<Button
android:id="#+id/getQuotes"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:background="#drawable/button"
android:text="Get Quotes"/>
</LinearLayout>
The Logcat:
11-09 12:11:28.814 24299-24299/san.com.andamanecstacy1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: san.com.andamanecstacy1, PID: 24299
java.lang.NullPointerException
at san.com.andamanecstacy1.Booking$1.onClick(Booking.java:92)
at android.view.View.performClick(View.java:4487)
at android.view.View$PerformClick.run(View.java:18746)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5077)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Make rootView as global variable because your method 'addListenerOnButton()' getting null view.
as below:
public class Booking extends Fragment {
public Context _context = getActivity();
private String JSON_URL;
private SharedPrefManager sharedPrefManager;
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button getQuotes;
private View rootView;
public Booking() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_booking, container, false);
sharedPrefManager = new SharedPrefManager(getActivity());
return rootView;
}
public void onViewCreated(View rootView, Bundle savedInstanceState){
super.onViewCreated(rootView, savedInstanceState);
final View v = rootView;
// Spinner element
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
radioGroup = (RadioGroup) rootView.findViewById(R.id.radio);
getQuotes = (Button) rootView.findViewById(R.id.getQuotes);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("4 Night / 5 Days");
categories.add("5 Night / 6 Days");
categories.add("6 Night / 7 Days");
categories.add("7 Night / 8 Days");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.d("tag", "String item="+position);
if(position == 0) {
JSON_URL = "http://kaushika.tigrimigri.com/gcmMulticast2/getPackages.php";
}
getJSON(JSON_URL, v);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String text = spinner.getSelectedItem().toString();
sharedPrefManager.addSpinner(text);
addListenerOnButton();
}
public void addListenerOnButton(){
getQuotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
Log.d("tag","selectId" + selectedId);
// find the radiobutton by returned id
radioButton = (RadioButton) rootView.findViewById(selectedId);
Log.d("tag","radioButton" + radioButton);
Log.d("tag","radioButton.getText()" + radioButton.getText());
//String radiovalue = ((RadioButton) rootView.findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
//sharedPrefManager.addRadio(radioButton.getText().toString());
Toast.makeText(getActivity().getApplication(), radioButton.getText(), Toast.LENGTH_LONG).show();
}
});
}
I did not try this but I hope this works.
Related
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_paternity"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:layout_marginTop="52dp"
android:id="#+id/paternity_ans" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/textView6"
android:text="Father"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_above="#+id/childblds"
android:layout_centerHorizontal="true" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="53dp"
android:id="#+id/textView5"
android:text="Child "
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/btn_paternity"
android:layout_toStartOf="#+id/btn_paternity" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:id="#+id/dadblds"
android:dropDownWidth="match_parent"
android:layout_toLeftOf="#+id/textView4"
android:layout_toStartOf="#+id/textView4"
android:layout_alignBottom="#+id/childblds"
android:layout_alignTop="#+id/childblds" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/childblds"
android:spinnerMode="dialog"
android:dropDownWidth="match_parent"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/momblds"
android:spinnerMode="dialog"
android:entries="#array/paternitybldtype"
android:dropDownWidth="match_parent"
android:layout_alignTop="#+id/dadblds"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_paternity"
android:layout_below="#+id/dadblds"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:gravity="center_horizontal"
android:text="Mother"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginLeft="9dp"
android:layout_marginStart="9dp"
android:layout_above="#+id/childblds"
android:layout_toRightOf="#+id/textView6"
android:layout_toEndOf="#+id/textView6" />
</RelativeLayout>
</LinearLayout>
Fragments code:
public class Paternitytest extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Some if else statement will be applied here by using String c, f and m
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String f = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String m = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
I have made some changes in your code so try this.
public class Paternitytest extends Fragment {
private String childSpinnerString, momSpinnerString, dadspinnerString;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo,
container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Some if else statement will be applied here by using String c, f and m
Log.d("Blood groups- ", "Child - " + childSpinnerString + " Mom - " + momSpinnerString + " Dad - " + dadspinnerString);
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
childSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
dadspinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
momSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Try onClickListener for your button:
btn_paternity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String mom = momblds.getSelectedItem().toString();
}
});
Hi I recently came to the android technology and in my app I have two buttons(one for showing movies-list and another one for showing countrieslist)
When I tap on the second button I want to display movies-list in spinner-list as in the first image bellow.
But according to my code, when I tap on the button first spinner is appearing and I selected any one item and set that to my button title but after selection spinner still visible B/w two button as like my second screen how can remove it.
How can I resolve this problem?
Please help me.
I want to show directly spinner-list when I tap on button.
xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button1Action"
android:text="CountiesList"/>
<Spinner
android:visibility="gone"
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainLayout"
android:layout_alignParentRight="true"
android:paddingRight="0dp"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button2Action"
android:text="MoviesList"/>
<Spinner
android:visibility="gone"
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainLayout"
android:layout_alignParentRight="true"
android:paddingRight="0dp"
android:layout_marginTop="5dp"
/>
</LinearLayout>
activity:-
public class spinnerListProgramatically extends AppCompatActivity{
String [] countriesList = {"india","usa","england"
};
String [] moviesList = {"fury","300 rise of an empire","troy"
};
Spinner spinner1,spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerlist_runtime);
}
public void Button1Action(View view){
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.VISIBLE);
}
public void Button2Action(View view){
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.VISIBLE);
}
}
---
Why not remove Spinner and have just a Button instead. Having a Spinner and Button both, makes no sense.
As per the image you have shown, you require PopupMenu:
public void Button2Action(View view){
showFilterPopup(view);
}
private void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
// Inflate the menu from xml
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
// Setup menu item selection
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.troy:
Toast.makeText(MainActivity.this, "troy", Toast.LENGTH_SHORT).show();
return true;
case R.id.rise:
Toast.makeText(MainActivity.this, "300 Rise of Empire", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
// Handle dismissal with: popup.setOnDismissListener(...);
// Show the menu
popup.show();
}
Your R.menu.popup will contain every item you need.
This approach will be useful when you have static set of data.
With few more steps you can make it dynamic. Hope this helps.
Use this it work
public void Button1Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.INVISIBLE);
spinner1.performClick();
}
public void Button2Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.INVISIBLE);
spinner2.performClick();
}
View this Screen
Can set this as the screen Display.
OK, Finally I knew what you really meant to say after a long discussion. I have provided you full source codes which are optimized and modified a little bits from yours.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:layout_marginTop="50dp"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button1Action"
android:text="CountiesList"/>
<Spinner
android:visibility="invisible"
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<Spinner
android:visibility="gone"
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button2Action"
android:text="MoviesList"/>
</LinearLayout>
Your Activity
public class spinnerListProgramatically extends AppCompatActivity {
Button button1, button2;
String [] countriesList = {"NONE","india","usa","england"};
String [] moviesList = {"NONE","fury","300 rise of an empire","troy" };
Spinner spinner1,spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Your other setup codes
spinner1 = (Spinner)findViewById(R.id.spinner1);
spinner2 = (Spinner)findViewById(R.id.spinner2);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
}
public void Button1Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.VISIBLE);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!=0) {
button1.setText(countriesList[position]);
spinner1.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void Button2Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.VISIBLE);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!=0) {
button2.setText(moviesList[position]);
spinner2.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
show Spinner-List item without tap on spinner
Spinner spi_type = findViewById(R.id.spi_type);
Button button = findViewById(R.id.button);
imgVIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// performClick() this method show Spinner-List item without tap on spinner
spi_type.performClick();
}
});
cant comment cause am not having that much reputation.. can u be more specific of what you want to achieve??
The problem was that
if(spinner2.getSelectedItem() == null)
is not null.. it by default tasks the first value
so use this code instead
if(spinner2.getSelectedItem() == "fury") {
// for checking user havent selected anything
spinner2.performClick();
}
if(spinner1.getSelectedItem() == "india") {
// for checking user havent selected anything
spinner1.performClick();
}
and for setting the title for button
public void Button1Action(View view){
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);
spinner1.setVisibility(View.VISIBLE);
String s = (String) spinner1.getSelectedItem();
spinner1.performClick();
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
button.setText(""+ spinner1.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
in the button onCLick
and also intialize the buttons on onCreate
button = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
and placing adaptor is not an issue..
find spinner and set adapetr before Button onClick method
I'm using a ListView with ArrayAdapter. There is a Button along with TextView in the listview.xml. I want to retrieve data from that TextView by Clicking over corresponding buttons.
My listview.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="90dp"
android:id="#+id/btConfirmfriend"
android:text="Confirm Friend"
/>
</RelativeLayout>
My PendingRequest Class is as follows:
public class PendingRequest extends AddFriend {
TextView tvPending;
Button btConfirmfriend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pendingrequest);
final String[] s= getIntent().getExtras().getStringArray("pending");
System.out.println(s[1]);
final ListAdapter adapter = new ArrayAdapter<String>(this,R.layout.listview,R.id.label,s);
final ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
final View inflatedView = getLayoutInflater().inflate(R.layout.listview, null);
btConfirmfriend = (Button) inflatedView.findViewById(R.id.btConfirmfriend);
btConfirmfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ServerConnection sc = new ServerConnection();
//here I want to retrieve the value from List
//System.out.println(s[adapter.]);
int status = sc.confirmRequest(s[listView.getSelectedItemPosition()]);
AlertDialog.Builder alert = new AlertDialog.Builder(PendingRequest.this);
if (status == 1) {
alert.setMessage("Friend has been Added");
alert.show();
} else {
alert.setMessage("Sorry for inconvinient!!Try Again");
alert.show();
}
}
});
}
}
My pendingrequest.xml file is:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#drawable/background"
android:layout_height="match_parent">
<Button
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="100dp"
android:background="#e9abab"
android:id="#+id/btSend"
android:text="Pending Requests"
/>
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
On clicking over the button nothing happening.onClick() method is not executing.Please help.
Since you need a click listener on a view inside your list item, you need to write your own adapter for that -
class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, String[] list) {
super(context, 0, list);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Lookup view for data population
TextView label = (TextView) convertView.findViewById(R.id.label);
Button btConfirmfriend = (Button) convertView.findViewById(R.id.btConfirmfriend);
// Populate the data into the template view using the data object
label.setText(item);
btConfirmfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getItem(position); //Get your selected text
}
});
return convertView;
}
}
And this is how you will set the adapter -
final CustomAdapter adapter = new CustomAdapter(this,s);
final ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
Im new in android programing, I want make calculating with multiple spinner that have value string and edit text. and proccess with button click and show on text view. please healp me to fix so i can learn next subject.
THx
My activity .java code:
public class MainActivity extends Activity {
private EditText jumlah;
String[] spinnerValues = { "Bakso", "Es Buah" };
String[] spinnerSubs = {"10000", "8000" };
int total_images[] = { R.drawable.bakso, R.drawable.es_buah };
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this, R.layout.menu_resto,
spinnerValues));
jumlah = (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
initButton();
}
private void initButton() {
button1.setOnClickListener(new OnClickListener() {
// this one performs an action when our button is clicked. it performs whatever is below
#Override
public void onClick(View v) {
// String strA = i want call the spinersubs value that chsoed. how ?
String strB = jumlah.getText().toString();
Double dblAnswer = doCalc(strA, strB);
TextView lblAnswer = (TextView) findViewById(R.id.lblAnswer);
// the disadvantage is that we can't do anything to it outside of this curly
// in general it's wasteful to use fields when you can suffice with local variable
String answer = String.valueOf(dblAnswer);
// we get our answer and turn it to a string.
lblAnswer.setText(answer);
// finally we set our result to the textView.
}
});
}
public double doCalc(String a, String b) {
double dblA = Double.parseDouble(a);
double dblB = Double.parseDouble(b);
return dblA * dblB;
}
class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.menu_resto, parent,
false);
TextView main_text = (TextView) mySpinner
.findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
Here my XML
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="X - Resto Menu"
android:textSize="30px" />
<Spinner
android:id="#+id/spinner_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100px"
android:drawSelectorOnTop="true" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="Jumlah Pesanan" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:onClick="#string/hitung"
android:text="#string/pesan" />
<TextView
android:id="#+id/lblAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="" />
You need to implement CustomOnItemSelectedListener for Spinner like
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and then set this Listener to your Spinner like
mySpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
and in Button click you'll get a Spinner selected value like
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner : "+ String.valueOf(mySpinner.getSelectedItem())
,Toast.LENGTH_SHORT).show();
}
});
Go to this for Tutorial
I've created a ListView with a list of items, each with their own delete button.
I've overridden the getView method in the ArrayAdapter and attached a handler to the delete button.
The problem is, the getView method is being called twice. On the second time, the v.findViewById(DeleteButton) call returns null. I've inspected the view and the ImageButton is there in the hierarchy, but the Id is 0.
Can anyone explain why this is happening please?
ManualFragment.java
public class ManualFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_manual, container, false);
Button addButton = (Button) view.findViewById(R.id.AddButton);
ListView listView = (ListView) view.findViewById(R.id.ListView);
final List<String> items = new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(), R.layout.list_item, R.id.TextItem, items) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ManualFragment.this.getLayoutInflater(savedInstanceState);
v = vi.inflate(R.layout.list_item, null);
}
TextView time = (TextView) v.findViewById(R.id.TextItem);
time.setText(items.get(position));
ImageButton delete = (ImageButton) v
.findViewById(R.id.DeleteButton);
//THIS LINE THROWS A NULLREF ON SECOND CALL
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageButton deleteButton = (ImageButton) v;
items.remove(deleteButton.getId());
notifyDataSetChanged();
}
});
delete.setId(position);
return v;
}
};
listView.setAdapter(adapter);
final EditText addText = (EditText) view.findViewById(R.id.AddText);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String value = addText.getText().toString();
if (!"".equals(value)) {
items.add(value);
adapter.notifyDataSetChanged();
addText.setText("");
}
}
});
return view;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:focusable="false" >
<TextView
android:id="#+id/TextItem"
android:layout_width="267dp"
android:layout_height="match_parent"
android:layout_weight="0.89"
android:focusable="false"
android:gravity="center_vertical"
android:text="Item"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:id="#+id/DeleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:focusable="false"
android:src="#drawable/delete" />
</LinearLayout>
</LinearLayout>
You're setting it with
delete.setId(position)
I think you wanted to tag the buttojn with the position
delete.setTag(position)