(SOLVED) -- Removed layout params on each view ---
I am new to Android and I am trying to add rows in a TableLayout from the items that I entered in text fields.
(EDITED) Here's my layout for this Fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:tag="contacts">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/contactName"
android:hint="Name"
android:paddingTop="5dip" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/contactRelationship"
android:hint="Relationship"
android:paddingTop="5dip" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/contactAddress"
android:hint="Address"
android:paddingTop="5dip" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/contactPhoneNo"
android:hint="Phone Number"
android:paddingTop="5dip" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/contactPhoneTypeSpinner"
android:layout_toEndOf="#+id/contactPhoneNo"
android:layout_toRightOf="#+id/contactPhoneNo"
android:paddingTop="5dip" />
</RelativeLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="107dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactSpecialNotes"
android:paddingTop="5dip"
android:hint="Write special notes here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContact" />
<TableLayout
android:id="#+id/contactsTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dip"></TableLayout>
</LinearLayout>
</ScrollView>
(EDITED)Here's the code for this Fragment:
public static class ContactsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_contacts,
container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Spinner phoneTypeSpinner = (Spinner) this.getView().findViewById(R.id.contactPhoneTypeSpinner);
Button contactButton = (Button) this.getView().findViewById(R.id.addContact);
final TableLayout tableLayout = (TableLayout) this.getView().findViewById(R.id.contactsTableLayout);
final EditText txtContactName = (EditText) this.getView().findViewById(R.id.contactName);
final EditText txtContactRelationship = (EditText) this.getView().findViewById(R.id.contactRelationship);
final EditText txtContactAddress = (EditText) this.getView().findViewById(R.id.contactAddress);
final EditText txtContactPhoneNo = (EditText) this.getView().findViewById(R.id.contactPhoneNo);
Spinner contactPhoneTypeSpinner = (Spinner) this.getView().findViewById(R.id.contactPhoneTypeSpinner);
EmployeeDataSource datasource = new EmployeeDataSource(getActivity());
datasource.open();
//--- Gender Spinner ---
List<PhoneType> list = datasource.getPhoneTypeList();
ArrayAdapter<PhoneType> adapter = new ArrayAdapter<PhoneType>(getActivity(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
phoneTypeSpinner.setAdapter(adapter);
phoneTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
contactButton.setOnClickListener(new View.OnClickListener() {
int rowId = 0;
#Override
public void onClick(View v) {
TableRow tableRow = new TableRow(getActivity().getApplicationContext());
tableRow.setId(rowId++);
tableRow.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
TextView tvContactName = new TextView(getActivity().getApplicationContext());
tvContactName.setText(txtContactName.getText().toString());
tvContactName.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvContactName);
TextView tvRelationship = new TextView(getActivity().getApplicationContext());
tvRelationship.setText(txtContactRelationship.getText().toString());
//tvRelationship.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.FILL_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvRelationship);
TextView tvContactNo = new TextView(getActivity().getApplicationContext());
tvContactNo.setText(txtContactPhoneNo.getText().toString());
//tvContactNo.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.FILL_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvContactNo);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
}
}
I could see in the debugger that the values from my views were added in my tableRow but I don't see the table appearing in my screen, what am I missing or doing wrong?
Any help would be greatly appreciated.
Thanks!
I guess the height of screen is increased. Try using Scrollview on top of this layout.
I think you have to change RelativeLayout property android:height="wrap_content" instead of android:height="fill_parent" and also do for TableLayout
May this work for you...
Try this:
Edited:
public static class ContactsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_contacts,
container, false);
Spinner phoneTypeSpinner = (Spinner) rootView.findViewById(R.id.contactPhoneTypeSpinner);
Button contactButton = (Button) rootView.findViewById(R.id.addContact);
final TableLayout tableLayout = (TableLayout) rootView.findViewById(R.id.contactsTableLayout);
final EditText txtContactName = (EditText) rootView.findViewById(R.id.contactName);
final EditText txtContactRelationship = (EditText) rootView.findViewById(R.id.contactRelationship);
final EditText txtContactAddress = (EditText) rootView.findViewById(R.id.contactAddress);
final EditText txtContactPhoneNo = (EditText) rootView.findViewById(R.id.contactPhoneNo);
Spinner contactPhoneTypeSpinner = (Spinner) rootView.findViewById(R.id.contactPhoneTypeSpinner);
EmployeeDataSource datasource = new EmployeeDataSource(getActivity());
datasource.open();
//--- Gender Spinner ---
List<PhoneType> list = datasource.getPhoneTypeList();
ArrayAdapter<PhoneType> adapter = new ArrayAdapter<PhoneType>(getActivity(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
phoneTypeSpinner.setAdapter(adapter);
phoneTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
contactButton.setOnClickListener(new View.OnClickListener() {
int rowId = 0;
#Override
public void onClick(View v) {
TableRow tableRow = new TableRow(getActivity().getApplicationContext());
tableRow.setId(rowId++);
TextView tvContactName = new TextView(getActivity().getApplicationContext());
tvContactName.setText(txtContactName.getText().toString());
tableRow.addView(tvContactName);
TextView tvRelationship = new TextView(getActivity().getApplicationContext());
tvRelationship.setText(txtContactRelationship.getText().toString());
tableRow.addView(tvRelationship);
TextView tvContactNo = new TextView(getActivity().getApplicationContext());
tvContactNo.setText(txtContactPhoneNo.getText().toString());
tableRow.addView(tvContactNo);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Related
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.
Hello i want to add a autocompletetextview in popup. Such that when i type city name it should come as suggestion.. Is this possible in PopUpWindow. Was trying this.
View addresspopupView =addresslayoutInflater.inflate(R.layout.addressinput, null);
AutoCompleteTextView city = (AutoCompleteTextView) addresspopupView.findViewById(R.id.city);
String[] CITY ={"Mumbai", "Ahemadabad", "Kolkata", "Chennai", "Thane"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, CITY);
city.setAdapter(adapter);
PopupWindow addresspopupWindow = new PopupWindow(addresspopupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
addresspopupWindow.showAtLocation(addresspopupView, Gravity.CENTER, 0, 0);
logcat
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#424c2b38 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:706)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:234)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:153)
at android.view.Window$LocalWindowManager.addView(Window.java:559)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1013)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:922)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:595)
at android.widget.AutoCompleteTextView.showDropDown(AutoCompleteTextView.java:1093)
at android.widget.AutoCompleteTextView.updateDropDownForFilter(AutoCompleteTextView.java:956)
at android.widget.AutoCompleteTextView.onFilterComplete(AutoCompleteTextView.java:938)
at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:285)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Here is my addressInput.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:elevation="#dimen/dimen_4dp"
android:orientation="vertical"
android:padding="#dimen/dimen_4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/addressPopUptitle"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_horizontal"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/addressLine1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:hint="Address Line 1" />
<EditText
android:id="#+id/addressLine2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Address Line 2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/landMark"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:hint="Landmark" />
<EditText
android:id="#+id/locality"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Locality" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!--<EditText-->
<!--android:id="#+id/city"-->
<!--android:layout_width="0dp"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_marginRight="2dp"-->
<!--android:layout_weight="1"-->
<!--android:hint="City" />-->
<AutoCompleteTextView
android:id="#+id/city"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:hint="City" />
<EditText
android:id="#+id/pin"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="PIN" />
</LinearLayout>
<EditText
android:id="#+id/state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="State" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/summitAddrPopUp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SUMMIT"
android:textColor="#color/green" />
<Button
android:id="#+id/cancelAddrPopUp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CANCEL"
android:textColor="#color/red" />
</LinearLayout>
OnCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d("ClientBookingScreen", "Inside OnCreateView of ClientBookingScreen");
rootView = inflater.inflate(R.layout.bookingrequest, container, false);
intialize(rootView);
intialSetUp();
loadconfigs();
initializeAddressPopUp();
settingClickListener();
return rootView;
}
The methods in onCreateView() :
private void intialize(View rootView) {
//Setting toolbar
myCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
pickUpDate = (TextView) rootView.findViewById(R.id.pickUpDateInput);
pickUpTime = (TextView) rootView.findViewById(R.id.pickUpTimeInput);
returnDate = (TextView) rootView.findViewById(R.id.returnDateInput);
returnTime = (TextView) rootView.findViewById(R.id.returnTimeInput);
pickUpAddress = (TextView) rootView.findViewById(R.id.pickUpAddressInput);
pickUpAddress.setMovementMethod(new ScrollingMovementMethod());
returnAddress = (TextView) rootView.findViewById(R.id.returnAddressInput);
returnAddress.setMovementMethod(new ScrollingMovementMethod());
description = (EditText) rootView.findViewById(R.id.descriptionInput);
description.setMovementMethod(new ScrollingMovementMethod());
book = (Button) rootView.findViewById(R.id.bookButton);
//Spinners
dutyType = (Spinner) rootView.findViewById(R.id.dutyTypeInput);
vehicleCategory = (Spinner) rootView.findViewById(R.id.vehicleCategoryInput);
vehicleType = (Spinner) rootView.findViewById(R.id.vehicleTypeInput);
//creating reflection of spinner to limit his height
createReflectionOfSpinner(dutyType);
createReflectionOfSpinner(vehicleCategory);
createReflectionOfSpinner(vehicleType);
isDrawerOpened = false;
//CheckBox
btcCheckBox = (CheckBox) rootView.findViewById(R.id.btccheckBox);
}
private void loadconfigs() {
categoryMap = new HashMap<String, ArrayList<String>>();
guestAddressMap = new HashMap<String, String>();
guestaddressLabel = new ArrayList<String>();
categoryName = new ArrayList<String>();
dutyTypeName = new ArrayList<String>();
new LoadConfigs().execute();
}
private void initializeAddressPopUp() {
//Address Input Popup
addresslayoutInflater = (LayoutInflater) getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
addresspopupView = addresslayoutInflater.inflate(R.layout.addressinput, null);
addressLine1 = (EditText) addresspopupView.findViewById(R.id.addressLine1);
addressLine2 = (EditText) addresspopupView.findViewById(R.id.addressLine2);
landmark = (EditText) addresspopupView.findViewById(R.id.landMark);
locality = (EditText) addresspopupView.findViewById(R.id.locality);
city = (AutoCompleteTextView) addresspopupView.findViewById(R.id.city);
String[] CITY ={"Mumbai", "Ahemadabad", "Kolkata", "Chennai", "Thane"};
// AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.actv_country);
ArrayAdapter adapter = new ArrayAdapter(addresspopupView.getContext(), android.R.layout.simple_dropdown_item_1line, CITY);
city.setAdapter(adapter);
pin = (EditText) addresspopupView.findViewById(R.id.pin);
state = (EditText) addresspopupView.findViewById(R.id.state);
title = (TextView) addresspopupView.findViewById(R.id.addressPopUptitle);
addressSummit = (Button) addresspopupView.findViewById(R.id.summitAddrPopUp);
addressCancel = (Button) addresspopupView.findViewById(R.id.cancelAddrPopUp);
//AddressLabelList Popoup
addressLabelInflater = (LayoutInflater) getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listOfaddressTitle = addressLabelInflater.inflate(R.layout.addresslabellist, null);
addressLabelListView = (ListView) listOfaddressTitle.findViewById(R.id.addressLabelListView);
selectedListok = (Button) listOfaddressTitle.findViewById(R.id.addressLabelListButton);
}
private void settingClickListener() {
pickUpDate.setOnClickListener(this);
pickUpTime.setOnClickListener(this);
returnDate.setOnClickListener(this);
returnTime.setOnClickListener(this);
pickUpAddress.setOnClickListener(this);
returnAddress.setOnClickListener(this);
addressSummit.setOnClickListener(this);
addressCancel.setOnClickListener(this);
book.setOnClickListener(this);
btcCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(getActivity(),
"CHECKED", Toast.LENGTH_LONG).show();
isBTC = true;
} else {
Toast.makeText(getActivity(),
"UNCHECKED", Toast.LENGTH_LONG).show();
isBTC = false;
}
}
});
//on item listener for Spinners
dutyType.setOnItemSelectedListener(this);
vehicleCategory.setOnItemSelectedListener(this);
vehicleType.setOnItemSelectedListener(this);
}
Any suggesstion please...
Let you try this,
Change your onCreateView codings as like below.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View addresspopupView =inflater.inflate(R.layout.addressinput, container, false);
AutoCompleteTextView city = (AutoCompleteTextView) addresspopupView.findViewById(R.id.city);
String[] CITY ={"Mumbai", "Ahemadabad", "Kolkata", "Chennai", "Thane"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, CITY);
city.setAdapter(adapter);
PopupWindow addresspopupWindow = new PopupWindow(addresspopupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
addresspopupWindow.showAtLocation(addresspopupView, Gravity.CENTER, 0, 0);
return addresspopupView;
}
EDITED :
Copy paste these lines in your oncreateView method like this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d("ClientBookingScreen", "Inside OnCreateView of ClientBookingScreen");
rootView = inflater.inflate(R.layout.bookingrequest, container, false);
AutoCompleteTextView city = (AutoCompleteTextView) rootView.findViewById(R.id.city);
String[] CITY ={"Mumbai", "Ahemadabad", "Kolkata", "Chennai", "Thane"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, CITY);
city.setAdapter(adapter);
intialize(rootView);
intialSetUp();
loadconfigs();
initializeAddressPopUp();
settingClickListener();
return rootView;
}
May be the way you inflate the layout is wrong. Try the above code and let me know.
In my fragment, I want each custom item in my listview to look as follows:
Name
SetsXReps
[][][][][] ---> array of textviews
[][][][][] ---> array of checkboxes
The number of textviews and checkboxes depends upon the item in the adapter, so I need to create that part dynamically. I am having trouble adding these elements dynamically to my relativelayout that I partially define in my xml. Here is my fragment class followed by my xml for the custom list item. The id for the layout is list_item_exercise_in_workout.
public class WorkoutFragment extends Fragment
{
public static final String EXTRA_ALREADYCREATED_ID = "shake2lift.nickdelnano.com";
private ExAdapter adapter;
private ListView listView;
private ArrayList<Set> sets;
private Workout w;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID workoutId = (UUID) getArguments().getSerializable(EXTRA_ALREADYCREATED_ID);
w = WorkoutMASTER.get(getActivity()).getWorkout(workoutId);
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent,Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_workout, parent, false);
adapter = new ExAdapter(getActivity(), R.layout.fragment_create_workout, R.id.list, sets);
listView.setAdapter(adapter);
return v;
}
public static WorkoutFragment newInstance(UUID workoutId)
{
Bundle args = new Bundle();
args.putSerializable(EXTRA_ALREADYCREATED_ID, workoutId);
WorkoutFragment fragment = new WorkoutFragment();
fragment.setArguments(args);
return fragment;
}
private class ExAdapter extends ArrayAdapter<Set>
{
public ExAdapter(Context c, int resource, int textViewResourceId, ArrayList<Set> sets ) {
super(c, 0, sets);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
//if we werent given a view, inflate one
if(convertView == null)
{
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_exercise_in_workout, null);
}
Set s = getItem(position);
//RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
// RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );
TextView name = (TextView) convertView.findViewById(R.id.exName);
name.setText(s.getName());
TextView setsReps = (TextView) convertView.findViewById(R.id.setsXreps);
setsReps.setText(s.getSets() + "X" + s.getReps());
CheckBox[] checkBoxes = new CheckBox[s.getSetsInt()];
EditText[] weightBoxes = new EditText[s.getSetsInt()];
//initialize weightBoxes's text to the inputted weight
for(int i = 0; i < weightBoxes.length; i++)
{
//code to add dynamically here
}
return convertView;
}
}
}
and my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativeLayoutEx"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:id="#+id/exName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="SetsXReps"
android:id="#+id/setsXreps"
android:layout_below="#id/exName"
android:layout_alignParentLeft="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2"
android:layout_below="#+id/setsXreps"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="112dp" />
I appreciate any help or advice.
You need to first get a pointer to your RelativeLayout like this
RelativeLayout container = (RelativeLayout) view.findViewById(R.id.relativeLayoutEx);
Then in your for loop, create the Text Boxes (and Check Boxes) dynamically and add them to the layout:
TextView text = new TextView(getActivity());
text.setText("Hello");
container.addView(text);
I have created dynamically Table Layout. However, my Title Row pushes downward when other rows are dynamically created. I want to make the title stay at the top.
The XML code:
<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"
tools:context=".FirstScreen"
android:orientation="vertical"
android:background="#color/white" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:text="Shopping Cart"
android:textColor="#898989"
android:textSize="17dp"
android:textStyle="bold" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/displayLinear"
android:layout_marginLeft="10dp"
android:background="#ffffff"
android:orientation="vertical" >
</TableLayout>
<Button
android:id="#+id/second"
style="#style/btnStyleShakespeare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="80dp"
android:layout_marginTop="10dp"
android:text="Checkout"
android:textColor="#ffffff" />
<Button
android:id="#+id/scanMore"
style="#style/btnStyleShakespeare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="80dp"
android:layout_marginTop="5dp"
android:text="Scan More"
android:textColor="#ffffff" />
</LinearLayout>
This is my dynamically created code.
package info.androidhive.slidingmenu;
public class ScreenFirstFragment extends Fragment {
public ScreenFirstFragment(){}
public static double pFinalPrice;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_firstscreen, container, false);
//final LinearLayout lm = (LinearLayout) rootView.findViewById(R.id.linearMain);
final Button secondBtn = (Button) rootView.findViewById(R.id.second);
final Button scanMoreBtn = (Button) rootView.findViewById(R.id.scanMore);
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
final Controller aController = (Controller) getActivity().getApplicationContext();
/******* Create view elements dynamically and show on activity ******/
//Product arraylist size
int ProductsSize = aController.getProductsArraylistSize();
/******** Dynamically create view elements - Start **********/
TableLayout ll = (TableLayout) rootView.findViewById(R.id.displayLinear);
ll.setStretchAllColumns(true);
ll.setShrinkAllColumns(true);
TableRow rowProdLabels = new TableRow(this.getActivity());
// Product column
TextView prodLabel = new TextView(this.getActivity());
prodLabel.setText("PRODUCT");
prodLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(prodLabel);
// Price column
TextView priceLabel = new TextView(this.getActivity());
priceLabel.setText("PRICE");
priceLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(priceLabel);
// Quantity column
TextView quantityLabel = new TextView(this.getActivity());
quantityLabel.setText("Quantity");
quantityLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(quantityLabel);
// Total column
TextView totalLabel = new TextView(this.getActivity());
totalLabel.setText("Total Price");
totalLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(totalLabel);
ll.addView(rowProdLabels);
for(int j=0;j< ProductsSize;j++)
{
// Get probuct data from product data arraylist
String pName = aController.getProducts(j).getProductName();
double pPrice = aController.getProducts(j).getProductPrice();
int pQuantity = aController.getProducts(j).getProductQuantity();
double pTotalPrice = pPrice * pQuantity;
TableRow row= new TableRow(this.getActivity());
TextView product = new TextView(this.getActivity());
product.setText(pName+" ");
//Add textView to LinearLayout
row.addView(product);
TextView price = new TextView(this.getActivity());
price.setText("RM "+pPrice+" ");
//Add textView to LinearLayout
row.addView(price);
TextView quantity = new TextView(this.getActivity());
quantity.setText(pQuantity+" ");
//Add textView to LinearLayout
row.addView(quantity);
TextView totalprice = new TextView(this.getActivity());
totalprice.setText(String.format("RM %.2f",pTotalPrice));
//Add textView to LinearLayout
row.addView(totalprice);
//Update final price
pFinalPrice += pTotalPrice;
ll.addView(row,j);
}
/******** Dynamically create view elements - End **********/
secondBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FragmentTransaction mFragmentTransaction = getFragmentManager().beginTransaction();
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
mFragmentTransaction.replace(R.id.frame_container, new ScreenSecondFragment(), "Cart");
mFragmentTransaction.commit();
}
});
scanMoreBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FragmentTransaction mFragmentTransaction = getFragmentManager().beginTransaction();
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
mFragmentTransaction.replace(R.id.frame_container, new ScanFragment(), "Scan Product");
mFragmentTransaction.commit();
}
});
return rootView;
}
}
I'm trying to create a DialogFragment with a ListView and some Buttons. I'm declaring all of them i the layout file and the buttons are working fine but the ListView is null when i use fineViewByID().
Here's my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/category_picker"
android:layout_gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/lvCategorys"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.5" >
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="bottom"
android:layout_weight="0.5"
android:orientation="horizontal" >
<Button
android:id="#+id/btnAddNew"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/cpf_btnAddNew" />
<Button
android:id="#+id/btnConfig"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/cpf_btnConfig" />
</LinearLayout>
</LinearLayout>
And here is the FragmentDialog:
package com.example.spendo.fragments;
imports....
public class CategoryPickerFragment extends DialogFragment implements OnItemClickListener{
private CategoryGroup categoryGroup;
private ListView lvCategorys;
private ArrayAdapter<String> lvAdapter;
private Button btnAddNew, btnConfig;
public CategoryPickerFragment() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_picker, container);
getDialog().setTitle("Hello");
categoryGroup = General.getActiveCategoryGroup(this.getActivity());
System.out.println(categoryGroup);
btnAddNew = (Button) this.getActivity().findViewById(R.id.btnAddNew);
btnConfig = (Button) this.getActivity().findViewById(R.id.btnConfig);
lvCategorys = (ListView) this.getActivity().findViewById(R.id.lvCategorys);
if(lvCategorys == null){ //this returns "lvCategorys is null"
System.out.println("lvCategorys is null");
}else{
System.out.println(lvCategorys + " is not null");
}
lvAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1, categoryGroup.getNameArray());
System.out.println(lvAdapter);
ArrayList<String> nameArray = categoryGroup.getNameArray();
lvAdapter.clear();
for(int i = 0; i < nameArray.size(); i++){
lvAdapter.add((String) nameArray.get(i));
}
lvAdapter.notifyDataSetChanged();
lvCategorys.setAdapter(lvAdapter);
return view;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Does anyone see my problem. (I'm quite new to android, altho i've done some java in the past).
//Sverker
I think you need to replace
btnAddNew = (Button) this.getActivity().findViewById(R.id.btnAddNew);
btnConfig = (Button) this.getActivity().findViewById(R.id.btnConfig);
lvCategorys = (ListView) this.getActivity().findViewById(R.id.lvCategorys);
with
btnAddNew = (Button) view.findViewById(R.id.btnAddNew);
btnConfig = (Button) view.findViewById(R.id.btnConfig);
lvCategorys = (ListView) view.findViewById(R.id.lvCategorys);