convert activity to fragment to use navigation drawer

  • Replies:0
Andi Syarif
  • Forum posts: 1

Jan 23, 2017, 5:34:26 AM via Website

hello all
any body can help me to convert my activity to fragment because i want to use navigation drawer parsing data from mysql to list view

this is my code

package com.andicom.andi;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.andicom.andi.adapter.AdapterAdmin;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.andicom.andi.app.AppControllerAdmin;
import com.andicom.andi.data.DataAdmin;
import com.andicom.andi.util.ServerAdmin;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivityAdmin extends  AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener  {

    Toolbar toolbar;
    FloatingActionButton fab;
    ListView list;
    SwipeRefreshLayout swipe;
    List<DataAdmin> itemList = new ArrayList<DataAdmin>();
    AdapterAdmin adapterAdmin;
    int success;
    AlertDialog.Builder dialog;
    LayoutInflater inflater;
    View dialogView;
    EditText txt_id, txt_namapengguna, txt_pass, txt_email;
    String id, namapengguna, pass, email;


    private static final String TAG = MainActivityAdmin.class.getSimpleName();

    private static String url_select     = ServerAdmin.URL + "select.php";
    private static String url_insert     = ServerAdmin.URL + "insert.php";
    private static String url_edit       = ServerAdmin.URL + "edit.php";
    private static String url_update     = ServerAdmin.URL + "update.php";
    private static String url_delete     = ServerAdmin.URL + "delete.php";

    public static final String TAG_ID       = "id";
    public static final String TAG_NAMAPENGGUNA     = "namapengguna";
    public static final String TAG_PASS  = "pass";
    public static final String TAG_EMAIL  = "email";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    String tag_json_obj = "json_obj_req";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainadmin);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        // menghubungkan variablel pada layout dan pada java
        fab     = (FloatingActionButton) findViewById(R.id.fab_add);
        swipe   = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        list    = (ListView) findViewById(R.id.list);

        // untuk mengisi data dari JSON ke dalam adapterAdmin
        adapterAdmin = new AdapterAdmin(MainActivityAdmin.this, itemList);
        list.setAdapter(adapterAdmin);

        // menamilkan widget refresh
        swipe.setOnRefreshListener(this);

        swipe.post(new Runnable() {
                       @Override
                       public void run() {
                           swipe.setRefreshing(true);
                           itemList.clear();
                           adapterAdmin.notifyDataSetChanged();
                           callVolley();
                       }
                   }
        );

        // fungsi floating action button memanggil form kontak
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogForm("", "", "","", "SIMPAN");
            }
        });

        // listview ditekan lama akan menampilkan dua pilihan edit atau delete data
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view,
                                           final int position, long id) {
                // TODO Auto-generated method stub
                final String idx = itemList.get(position).getId();

                final CharSequence[] dialogitem = {"Edit", "Delete"};
                dialog = new AlertDialog.Builder(MainActivityAdmin.this);
                dialog.setCancelable(true);
                dialog.setItems(dialogitem, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        switch (which) {
                            case 0:
                                edit(idx);
                                break;
                            case 1:
                                delete(idx);
                                break;
                        }
                    }
                }).show();
                return false;
            }
        });


    }

    @Override
    public void onRefresh() {
        itemList.clear();
        adapterAdmin.notifyDataSetChanged();
        callVolley();
    }

    // untuk mengosongi edittext pada form
    private void kosong(){
        txt_id.setText(null);
        txt_namapengguna.setText(null);
        txt_pass.setText(null);
        txt_email.setText(null);
    }

    // untuk menampilkan dialog from kontak
    private void DialogForm(String idx, String namax, String passx, String emailx, String button) {
        dialog = new AlertDialog.Builder(MainActivityAdmin.this);
        inflater = getLayoutInflater();
        dialogView = inflater.inflate(R.layout.form_admin, null);
        dialog.setView(dialogView);
        dialog.setCancelable(true);
        dialog.setIcon(R.mipmap.ic_launcher);
        dialog.setTitle("Form Biodata");

        txt_id      = (EditText) dialogView.findViewById(R.id.txt_id);
        txt_namapengguna    = (EditText) dialogView.findViewById(R.id.txt_namapengguna);
        txt_pass  = (EditText) dialogView.findViewById(R.id.txt_pass);
        txt_email  = (EditText) dialogView.findViewById(R.id.txt_email);

        if (!idx.isEmpty()){
            txt_id.setText(idx);
            txt_namapengguna.setText(namax);
            txt_pass.setText(passx);
            txt_email.setText(emailx);
        } else {
            kosong();
        }

        dialog.setPositiveButton(button, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                id      = txt_id.getText().toString();
                namapengguna    = txt_namapengguna.getText().toString();
                pass  = txt_pass.getText().toString();
                email  = txt_email.getText().toString();

                simpan_update();
                dialog.dismiss();
            }
        });

        dialog.setNegativeButton("BATAL", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                kosong();
            }
        });

        dialog.show();
    }

    // untuk menampilkan semua data pada listview
    private void callVolley(){
        itemList.clear();
        adapterAdmin.notifyDataSetChanged();
        swipe.setRefreshing(true);

        // membuat request JSON
        JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject obj = response.getJSONObject(i);

                        DataAdmin item = new DataAdmin();

                        item.setId(obj.getString(TAG_ID));
                        item.setNama(obj.getString(TAG_NAMAPENGGUNA));
                        item.setPass(obj.getString(TAG_PASS));
                        item.setEmail(obj.getString(TAG_EMAIL));

                        // menambah item ke array
                        itemList.add(item);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                // notifikasi adanya perubahan data pada adapterAdmin
                adapterAdmin.notifyDataSetChanged();

                swipe.setRefreshing(false);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                swipe.setRefreshing(false);
            }
        });

        // menambah request ke request queue
        AppControllerAdmin.getInstance().addToRequestQueue(jArr);
    }

    // fungsi untuk menyimpan atau update
    private void simpan_update() {
        String url;
        // jika id kosong maka simpan, jika id ada nilainya maka update
        if (id.isEmpty()){
            url = url_insert;
        } else {
            url = url_update;
        }

        StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    success = jObj.getInt(TAG_SUCCESS);

                    // Cek error node pada json
                    if (success == 1) {
                        Log.d("Add/update", jObj.toString());

                        callVolley();
                        kosong();

                        Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                        adapterAdmin.notifyDataSetChanged();

                    } else {
                        Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(MainActivityAdmin.this, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters ke post url
                Map<String, String> params = new HashMap<String, String>();
                // jika id kosong maka simpan, jika id ada nilainya maka update
                if (id.isEmpty()){
                    params.put("namapengguna", namapengguna);
                    params.put("pass", pass);
                    params.put("email", email);
                } else {
                    params.put("id", id);
                    params.put("namapengguna", namapengguna);
                    params.put("pass", pass);
                    params.put("email", email);
                }

                return params;
            }

        };

        AppControllerAdmin.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }

    // fungsi untuk get edit data
    private void edit(final String idx){
        StringRequest strReq = new StringRequest(Request.Method.POST, url_edit, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    success = jObj.getInt(TAG_SUCCESS);

                    // Cek error node pada json
                    if (success == 1) {
                        Log.d("get edit data", jObj.toString());
                        String idx      = jObj.getString(TAG_ID);
                        String namapenggunax    = jObj.getString(TAG_NAMAPENGGUNA);
                        String passx  = jObj.getString(TAG_PASS);
                        String emailx  = jObj.getString(TAG_EMAIL);

                        DialogForm(idx, namapenggunax, passx, emailx, "UPDATE");

                        adapterAdmin.notifyDataSetChanged();

                    } else {
                        Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(MainActivityAdmin.this, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters ke post url
                Map<String, String> params = new HashMap<String, String>();
                params.put("id", idx);

                return params;
            }

        };

        AppControllerAdmin.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }

    // fungsi untuk menghapus
    private void delete(final String idx){
        StringRequest strReq = new StringRequest(Request.Method.POST, url_delete, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    success = jObj.getInt(TAG_SUCCESS);

                    // Cek error node pada json
                    if (success == 1) {
                        Log.d("delete", jObj.toString());

                        callVolley();

                        Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

                        adapterAdmin.notifyDataSetChanged();

                    } else {
                        Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(MainActivityAdmin.this, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters ke post url
                Map<String, String> params = new HashMap<String, String>();
                params.put("id", idx);

                return params;
            }

        };

        AppControllerAdmin.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }
}

Regard's

Reply