user6880336 user6880336 - 9 days ago 4
JSON Question

How to Delete a record from the DataBase mysql &Screen while Clicked on ListView item?

I want to Delete a record from the database when i click on the Buttton.

The Button i set in the listView.

I want to perfrom this on ListView Here i tried following way but its not working..

Here My API

<?php
include("connection.php");
$tbl = "abc";
$idToDelete = $_GET["id"];
$delete_row = mysql_query("DELETE FROM $tbl WHERE o_id=".$idToDelete);
$response["delete"] = array();
$response["success"]=1;
// push single product into final response array
echo json_encode($response);
?>


ListviewAdapter.java

package com.example.sachin.alertbox;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {
Button add;
Spinner spinner;
ListView listview;
LinearLayout linearlayout;
JSONObject jsonobject;
private static String url_addevent = "http ://10.0.2.2/portal/order_product.php";
public static String url_visitor= "http://10.0.2.2/portal/fetchorder_of_user.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
ListViewAdapterorder listadapter;
EditText qty;
LinearLayout layout;
ActionMenuView.LayoutParams params;
LinearLayout mainLayout;
PopupWindow popUp;
final Context context = this;
ArrayAdapter<String> adapter;
Button Delete;
ArrayList<String> listItems = new ArrayList<>();



String stringqty,stringspinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.clickme);
popUp = new PopupWindow(this);
layout = new LinearLayout(this);
mainLayout = new LinearLayout(this);
listview = (ListView)findViewById(R.id.listview);
Delete=(Button)findViewById(R.id.delete);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);

spinner=(Spinner)promptsView.findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(getApplication(), R.layout.spinner_layout, R.id.txt, listItems);
spinner.setAdapter(adapter);
spinner.setSelection(0);

qty=(EditText)promptsView.findViewById(R.id.qty);

// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
stringqty=qty.getText().toString();
stringspinner=spinner.getSelectedItem().toString();
addvisitor();
new fetchorder().execute();
Toast.makeText(getApplicationContext(), "qty : " + stringqty +stringspinner, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
private void addvisitor() {
service(stringqty,stringspinner);
}
private void service(String qty,String sp) {

class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();

//@Override
protected void onPreExecute() {
// Create a progressdialog
super.onPreExecute();
//loading = ProgressDialog.show(getApplicationContext(), "Please Wait...!!!", null, true, true);
}

@Override
protected String doInBackground(String... params) {

HashMap<String, String> param = new HashMap<String, String>();

param.put("quantity", params[0]);
param.put("model", params[1]);


String result = ruc.sendPostRequest(url_addevent, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}

//@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

//loading.dismiss();
Toast.makeText(getApplicationContext(), "Service Added Successfully...!!!", Toast.LENGTH_LONG).show();
/* Intent i1 = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i1);*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(qty,sp);

}

ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();

private class fetchorder extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();

List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/spinner.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}

//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
list.add("Please Select Model");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("m_model"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(Void result) {
listItems.addAll(list);

}
}




}


Here MainActivity.java ListView class

ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();

private class fetchorder extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();

List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}


I tried this way but the delete is not happening.. please suggest me some coede for this.

Answer

Try this.

  Delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                datlist.remove(position);

                o_aid.remove(position);
                o_aproduct.remove(position);
                o_aqty.remove(position);
                o_atotal.remove(position);

                Snackbar.make(view, "Record Delete Succesfully", Snackbar.LENGTH_LONG).show();
                notifyDataSetChanged();
            }
        });