1

I know this question has been asked,but I didn't solve this case obviously I have two fragments containing same details one with a view as a list and the others views as a grid got from data base and have an activity which contain a tool bar this tool bar contains just an icons button like this enter image description here

all I need just a method that If I click the grid icon shows the Grid Fragment in the same activity with the same tool bar and if I clicked the list icon just replace the grid fragment with a list fragment by the way each fragment have an adapter and a getter and setter class this is the activity which contains the tool bar

package abtech.waiteriano.com.waitrer;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;

public class MenuActivity extends AppCompatActivity {
    private android.support.v7.widget.Toolbar toolbar;
    private ArrayList<String> category ;

    ImageView listIcon, gridIcon;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        String menugridSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        ResultSet rs = ConnectionClass.Ret_RS(menugridSTR);

        listIcon = (ImageView) findViewById(R.id.listicon);
        gridIcon = (ImageView) findViewById(R.id.gridicon);
        category = new ArrayList<String>() ;
        String str = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        rs = ConnectionClass.Ret_RS(str);
        try {
            while (rs.next()) {
                category.add(rs.getString("Name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, category);
        navigationSpinner.setAdapter(adapter);
        toolbar.addView(navigationSpinner, 0);

        navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MenuActivity.this,
                        "you selected: " + category.get(position),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.iconmenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()){
            case R.id.searchicon:
                // ...
                return true;
            case R.id.listicon:
                setContentView(R.layout.activity_menu_lv);
                return true;
            case R.id.gridicon:
                // ...
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

and this activity.xml file

<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="wrap_content"
    android:orientation="vertical"
    tools:context="abtech.waiteriano.com.waitrer.MenuActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" />
</LinearLayout>

and this is grid fragment class

package abtech.waiteriano.com.waitrer.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuGridViewAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;
import abtech.waiteriano.com.waitrer.getters_and_setters.MenuItem;

public class MenuGridFragment extends Fragment {

    View rootView;
    GridView menuGridView;
    static ArrayList<MenuItem> menuGridArray = new ArrayList<MenuItem>();
    CustomMenuGridViewAdapter customMenuGridViewAdapter;

    ImageView listIcon, gridIcon;


    public MenuGridFragment() {
        // Required empty public constructor
    }


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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        menuGridView = (GridView) rootView.findViewById(R.id.menuGridView);
        customMenuGridViewAdapter = new CustomMenuGridViewAdapter(getActivity(), R.layout.menu_row_grid, menuGridArray);
        menuGridView.setAdapter(customMenuGridViewAdapter);
        String menugridSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        ResultSet rs = ConnectionClass.Ret_RS(menugridSTR);
        try {
            while (rs.next()) {
                menuGridArray.add(new MenuItem(rs.getString("Name")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rootView;
    }

}

it's xml file

<FrameLayout 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="abtech.waiteriano.com.waitrer.fragments.MenuGridFragment">

    <GridView
        android:id="@+id/menuGridView"
        android:layout_width="match_parent"
        android:background="#d2d2d2"
        android:layout_height="fill_parent"
        android:layout_margin="4dp"
        android:columnWidth="80dp"
        android:gravity="center"
        android:horizontalSpacing="5dp"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:layout_below="@+id/toolbar" />

</FrameLayout>

this is list fragment class

package abtech.waiteriano.com.waitrer.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuListViewAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;
import abtech.waiteriano.com.waitrer.getters_and_setters.MenuListItem;

public class MenuLVFragment extends Fragment {

    View rootView;
    ListView menuListView;
    static ArrayList<MenuListItem> listMenuArray = new ArrayList<MenuListItem>();
    CustomMenuListViewAdapter customMenuListViewAdapter;

    public MenuLVFragment() {
        // Required empty public constructor
    }


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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        menuListView = (ListView) rootView.findViewById(R.id.menuLV);
        customMenuListViewAdapter = new CustomMenuListViewAdapter(getActivity(), R.layout.menu_row_list,listMenuArray);
        menuListView.setAdapter(customMenuListViewAdapter);
        String menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
        try {
            while (rs.next()){
                listMenuArray.add(new MenuListItem(rs.getString("Name")));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rootView;
    }
}

it's xml file

<FrameLayout 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="abtech.waiteriano.com.waitrer.fragments.MenuLVFragment">

    <ListView
        android:id="@+id/menuLV"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

by the way I I need the grid fragment was the default view as when I start this activity always shows the grid fragment as a default one sorry if any thing doesn't clear and for long code,if any observation please post a comment LogCat Error

03-02 13:59:23.352 6741-6741/? E/ERRO: Unknown server host name 'Host is unresolved: null'.
03-02 13:59:23.389 6741-6741/? E/ERRO: Unknown server host name 'Host is unresolved: null'.
03-02 13:59:23.403 6741-6741/? E/ERRO: Unknown server host name 'Host is unresolved: null'.
03-02 13:59:23.508 6741-6766/? E/GED: Failed to get GED Log Buf, err(0)
03-02 13:59:23.526 6741-6766/? E/[PropSet]: connect fail
03-02 13:59:23.526 6741-6766/? E/libc: __system_property_set error : retry fail, errno 13(Permission denied)
03-02 13:59:23.526 6741-6766/? E/[PropSet]: send_prop_msg return err -5
03-02 14:01:34.965 6741-6741/abtech.waiteriano.com.waitrer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: abtech.waiteriano.com.waitrer, PID: 6741
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                 at abtech.waiteriano.com.waitrer.fragments.MenuLVFragment.onCreateView(MenuLVFragment.java:40)
                                                                                 at android.app.Fragment.performCreateView(Fragment.java:2069)
                                                                                 at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:899)
                                                                                 at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1072)
                                                                                 at android.app.BackStackRecord.run(BackStackRecord.java:852)
                                                                                 at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
                                                                                 at android.app.FragmentManagerImpl$1.run(FragmentManager.java:452)
                                                                                 at android.os.Handler.handleCallback(Handler.java:815)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                                 at android.os.Looper.loop(Looper.java:214)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6102)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

3 Answers3

0

I always use fragments in my project like this: at first in Activity that i want be host for fragment or fragments I create a container for example <FrameLayout... in layout activity.

    <FrameLayout
    android:id="@+id/profile_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

in you Activity class you should declare your fragment as a field below of your class:

private ProfileFragment profileFragment;
private EditProfileFragment editProfileFragment;

second in my hosted activity I use lazy loading for instantiate fragment or fragments like this, of course i am doing this on onResume() method:

    @Override
protected void onResume() {
    super.onResume();
    getProfileFragment();
    getEditProfileFragment();
}

and then :

    private ProfileFragment getProfileFragment() {
    if (profileFragment == null) {
        profileFragment = new ProfileFragment();

    }
    return profileFragment;
}

private EditProfileFragment getEditProfileFragment() {
    if (editProfileFragment == null) {
        editProfileFragment = new EditProfileFragment();

    }
    return editProfileFragment;
}

for example if u want by clicking on one button, one fragment is begin transaction you should write codes on button action like this:

private void addFragment () {
getSupportFragmentManager().beginTransaction().
replace(R.id.profile_container, getProfileFragment()).commit();

R.id.profile_container is my container in my hosted activity layout.

if you want one fragment by default sit on you container you can do it on onResume()just call you method of your fragment:

        @Override
protected void onResume() {
    super.onResume();
    getProfileFragment();
    getEditProfileFragment();
    addFragment ();

}

sorry if my english is bad.

for toolBar you can create a menu and in your menu Item action invoke your Fragment method that you create like above.

sayres kabir
  • 362
  • 4
  • 22
  • First of all thanks a lot for your interests but I just need how to add or Use these methods in my case for example the line for getProfileFragment(); how can I use this method, am just a fresh developer and it's hard for me to under stand this :D @sayres kabir –  Mar 02 '17 at 09:30
  • @Dev.7arooney I am using 2 button for change fragments in one Activity – sayres kabir Mar 02 '17 at 09:51
  • Thanks alot @sayres kabir am gonna try this and reply you with results –  Mar 02 '17 at 09:53
  • @Dev.7arooney i do EDIT my post.look agein – sayres kabir Mar 02 '17 at 09:56
0

First of All If you are going to show your same data in ListView and GridView then there is no required to create individual fragment for ListView and GridView, instead you should go with RecyclerView which can display data in List format as well as Grid format.

Here you can see the documentation of RecyclerView.

RecyclerView provides these built-in layout managers:

  1. LinearLayoutManager shows items in a vertical or horizontal scrolling list.
  2. GridLayoutManager shows items in a grid.
  3. StaggeredGridLayoutManager shows items in a staggered grid.

So For List View you can set

 LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
 mRecyclerView.setLayoutManager(mLayoutManager);

and For Grid View

 GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
 mRecyclerView.setLayoutManager(mLayoutManager);

where 2 is number of cells in single row.

sodhankit
  • 1,138
  • 1
  • 14
  • 26
0

Add this FrameLayout to your activity.xml

<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="wrap_content"
    android:orientation="vertical"
    tools:context="abtech.waiteriano.com.waitrer.MenuActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" />

         <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></FrameLayout>

</LinearLayout>

Replace this frame with your MenuGridFragment in OnCreate() of MainActivity. (As you said MenuGridFragment is your default fragment)

FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MenuGridFragment()).commit();

Load fragment depending on the selected icon in onMenuItemSelected():

@Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()){
            case R.id.searchicon:
                // ...
                return true;
            case R.id.listicon:
                 FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MenuLVFragment()).commit();
                return true;
            case R.id.gridicon:
                // ...
                 FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MenuGridFragment()).commit();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

Hope this helps.

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
  • Thanks @tahsinRupam for your answer but you mean that Replace menuGridView = (GridView) rootView.findViewById(R.id.menuGridView); with FragmentManager fm = getFragmentManager(); fm.beginTransaction().replace(R.id.content_frame, new MenuGridFragment()).commit();?? –  Mar 02 '17 at 11:32
  • No, no replace GridFragment. Sorry I putted it wrongly. We are replacing fragments here. First replace a blank FrameLayout with the MenuGridFragment(Then MenugridGragment will be the default screen of the app). Then it'll be replaced by Toolbar icon click. – tahsinRupam Mar 02 '17 at 11:36
  • I've edited my answer. I used wrong word, that made the confusion. Sorry for that. – tahsinRupam Mar 02 '17 at 11:38
  • I found Underlined error on this code new MenuGridFragment() says that Wrong 2nd argument type. Found: 'abtech.waiteriano.com.waitrer.fragments.MenuGridFragment', required: 'android.app.Fragment' how can I solve this –  Mar 02 '17 at 11:43
  • Modify "public class MenuLVFragment extends Fragment {" to "public class MenuLVFragment extends android.app.Fragment {" in MenuLVFragment class – tahsinRupam Mar 02 '17 at 11:51
  • am so sorry I know I asking a lot but I can't solve this case since 2 days and thanks alot that you are trying to help me but I found another error app crashes When I click the Icons button says that "java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference" –  Mar 02 '17 at 11:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/137052/discussion-between-tahsinrupam-and-dev-7arooney). – tahsinRupam Mar 02 '17 at 11:58