Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 列表视图和异步任务不通信以删除项?_Java_Android_Android Listview_Android Asynctask - Fatal编程技术网

Java 列表视图和异步任务不通信以删除项?

Java 列表视图和异步任务不通信以删除项?,java,android,android-listview,android-asynctask,Java,Android,Android Listview,Android Asynctask,我有一节简单的课。它从我的本地主机加载数据,并用android:id/list填充listview 我已经设置了一个onclick侦听器,以便在单击某个项目时调用我的delete async任务 我的profileList.remove(position)有效,我似乎无法获得notifyDataSetChanged();工作方法不知道放在哪里 最后,我不确定,但我不认为我的类引用了我要删除的项目的位置,并将其与我的数据库匹配?我一直在日志中找到“success=0 no profile” 有什么

我有一节简单的课。它从我的本地主机加载数据,并用android:id/list填充listview

我已经设置了一个onclick侦听器,以便在单击某个项目时调用我的delete async任务

我的profileList.remove(position)有效,我似乎无法获得notifyDataSetChanged();工作方法不知道放在哪里

最后,我不确定,但我不认为我的类引用了我要删除的项目的位置,并将其与我的数据库匹配?我一直在日志中找到“success=0 no profile”

有什么想法吗?我只想刷新我的计数/列表视图并删除我的项目

类别:

 public class ViewAllLocations extends ListActivity {

    String id;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> profileList;
    SimpleAdapter adapter;
    // url to get all products list
    private static String url_all_profile = "http://MYIP:8888/android_connect/get_all_location.php";
    // url to delete product
    private static final String url_delete_profile = "http://MYIP:8888/android_connect/delete_location.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_LOCATION = "Location";
    private static final String TAG_ID = "id";
    private static final String TAG_LATITUDE = "latitude";
    private static final String TAG_LONGITUDE = "longitude";


    // products JSONArray
    JSONArray userprofile = null;

    TextView locationCount;
    int count = 0;
    Button deleteLocation;
    ListView lo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_all_locations);
        // Hashmap for ListView
        profileList = new ArrayList<HashMap<String, String>>();

        deleteLocation = (Button) findViewById(R.id.deleteLocation);
        locationCount = (TextView) findViewById(R.id.locationCount);
        lo = (ListView) findViewById(android.R.id.list);

        //setup adapter first //now no items, after getting items (LoadAllLocations) will update it
        adapter = new SimpleAdapter(
                ViewAllLocations.this, profileList,
                R.layout.locationitem, new String[]{TAG_ID,
                TAG_LATITUDE, TAG_LONGITUDE},
                new int[]{R.id.id, R.id.latitude, R.id.longitude});

        // updating listview
        setListAdapter(adapter);

        // Loading products in Background Thread
        new LoadAllLocation().execute();

        deleteLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        id = i.getStringExtra(TAG_ID);

        // Get listview
        ListView lo = getListView();

        lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                new DeleteLocation(position).execute();
                Map<String, String> item = profileList.get(position);
                String selectedItemId = item.get(TAG_ID);
                new DeleteLocation(position).execute(selectedItemId);


            }
        });


    }


    /**
     * **************************************************************
     * Background Async Task to Delete Product
     */
    class DeleteLocation extends AsyncTask<String, String, Integer> {

        int deleteItemPosition;

        public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
            this.deleteItemPosition = position;
        }

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ViewAllLocations.this);
            pDialog.setMessage("Deleting Location...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Deleting product
         */
        protected Integer doInBackground(String... args) {

            String selectedId = args[0];

            // Check for success tag
            int success = 0; //0=failed 1=success
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", selectedId));

                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_profile, "POST", params);

                // check your log for json response
                Log.d("Delete Product", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                //if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
                // Intent i = getIntent();
                // send result code 100 to notify about product deletion
                //setResult(100, i);

                //you cant update UI on worker thread, it must be done on UI thread
                // Toast.makeText(getApplicationContext(), "Location Deleted",
                // Toast.LENGTH_SHORT).show();
                //finish();
                // }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return success;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(Integer result) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (result == 1) {
                    //success
                   //delete from list and update listview
                profileList.remove(deleteItemPosition);
                adapter.notifyDataSetChanged();
            } else {
            //failed
            }

        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadAllLocation extends AsyncTask<String, String, Integer> {
        int success;

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ViewAllLocations.this);
            pDialog.setMessage("Loading Locations. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         */
        protected Integer doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Profiles: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                     // products found
                    // Getting Array of Products
                    userprofile = json.getJSONArray(TAG_LOCATION);

                    // looping through All Products
                    for (int i = 0; i < userprofile.length(); i++) {
                        JSONObject c = userprofile.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String latitude = c.getString(TAG_LATITUDE);
                        String longitude = c.getString(TAG_LONGITUDE);


                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_LATITUDE, latitude);
                        map.put(TAG_LONGITUDE, longitude);


                        // adding HashList to ArrayList
                        profileList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //Intent i = new Intent(getApplicationContext(),
                    // UserLocation.class);
                    // Closing all previous activities
                    // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    // startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return success;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(Integer result) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            locationCount.setText("" + profileList.size());
            if (result == 1) {
            //success
            //update adapter items
                adapter.notifyDataSetChanged();
            } else {
            //failed
            //launch activity here
            }


        }

    }
<?php

/*
 * Following code will delete a profile from table
 * A product is identified by profile id (id)
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['id'])) {
    $id = $_POST['id'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql update row with matched pid
    $result = mysql_query("DELETE FROM Location WHERE id = $id");

    // check if row deleted or not
    if (mysql_affected_rows() > 0) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Profile successfully deleted";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No Profile found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>
public类ViewAllLocations扩展了ListActivity{
字符串id;
//进度对话框
私人对话;
//JSON解析器类
JSONParser JSONParser=新的JSONParser();
ArrayList概要列表;
SimpleAdapter适配器;
//获取所有产品列表的url
私有静态字符串url_all_profile=”http://MYIP:8888/android_connect/get_all_location.php";
//用于删除产品的url
私有静态最终字符串url_delete_profile=”http://MYIP:8888/android_connect/delete_location.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串TAG_LOCATION=“LOCATION”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_LATITUDE=“LATITUDE”;
私有静态最终字符串标记_LONGITUDE=“LONGITUDE”;
//产品JSONArray
JSONArray userprofile=null;
文本视图位置计数;
整数计数=0;
按钮删除位置;
ListView lo;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u view\u所有位置);
//ListView的Hashmap
profileList=newarraylist();
deleteLocation=(按钮)findViewById(R.id.deleteLocation);
locationCount=(TextView)findViewById(R.id.locationCount);
lo=(ListView)findViewById(android.R.id.list);
//首先安装适配器//现在没有项目,获取项目后(LoadAllLocations)将更新它
适配器=新的SimpleAdapter(
ViewAllLocations.this、profileList、,
R.layout.locationitem,新字符串[]{TAG_ID,
TAG_纬度,TAG_经度},
新的int[]{R.id.id,R.id.latitude,R.id.longitude});
//更新列表视图
setListAdapter(适配器);
//在后台线程中加载产品
新建LoadAllLocation().execute();
deleteLocation.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
}
});
//从intent获取产品详细信息
Intent i=getIntent();
//从intent获取产品id(pid)
id=i.getStringExtra(标签id);
//获取列表视图
ListView lo=getListView();
lo.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
新建DeleteLocation(position).execute();
映射项=profileList.get(位置);
String selectedItemId=item.get(TAG\u ID);
新建删除位置(位置)。执行(选择编辑EMID);
}
});
}
/**
* **************************************************************
*用于删除产品的后台异步任务
*/
类DeleteLocation扩展了异步任务{
int-deleteItemPosition;
公共位置(内部位置){
//TODO自动生成的构造函数存根
this.deleteItemPosition=位置;
}
/**
*在启动后台线程显示进度对话框之前
*/
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(ViewAllLocations.this);
setMessage(“删除位置…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*删除产品
*/
受保护的整数doInBackground(字符串…args){
字符串selectedId=args[0];
//检查成功标签
int success=0;//0=failed 1=success
试一试{
//建筑参数
List params=new ArrayList();
添加(新的BasicNameValuePair(“id”,selectedId));
//通过发出HTTP请求获取产品详细信息
JSONObject json=jsonParser.makeHttpRequest(
url_删除_配置文件,“发布”,参数);
//检查日志中的json响应
Log.d(“删除产品”,json.toString());
//json成功标记
success=json.getInt(TAG_success);
//如果(成功==1){
//产品已成功删除
//通过发送代码100通知以前的活动
//Intent i=getIntent();
//发送结果代码100以通知产品删除
//setResult(100,i);
//您不能在工作线程上更新UI,它必须在UI线程上完成
//Toast.makeText(getApplicationContext(),“位置已删除”,
//吐司。长度(短)。show();
//完成();
// }
}捕获(JSONException e){
e、 printStackTrace();
}
回归成功;
}
/**
*完成后台任务后,关闭“进度”对话框
* *
*/
受保护的void onPostExecute(整数结果){
//一旦删除产品,请关闭该对话框