1

New in Android, trying to understand how it works. I am trying to load a Fragment Dynamically. I have a Layout with Four Buttons, and a Frame Layout to load an activity inside that frame layout according to the button clicked. Activity Code:

<?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">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50sp"
        android:background="#00BFF3">
        <Button
            android:id="@+id/teachers"
            android:layout_width="180sp"
            android:layout_height="25sp"
            style="?attr/borderlessButtonStyle"
            android:background="#00BFF3"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_marginTop="10sp"
            android:text="Staff Directory"
            android:textAlignment="viewStart"
            android:layout_marginStart="15sp"
            android:onClick="Teachers"/>
        <Button
            android:id="@+id/attendances"
            android:layout_width="175sp"
            android:layout_height="25sp"
            style="?attr/borderlessButtonStyle"
            android:background="#00BFF3"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_marginTop="10sp"
            android:text="Attendance List"
            android:textAlignment="viewStart"
            android:layout_marginStart="185sp"
            android:onClick="Attendances"/>
        <Button
            android:id="@+id/todayAttandance"
            android:layout_width="190sp"
            android:layout_height="25sp"
            style="?attr/borderlessButtonStyle"
            android:background="#00BFF3"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_marginTop="10sp"
            android:text="Today Attendance"
            android:textAlignment="viewStart"
            android:layout_marginStart="355sp"
            android:onClick="TodayAttendance"/>

        <Button
            android:id="@+id/students"
            android:layout_width="150sp"
            android:layout_height="25sp"
            style="?attr/borderlessButtonStyle"
            android:background="#00BFF3"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_marginTop="10sp"
            android:text="Student List"
            android:textAlignment="viewStart"
            android:layout_marginStart="545sp"
            android:onClick="Students"/>
    </RelativeLayout>
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_marginTop="10sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

Listview Template:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="40sp"
        android:text="TextView"
        android:layout_weight="1"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"  />

    <TextView
        android:id="@+id/classname"
        android:layout_width="0dp"
        android:layout_height="40sp"
        android:text=""
        android:layout_weight="1"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"  />

    <TextView
        android:id="@+id/fname"
        android:layout_width="0dp"
        android:layout_height="40sp"
        android:text=""
        android:layout_weight="1"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"  />

    <TextView
        android:id="@+id/fphone"
        android:layout_width="0dp"
        android:layout_height="40sp"
        android:text=""
        android:layout_weight="1"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"  />

</LinearLayout>

Activity.Java:

    public class firstWindow extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_window);

    }
    public void Students(View v){
        OpenWindow(1);
    }
    public void OpenWindow(int index){
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        studentFragment fragment = new studentFragment();
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    }
}

Fragment Code: Downloads the data from an API:

public class studentFragment extends ListFragment implements iEvents<student> {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);


   student s = new student();
    ArrayList<student> arraylist = new ArrayList<student>();
    s.setName("Vikas");
    s.setId(1);
    s.setAddress("G-20, Arjun Nagar");
    s.setPhone("9818899114");
    arraylist.add(s);
    studentAdapter simpleAdapter = new studentAdapter(getActivity().getApplicationContext(),arraylist);
    setListAdapter(simpleAdapter);


}

@Override
public void Success(List<student> extenders) {

    if(extenders!=null){
        if(extenders.size()==1){
            //may be a failure

            student s = extenders.get(0);
            if(s.getCode()==-1){
                //error
                return;
            }
        }

        if(extenders.size() > 0){
            //valid collection
            //  setContentView(R.layout.studentlistview);

            ArrayList<student> arraylist = new ArrayList<student>(extenders);
            context.get_context().setStudentList(extenders);
            studentAdapter simpleAdapter = new studentAdapter(getActivity().getApplicationContext(),arraylist);

            setListAdapter(simpleAdapter);
            // setContentView(R.layout.activity_student_show_all);
        }
    }

}

@Override
public void Failure(List<student> extenders) {

}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    ////outState.putInt("curChoice", mCurCheckPosition);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    //showDetails(position);
    student selectedItem = (student)  context.get_context().getStudentList().get(position);
    context.get_context().StudentHolder = selectedItem;
    ShowDetails(selectedItem);
}

private void ShowDetails(student stu){

}

/**
 * Helper function to show the details of a selected item, either by
 * displaying a fragment in-place in the current UI, or starting a
 * whole new activity in which it is displayed.
 */
void showDetails(int index) {

}

}

Adapter Code:

public class studentAdapter extends ArrayAdapter<student> {

    public studentAdapter(Context context, ArrayList<student> students) {

        super(context, R.layout.studentlistview, students);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        student user = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.studentlistview, parent, true);
        }
        // Lookup view for data population
        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView className = (TextView) convertView.findViewById(R.id.classname);
        TextView father = (TextView) convertView.findViewById(R.id.fname);
        TextView fatherMobile = (TextView) convertView.findViewById(R.id.fphone);


        name.setText(user.getName());
        className.setText(user.getClassName());
        father.setText(user.getFatherName());
        fatherMobile.setText(user.getFatherPhone());
        return convertView;
    }
}

So when I debug, it shows that 40 items of type Student are loaded, but the view is not refreshing it shows me this:Screenshot of image

It seems that the view is loading the values, but the view coming up on screen is different from the view which is loading the values so it is not showing up. Any help?

  • First, Java class names should start with capital letters and methods are lowercased. Anyways, how does `Success(List extenders)` get called? Where is the `executionList` class? – OneCricketeer Oct 11 '16 at 17:16
  • I am so confused about the coding standard java follows. I will work on that. Since I am not a Java guy, I wrote a Layer to download the data from API and then with in that Architecture, once the data is downloaded, the Success Function is called from data layer. The architecture has many classes so I couldn't post all. But this part is working fine, coz I ran my tests to create a student list in a stand alone activity and it loaded results fine. I think there is some very common/dumb error which might be causing which I am unable to understand or find. – Piyush Gupta Oct 11 '16 at 17:19
  • I didn't get what library are you using to load data to your application: **context.get_context().setStudentList(extenders);**?? or **executionList execution = new executionList<>(this);**??? could you explain a bit! However, I feel like you have recently start java and need more help. Maybe I can help you with it... – Mohsen Mirhoseini Oct 11 '16 at 17:33
  • I suggest you give me your api address for loading students and I write a standard Android java code for you in answer. – Mohsen Mirhoseini Oct 11 '16 at 17:36
  • I would love to, but this is for one of the client and I am not sure if they would like me to mention the API URL here. I will need to confirm from them before I can mention it here. However, I would like to mention that this API is loading data correctly. If I debug, I can see a list of students being pulled in correctly. GetView func of adapter is called and it is returning a view correctly. But it is not showing in Activity. A listview with blank 40 rows is displayed. Is this a possibility that since it is downloading from API, the Fragment is loaded first, and items are coming after that? – Piyush Gupta Oct 11 '16 at 17:56
  • "the Fragment is loaded first, and items are coming after that" -- Yes, that is definitely happening because that is how asynchronous code works. Please [edit] your question to add the `iEvents` interface and `executionList` class – OneCricketeer Oct 11 '16 at 18:10
  • I removed that block al together, I just added a single record, hard coded. Now it shows one record. and now it is not downloading any data from any API...just one item, and not showing up in listview. – Piyush Gupta Oct 11 '16 at 18:29
  • Sorry, I thought it is a test project and that was the reason I asked for the api link. I believe you have problem with loading data from api. I suggest you to study about retrofit library and use it in your project. It is really straight forward! https://square.github.io/retrofit/ – Mohsen Mirhoseini Oct 11 '16 at 18:35
  • ask further question if you need help – Mohsen Mirhoseini Oct 11 '16 at 18:35
  • sure, I would. However, I just edited my question and have removed the data from API downloading part. I guess it caused lot of confusions.Sorry about that. Now I am adding items hard coded, and it still is not showing up in listview – Piyush Gupta Oct 11 '16 at 18:40

1 Answers1

0

Since you claim that your list is showing 40 elements come through, I think your XML layout for the adapter is wrong or your student objects return all empty strings for getName(), getClassName(), etc.

For example, you've set the "row" layout to both match_parent on the width and height. This will cause one "row" to occupy the entire screen.

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" 
    android:layout_width="match_parent"
    android:layout_height="match_parent" <!-- change to "wrap_content" -->
>

If that isn't the problem, you could try getActivity() instead of getActivity().getApplicationContext(), which, yes, is the Activity, but an Activity is a Context. For details on that, you can see Using Application context everywhere?

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    in that case, shouldn't it show one row at least? Also, if you check the screenshot, it shows the blank placeholders in image. which makes me feel that view is not loading the data correctly. There must be something I am missing to bind the views with actual listview. – Piyush Gupta Oct 11 '16 at 18:31
  • plus I have made sure in logs that it shows the data in adapters – Piyush Gupta Oct 11 '16 at 18:32
  • The logs say the data exists, but you seem to be rendering wrong, which is what my answer says. How about `getActivity()` instead of `getActivity().getApplicationContext()`? – OneCricketeer Oct 11 '16 at 19:03
  • damn it, you nailed it. Thanks. I didn't downvote you btw. It just worked. But why it worked? – Piyush Gupta Oct 11 '16 at 19:13
  • I just read the definition of ArrayAdapter, and it asks for Context object, but sending the Activity instead made it work. It didnt throw any error either. I am confused what happened here. – Piyush Gupta Oct 11 '16 at 19:17
  • Can you add the comment in your answer, so I can accept your answer as a valid answer? Thanks for the help – Piyush Gupta Oct 11 '16 at 19:18
  • Updated answer. – OneCricketeer Oct 11 '16 at 19:36