I want to dynamically add text views in my app depending on the information I receive from the database. I am taking a reference to the linear layout and then instantiating text views in a loop, setting LayoutParams to them and then adding them to the the layout all this is done inside a static inner fragment class. I have gone through almost every solution and I am doing the same thing as others did but when I run my app on device I don't see the dynamically added views. Please help me solve this issue.
Here is a copy of my code:
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
final int PICKFILE_RESULT_CODE = 1;
String FilePath="";
UploadFileAsync u;
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
// TextView textView = (TextView) rootView.findViewById(R.id.section_label);
// textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
switch (sectionNumber){
case 1: rootView = inflater.inflate(R.layout.fragment_faculty_home_info, container, false);
facultyInfoFragment(rootView);
break;
case 2: rootView = inflater.inflate(R.layout.fragment_faculty_home_exam, container, false);
facultyExamFragment(rootView);
break;
case 3: rootView = inflater.inflate(R.layout.fragment_faculty_home_info, container, false);
facultyEventsFragment(rootView);
break;
default: rootView = inflater.inflate(R.layout.fragment_faculty_home_info, container, false);
}
return rootView;
}
public void facultyInfoFragment(View rootView){
TextView facultyInfoName = (TextView)rootView.findViewById(R.id.faculty_info_name_view);
facultyInfoName.setText("Ravi Singh");
TextView facultyInfoID = (TextView)rootView.findViewById(R.id.faculty_info_ID_view);
facultyInfoID.setText("12345");
TextView facultyInfoDept = (TextView)rootView.findViewById(R.id.faculty_info_dept_view);
facultyInfoDept.setText("CSE");
Button facultyInfoCaddButton = (Button)rootView.findViewById(R.id.faculty_info_cADD_button);
Button facultyInfoCdeleteButton = (Button)rootView.findViewById(R.id.faculty_info_cDelete_button);
EditText facultyInfoCIDField = (EditText)rootView.findViewById(R.id.faculty_info_cID_field);
EditText facultyInfoCnameField = (EditText)rootView.findViewById(R.id.faculty_info_cname_field);
if (facultyInfoCIDField.getText().toString() != null && facultyInfoCnameField.getText().toString() != null){
facultyInfoCaddButton.setEnabled(true);
facultyInfoCdeleteButton.setEnabled(true);
}
else{
facultyInfoCaddButton.setEnabled(false);
facultyInfoCdeleteButton.setEnabled(false);
}
facultyInfoCaddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
facultyInfoCdeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// this is the part where I dynamically try to add views
LinearLayout facultyInfoLayout = (LinearLayout)rootView.findViewById(R.id.faculty_info_layout);
int numberOfCourses = super.getArguments().getInt(SignupActivity.courses);// no. of courses returned from database
TextView coursesTextView[] = new TextView[numberOfCourses];
for (int i = 0; i < numberOfCourses; i++){
coursesTextView[i] = new TextView(getContext());
coursesTextView[i].setText("CSE1212 RDBMS"); //enter the course ID and course name returned from database
coursesTextView[i].setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
facultyInfoLayout.addView(coursesTextView[i]);
}
return;
}
public void facultyExamFragment(View rootView){
Button uploadExamScheduleButton = (Button)rootView.findViewById(R.id.faculty_exam_upload_button);
uploadExamScheduleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
FilePath = data.getData().getPath();
FilePath=FilePath.split(":")[1];
u=new UploadFileAsync(FilePath);
u.execute("");
}
break;
}
}
public static void facultyEventsFragment(View rootView){
}
}
Set orientation for your parent Linearlayout to which you are adding your textviews.
LinearLayout facultyInfoLayout = (LinearLayout)rootView.findViewById(R.id.faculty_info_layout);
facultyInfoLayout.setOrientation(LinearLayout.VERTICAL);
Remove LinearLayoutCompact instead use only LinearLayout in layout params
coursesTextView[i].setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
This is my xml part
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/parent"
android:layout_height="wrap_content"
android:orientation="vertical">
This is my java part
LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
TextView coursesTextView[] = new TextView[5];
for (int i = 0; i < 5; i++){
coursesTextView[i] = new TextView(this);
coursesTextView[i].setText("CSE1212 RDBMS"); //enter the course ID and course name returned from database
coursesTextView[i].setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
parent.addView(coursesTextView[i]);
}
And this adds 5 textviews one after the other
change this line
coursesTextView[i].setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
to . May be that is problem.and also set text color , may be same color not display textview.
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setTextColor(mHostActivity.getResources().getColor(R.color.orange));
Related
I had a fragment, in which first I check for availability for internet connection. If its available its fine, otherwise, I want to refresh the page by clicking on retry button. The problem which comes is, I am not able to refresh the fragment
This is my fragment code.
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homework, container, false);
listView = rootView.findViewById(R.id.home_list);
adapter = new HomeWorkAdapter(getContext(), R.layout.home_single, arrayList);
listView.setAdapter(adapter);
cal = rootView.findViewById(R.id.date_select);
boolean x = handleNetworkConnection();
if (x == true) {
methodListener();
SharedPreferences preferences = getActivity().getSharedPreferences("user_login", Context.MODE_PRIVATE);
HashMap<String, String> map = new HashMap<>();
map.put("school_id", preferences.getString("school_id", ""));
map.put("class", preferences.getString("classes", ""));
map.put("sec", "homeera");
defaultfetch(map);
}
else
{
final LinearLayout ll = new LinearLayout(getActivity());
TextView textView = new TextView(getActivity());
Button button = new Button(getActivity());
ImageView image = new ImageView(getActivity());
ll.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
ll.setBackgroundColor(Color.parseColor("#ecf0f1"));
image.setImageResource(R.drawable.errorsq);
button.setBackgroundColor(Color.parseColor("#02b48a"));
button.setText("Try Again");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(getActivity().).attach(this).commit();
*/
}
});
ll.addView(textView);
ll.addView(image);
ll.addView(button);
ll.setOrientation(LinearLayout.VERTICAL);
View rootview = ll;
return rootview;
}
return rootView;
}
In this code, I had applied a way to refresh the fragment, but the problem is that after refreshing UI comes blank. Nothing is there on the screen.
You should not refresh the fragment but refresh the list when you get an internet connection.
Since your method handleNetworkConnection() returns synchronously, you could organize the code as follows:
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homework, container, false);
listView = rootView.findViewById(R.id.home_list);
adapter = new HomeWorkAdapter(getContext(), R.layout.home_single, arrayList);
listView.setAdapter(adapter);
cal = rootView.findViewById(R.id.date_select);
prepareList();
}
void prepareList() {
boolean x = handleNetworkConnection();
if (x == true) {
// same code as now, load the list content and display it
} else {
// same code as now except the click listener:
public void onClick(View view) {
prepareList();
}
//
}
}
I have RadioButton and Checkboxes that are added programatically inside Fragments under ViewPager. Here's how I added the RadioButton/Checkboxes.
public class TeaserExam extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get all the checked values here
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1,questionList.get(position).getId(),
questionList.get(position).getQuestion(),questionList.get(position).getQuestionType(),questionList.get(position).getChoices());
}
}
public static class PlaceholderFragment extends Fragment {
public static PlaceholderFragment newInstance(int number, int questionID, String question, int questionType, List<Choices> choices) {
PlaceholderFragment fragment = new PlaceholderFragment();
ArrayList<Integer> choicesID = new ArrayList<>();
ArrayList<String> choicesLabel = new ArrayList<>();
for (int i = 0; i < choices.size(); i++){
choicesID.add(i,choices.get(i).getId());
choicesLabel.add(i,choices.get(i).getLabel());
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, number);
args.putInt("questionID", questionID);
args.putInt("questionType", questionType);
args.putInt("choicesSize", choices.size());
ParcelableChoices parcelableChoices = new ParcelableChoices(choicesID,choicesLabel);
args.putParcelable("parcelableChoices", parcelableChoices);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_teaser_exam, container, false);
int questionID = getArguments().getInt("questionID");
int questionType = getArguments().getInt("questionType");
int choicesSize = getArguments().getInt("choicesSize");
ParcelableChoices parcelableChoices = getArguments().getParcelable("parcelableChoices");
LinearLayout ll_choices = (LinearLayout)rootView.findViewById(R.id.ll_choices);
ArrayList<Integer> choicesIDs = parcelableChoices.getId();
ArrayList<String> choicesLabels = parcelableChoices.getLabel();
if (questionType == 2){
//checkboxes
for (int i = 0; i < choicesSize; i++){
CheckBox myChoices = new CheckBox(getContext());
myChoices.setId(choicesIDs.get(i));
myChoices.setText(choicesLabels.get(i));
myChoices.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll_choices.addView(myChoices);
}
}else{
//radio group
RadioGroup rg = new RadioGroup(getContext());
rg.setOrientation(RadioGroup.VERTICAL);
for (int i = 0; i < choicesSize; i++){
RadioButton myChoices = new RadioButton(getContext());
myChoices.setId(choicesIDs.get(i));
myChoices.setText(choicesLabels.get(i));
myChoices.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
rg.addView(myChoices);
}
ll_choices.addView(rg);
}
return rootView;
}
}
}
The problem is right now I have no idea how to retrieve the checked radiobutton/checkboxes value. I want to get all the checked values when I click on a button which will appear only at the last page.
Since all the views are added to ll_choices, is there any way I can get the id and values of all views added under ll_choices?
The direct answer to your question is to keep a reference to the controls which you add programmatically. You can do this with member field variables rather than local variables.
Since you are adding a list of dynamic views, you should learn about ListView or RecyclerView. These are designed for adding dynamic views. I also suggest that you separate the RadioButtons and the CheckBoxes into two separate fragments. Then the activity decides which fragment to show.
Currently your variables are local to onCreate inside the fragment.
Make them class fields inside the fragment class, initialize them inside onCreate and then they will be available inside the whole fragment class
I have two fragments. The content of the second fragment depends on the user input of the first one.
So if the user puts a 0 in the first fragment, I want to show the first LinearLayout, if he puts 1 I want to show the second LinearLayout. Both LinearLayouts are in the same xml-file.
My code works (see below). However it only works ONCE. On the first call it does everything it is supposed to. But on all the following calls, the setVisibility command does not seem to work anymore (at the same time the console prints work without problem).
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position+1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.out.println("test"+unitOfMeasurement);
View rootView;
View unitView = inflater.inflate(R.layout.fragment_personalization_unit, container, false);
View boundaryView = inflater.inflate(R.layout.fragment_personalization_low, container, false);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
rootView = unitView;
break;
case 2:
rootView = boundaryView;
break;
default:
rootView = inflater.inflate(R.layout.fragment_personalization_dummy, container, false);
}
setupUnitClickListener(unitView, boundaryView);
setupInputFields(boundaryView);
return rootView;
}
private void setupInputFields(View view) {
view.findViewById(R.id.fragment_personalization_mmol_low_picker).setVisibility(View.VISIBLE);
view.findViewById(R.id.fragment_personalization_mgdl_low_picker).setVisibility(View.VISIBLE);
if(unitOfMeasurement==1) {
view.findViewById(R.id.fragment_personalization_mmol_low_picker).setVisibility(View.GONE);
System.out.println("mmol gone");
} else if(unitOfMeasurement==0) {
view.findViewById(R.id.fragment_personalization_mgdl_low_picker).setVisibility(View.GONE);
System.out.println("mgdl gone");
}
/*switch(unitOfMeasurement) {
case 0: //it's mmol/l
view.findViewById(R.id.fragment_personalization_mgdl_low_picker).setVisibility(View.VISIBLE);
final EditText val1 = (EditText) view.findViewById(R.id.fragment_personalization_low_mmol_value1);
final EditText val2 = (EditText) view.findViewById(R.id.fragment_personalization_low_mmol_value2);
System.out.println("testtt");
break;
case 1: //it's mg/dl
LinearLayout lin = (LinearLayout) view.findViewById(R.id.fragment_personalization_mgdl_low_picker);
lin.setVisibility(View.VISIBLE);
final EditText val3 = (EditText) view.findViewById(R.id.fragment_personalization_low_mgdl_value1);
System.out.println("gettinasd here"+unitOfMeasurement);
break;
}*/
}
private void setupUnitClickListener(View view, final View boundaryView) {
final TextView mmoll = (TextView) view.findViewById(R.id.fragment_personalization_unit_option1);
final TextView mgdl = (TextView) view.findViewById(R.id.fragment_personalization_unit_option2);
if(unitOfMeasurement==0) { //using mmol
mmoll.setTextColor(Color.parseColor("#920d0a"));
mmoll.setBackgroundColor(Color.parseColor("#44525252"));
mgdl.setTextColor(Color.parseColor("#525252"));
mgdl.setBackgroundColor(Color.parseColor("#ffffffff"));
} else { //using mg/dl
mgdl.setTextColor(Color.parseColor("#920d0a"));
mgdl.setBackgroundColor(Color.parseColor("#44525252"));
mmoll.setTextColor(Color.parseColor("#525252"));
mmoll.setBackgroundColor(Color.parseColor("#ffffffff"));
}
mmoll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mmoll.setTextColor(Color.parseColor("#920d0a"));
mmoll.setBackgroundColor(Color.parseColor("#44525252"));
mgdl.setTextColor(Color.parseColor("#525252"));
mgdl.setBackgroundColor(Color.parseColor("#ffffffff"));
unitOfMeasurement = 0;
}
});
mgdl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mgdl.setTextColor(Color.parseColor("#920d0a"));
mgdl.setBackgroundColor(Color.parseColor("#44525252"));
mmoll.setTextColor(Color.parseColor("#525252"));
mmoll.setBackgroundColor(Color.parseColor("#ffffffff"));
unitOfMeasurement = 1;
}
});
}
}
Sorry about the messy code, I also tried the other way round (setting all visibilities to gone and then show one). Everything does not work anymore after the first call.
EDIT: Added entire code. All of it, except the dummyclass was created by the Android SDK.
i have set up an pp using the default tabs + swipe layout, i figured out how to display different content on different slides,
the problem im having is how i can start an intent (make a phone call using an imagebutton.
the image button is is fragment 1 or slide 1, i dont know where to declre the button, or how to format the code,
best i have managed is 1 error stating:
Gradle: error: non-static method findViewById(int) cannot be referenced from a static context
my code is as follows,
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if ((getArguments().getInt(ARG_SECTION_NUMBER)==1)) {
View view = inflater.inflate(R.layout.test, container, false);
return view;
ImageButton ib1;
ib1 = (ImageButton) findViewById(R.id.ib1);
// add button listener
ib1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));
startActivity(callIntent);
}
});
}
if ((getArguments().getInt(ARG_SECTION_NUMBER)==2)) {
View view = inflater.inflate(R.layout.test2, container, false);
return view;
}
if ((getArguments().getInt(ARG_SECTION_NUMBER)==3)) {
View view = inflater.inflate(R.layout.test3, container, false);
return view;
}
else {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
}
}
maybe remove the static in the DummySectionFragment declaration if this is not an inner class.
Also the findViewById should be getView().findViewById. Im no expert on Fragment but try this.
I have two fragments in my activity. I'm implementing actionbarsherlock TabNavigation and each tab has separate fragment. I'm performing network operation and place the results in a TextView.
If I change the fragment after the current fragment is completely loaded, it works fine. The NullPointerException only occurs if I change the fragment while the current fragment is still loading. Please help.
FRAGMENT 1:
public class Fragment1 extends SherlockFragment {
public static Fragment1 newInstance() {
Fragment1 f = new Fragment1 ();
return f;
}
private static LinearLayout mainll;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub4
final View V = inflater.inflate(R.layout.fragment_1, container, false);
AsyncHttpClient client = new AsyncHttpClient();
client.get(((MainActivity) act).getUrl(), new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Document document = Jsoup.parse(response);
Element results = document.getElementById("search_results");
mainll = (LinearLayout) V.findViewById(R.id.content);
LayoutParams mainllParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainllParams.setMargins(10, 5, 0, 0);
if(results != null) {
TextView tv= new TextView(getActivity()); //NPE occurs here
tv.setLayoutParams(mainllParams);
tv.setText(results.ownText());
tv.setGravity(Gravity.CENTER_HORIZONTAL);
mainll.addView(tv);
}
});
return V;
}
}
FRAGMENT 2:
public class Fragment2 extends SherlockFragment {
public static Fragment2 newInstance() {
Fragment2 f = new Fragment2 ();
return f;
}
private static LinearLayout mainll;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub4
final View V = inflater.inflate(R.layout.fragment_1, container, false);
AsyncHttpClient client = new AsyncHttpClient();
client.get(((MainActivity) act).getUrl(), new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Document document = Jsoup.parse(response);
Element results2 = document.getElementById("more_results");
mainll = (LinearLayout) V.findViewById(R.id.content);
LayoutParams mainllParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainllParams.setMargins(10, 5, 0, 0);
if(results2 != null) {
TextView tv2 = new TextView(getActivity()); //NPE Occurs here
tv2.setLayoutParams(mainllParams);
tv2.setText(results.ownText());
tv2.setGravity(Gravity.CENTER_HORIZONTAL);
mainll.addView(tv2);
}
});
return V;
}
}
Thanks in advance
Well, you already answered your own question: NPE occurs because current fragment is in detached state, it's mean it detached from activity and have no link to it -> getActivity() returns null.
You could add several extra options for your check to verify that your fragment is still visible and attached:
if(results2 != null && getActivity()!=null && isVisible()) {
TextView tv2 = new TextView(getActivity()); //NPE Occurs here
tv2.setLayoutParams(mainllParams);
tv2.setText(results.ownText());
tv2.setGravity(Gravity.CENTER_HORIZONTAL);
mainll.addView(tv2);
}