0

I want to show a ListView item, the code is from my activity and I want to show in all of my fragment

I've create a Json like this

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    //mTextMessage.setText(namapegawai);
                    selectedFragment = PegawaiFragment.newInstance();
                    break;
                case R.id.navigation_dashboard:
                    //mTextMessage.setText(R.string.title_dashboard);
                    selectedFragment = MemberFragment.newInstance();
                    break;
                //case R.id.navigation_notifications:
                   // mTextMessage.setText(R.string.title_notifications);
                    //break;
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.frame_layout, selectedFragment);
            transaction.commit();
            return true;
        }
    };

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

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        namapegawai = prefs.getString(MainActivity.UserName,MainActivity.UserName);
        mTextMessage = findViewById(R.id.message);

        StudentListView = findViewById(R.id.listview1);
        progressBar = findViewById(R.id.progressBar);

        StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // TODO Auto-generated method stub
                //Intent intentSemuaMemberLihat = new Intent(getActivity(),SemuaMemberLihat.class);
                // Sending ListView clicked value using intent.
                //intentSemuaMemberLihat.putExtra("ListViewValue", IdList.get(position).toString());
                //startActivity(intentSemuaMemberLihat);
            }
        });

        BottomNavigationView navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        //Manually displaying the first fragment - one time only
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, PegawaiFragment.newInstance());
        transaction.commit();
    }

// JSON parse class started from here.
    public class GetHttpResponse extends AsyncTask<Void, Void, Void>
    {
        public Context context;

        String JSonResult;

        List<Member> studentList;

        public GetHttpResponse(Context context)
        {
            this.context = context;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
            // Passing HTTP URL to HttpServicesClass Class.
            HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
            try
            {
                httpServicesClass.ExecutePostRequest();

                if(httpServicesClass.getResponseCode() == 200)
                {
                    JSonResult = httpServicesClass.getResponse();

                    if(JSonResult != null)
                    {
                        JSONArray jsonArray = null;

                        try {
                            jsonArray = new JSONArray(JSonResult);

                            JSONObject jsonObject;
                            Member member;
                            studentList = new ArrayList<Member>();

                            for(int i=0; i<jsonArray.length(); i++)
                            {
                                member = new Member();
                                jsonObject = jsonArray.getJSONObject(i);

                                // Adding Student Id TO IdList Array.
                                IdList.add(jsonObject.getString("id").toString());
                                //Adding Student Name.
                                member.nama = jsonObject.getString("nama").toString();
                                member.nrp = jsonObject.getString("nrp").toString();
                                studentList.add(member);

                                Fragment fragment = PegawaiFragment.newInstance();
                                Bundle bundle = new Bundle();
                                bundle.putString("name", member.nama);
                                fragment.setArguments(bundle);

                            }
                        }
                        catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                else
                {
                    Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBar.setVisibility(View.GONE);
            StudentListView.setVisibility(View.VISIBLE);

            if(studentList != null) {
                ListAdapterClass adapter = new ListAdapterClass(studentList, context);
                StudentListView.setAdapter(adapter);
            }else
            {
                Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
            }

        }
    }

And in my fragment call it with

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_member, container, false);

    new PegawaiActivity.GetHttpResponse(getActivity()).execute();

    return v;
}

And get this error

Error:(44, 9) error: an enclosing instance that contains PegawaiActivity.GetHttpResponse is required

arround this code

 new PegawaiActivity.GetHttpResponse(getActivity()).execute();

Anyone know how to fix this? Already search in other related but still confuse to understand it. thanks for your help

============ UPDATE

My simple AsyncTask

public class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public AsyncResponse delegate = null;

    public interface AsyncResponse{
        void onComplete(String output);
    }

    @Override
    protected void onPostExecute(String result){
        delegate.onComplete(result);
    }

}

here in fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_member, container, false);

    getActivity().setTitle("Daftar Member");
    setHasOptionsMenu(true);

    StudentListView = v.findViewById(R.id.listview1);
    progressBar = v.findViewById(R.id.progressBar);

    PegawaiActivity a = new PegawaiActivity();
    PegawaiActivity.GetHttpResponse mm = a.new GetHttpResponse(new PegawaiActivity.GetHttpResponse.AsyncResponse(){

        @Override
        public void onComplete(String output){
            progressBar.setVisibility(View.GONE);
        }
    });
    mm.execute();


    return v;
}

but give me error

Error:(51, 49) error: constructor GetHttpResponses in class PegawaiActivity.GetHttpResponses cannot be applied to given types; required: no arguments found: reason: actual and formal argument lists differ in length

Forumesia
  • 73
  • 1
  • 11

1 Answers1

0

Your first error is trying to get you to make your inner class public static class GetHttpResponse

Your second error is telling you that you passed an argument into the Asynctask without ever defining a constructor for one.


in all of my fragment

For starters, your Asynctask is only trying to setup one Fragment.

Secondly, you're creating a brand new one, not setting up a ListView in any existing one.


The Fragment can access any data that's part of the Activity.

For example, try to get this working in a Fragment

List<Member> studentList = ((PegawaiActivity) getActivity()).getStudents();

After you move the student list field out of the Asynctask and into the parent Activity, you can make a getter method.


You don't necessarily need to pass ListView data to any Fragment. If you did, though, checkout How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Once you have a result back in the Activity, you would load the Fragment, like you've tried to do already


Whichever way you choose, you will build the adapter inside the Fragments, and set the adapter on the Listview of the Fragment layout, not the existing StudentListView, which is part of the Activity layout, so you cannot show that in every Fragment

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • yes, but I'm confuse about how to implement that, can you help me edit my code? – Forumesia Dec 01 '17 at 05:50
  • i can't change my Asynctask to get interface code, i update my first post, can you help – Forumesia Dec 01 '17 at 10:15
  • For starters, quit using nested classes. The AsyncResponse should be an entirely separate Java file – OneCricketeer Dec 01 '17 at 14:11
  • Secondly, I assume you're new to Android, and not researched any other ways to do networking requests to get JSON? Look at either Volley or Retrofit. Asynctasks are too much code to get the problem solved – OneCricketeer Dec 01 '17 at 14:13
  • Lastly, looks like you skipped over my suggestion to start with implementing `getStudents()` method on the Activity... That does not require this AsyncResponse thing – OneCricketeer Dec 01 '17 at 14:18