Langsung ke konten utama

Menghapus Data MySQL

Web Service: deleteAccount.php
<?php
$username = $_GET['username'];
include "connect_db.php";
$query = "delete from tbaccount where username ='".$username."'";
$result = mysql_query($query, $link) or die('Error query:  '.$query);
echo "data berhasil dihapus";
?>

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

    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:orientation="horizontal"        >

        <TextView            android:layout_width="wrap_content"            android:layout_height="fill_parent"            android:layout_weight="1"            android:textStyle="bold"            android:text="USERNAME" />


    </LinearLayout>

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="750dp"        android:layout_weight="1"        >

        <ListView            android:id="@+id/listViewAccount"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:dividerHeight="5dp" >

        </ListView>

    </LinearLayout>

</LinearLayout>

Java
package adehodijah.example.com.pertemuanmysql;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;

public class DeleteActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    public static final String URL_GETACCOUNT = "http://192.168.43.78:8080/android/getAccount.php"; //koneksi database ke localhost    public static final String URL_DELETEACCOUNT = "http://192.168.43.78:8080/android/deleteAccount.php"; //koneksi database ke localhost    private AccountAdapter adapter;
    private ListView listAccount;

    private boolean isDelete =  false;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delete);
        adapter = new AccountAdapter(this, R.id.textView1);
        listAccount = (ListView) findViewById(R.id.listViewAccount);
        listAccount.setAdapter(adapter);
        listAccount.setOnItemClickListener(this);
    }

    @Override    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        loadRefreshData();
    }

    //Method untuk Mengirimkan data keserver    public String getRequest(String Url){
        String sret;
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(Url);
        try{
            HttpResponse response = client.execute(request);
            sret= request(response);
        }catch(Exception ex){
            sret= "Failed Connect to server!";
        }
        return sret;

    }
    //Method untuk Menerima data dari server    public static String request(HttpResponse response){
        String result = "";
        try{
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null){
                str.append(line + "\n");
            }
            in.close();
            result = str.toString();
        }catch(Exception ex){
            result = "Error";
        }
        return result;
    }

    @Override    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            isDelete =  true;
            CallWebPageTask task = new CallWebPageTask();
            task.applicationContext = DeleteActivity.this;
            String url =URL_DELETEACCOUNT+"?username="+adapter.getItem(position).username;
            task.execute(new String[] { url });
            Toast.makeText(DeleteActivity.this, "Account " + adapter.getItem(position).username + " berhasil dihapus", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this, "Error: "+ e.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    //Class CallWebPageTask untuk implementasi class AscyncTask    private class CallWebPageTask extends AsyncTask<String, Void, String> {

        private ProgressDialog dialog;
        protected Context applicationContext;

        @Override        protected void onPreExecute() {
            this.dialog = ProgressDialog.show(applicationContext, "Login Process", "Please Wait...", true);
        }

        @Override        protected String doInBackground(String... urls) {
            String response = "";
            response = getRequest(urls[0]);
            return response;
        }

        @Override        protected void onPostExecute(String result) {
            this.dialog.cancel();
            if(isDelete){
                loadRefreshData();
            }else {
                adapter.clear();
                Log.w("Load Account", result);
                JSONObject jObject = null;
                try {
                    jObject = new JSONObject(result);
                    JSONArray newsJsonArray = jObject.getJSONArray("Account");
                    Log.w("Load data Account", "Size = " + newsJsonArray.length());
                    for (int i = 0; i < newsJsonArray.length(); i++) {
                        Account account = new Account(newsJsonArray.getJSONObject(i));
                        adapter.add(account);
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    void loadRefreshData(){
        isDelete =  false;
        CallWebPageTask task = new CallWebPageTask();
        task.applicationContext = DeleteActivity.this;
        task.execute(new String[] { URL_GETACCOUNT });
    }

    class AccountAdapter extends ArrayAdapter<Account> {
        public AccountAdapter(Context context, int resource) {
            super(context, resource);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView==null){
                convertView = ((LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.row, parent,false);
            }
            TextView usernameUser = (TextView) convertView.findViewById(R.id.textViewUsername);
            Account entityUser = getItem(position);
            usernameUser.setText(entityUser.username);
            return convertView;
        }
    }
}

Komentar

Postingan populer dari blog ini

Menampilkan Data MySQL

Web Service: getAccount.php <?php include "connect_db.php"; $query = "SELECT username,password FROM tbaccount"; $result = mysql_query($query, $link) or die('Errorquery:  '.$query); $rows = array(); while ($r = mysql_fetch_assoc($result)) {     $rows[] = $r; } $data = "{Account:".json_encode($rows)."}"; echo $data; ?> Layout Adapter <? xml version= "1.0" encoding= "utf-8" ?> < LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android :layout_width= "fill_parent" android :layout_height= "fill_parent" android :orientation= "vertical" > < LinearLayout android :layout_width= "fill_parent" android :layout_height= "fill_parent" android :layout_weight= "1" android :orientation= "horizontal" > < TextView android...