AsyncTask类插入数据到服务器与接口回调

////////////////2016/04/21/////////////////////

//////////////by XBW///////////////////////////

///////////环境  api22 eclipse /////////////

搞了这么久终于弄好了接口,之前都是一个人在做项目,自己随心所欲的写代码,想怎么写就怎么写,到了团队呢,这接口那接口,各种类,各种枚举,各种内部类,抽象类,单例懒汉,单例饿汉的,也算学了不少东西,

我做的是把数据插入到数据库的一个线程类,继承的AsyncTask类,

按照惯例,先上效果图,

服务器已经获取到修改的数据了,今天主要不是布局,界面有点丑,主要是封装的AsyncTask类,上代码详细介绍

jar包的内容,

AsyncTask_Change.java是继承的AsyncTask类,是主要的类,

Config_mysql.java是配置类,配置的服务器端php返回json的url,

Info_Type.java是数据类型,用的枚举一一列举出来的,

JSONParser是向服务器收发json数据的类,是个工具类吧,

Progress_Dialog是一个系统的插入数据进度环显示,没有自定义布局,所有不需要xml文件,

上代码咯

AsyncTask_Change.java

package com.example.matrix.mysql;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.example.matrix.LoginActivity;
import com.example.matrix.mysql.Info_Type.INFOTYPE;
import com.example.matrix.util.ProgressDialogs;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class AsyncTask_Change extends AsyncTask<String, String, String> {
	// mysql
	JSONParser jsonParser = new JSONParser();
	private static String url_up = Config_mysql.Get_URLPATH();
	private static String url_s = "";
	private static final String TAG_MESSAGE = "message";
	Config_mysql USERYETEXIST = new Config_mysql();
	Context context;
	ProgressDialog dialog;
	boolean result = false;

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

	@SuppressWarnings("deprecation")
	public Config_mysql Mysql_Change(String ID, String INFO, INFOTYPE TYPE) {
		String id = ID;
		String info = INFO;
		INFOTYPE type = TYPE;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("user_phone", id));
		switch (type) {
		case brand:
			params.add(new BasicNameValuePair("brand", info));
			url_s = INFOTYPE.brand.getUrl();
			break;
		case logo:
			url_s = INFOTYPE.logo.getUrl();
			params.add(new BasicNameValuePair("logo", info));
			break;
		case platenum:
			url_s = INFOTYPE.platenum.getUrl();
			params.add(new BasicNameValuePair("platenum", info));
			break;
		case enginenum:
			url_s = INFOTYPE.enginenum.getUrl();
			params.add(new BasicNameValuePair("enginenum", info));
			break;
		case carlevel:
			url_s = INFOTYPE.carlevel.getUrl();
			params.add(new BasicNameValuePair("carlevel", info));
			break;
		case colometer:
			url_s = INFOTYPE.colometer.getUrl();
			params.add(new BasicNameValuePair("colometer", info));
			break;
		case enginestate:
			url_s = INFOTYPE.enginestate.getUrl();
			params.add(new BasicNameValuePair("enginestate", info));
			break;
		case shiftstate:
			url_s = INFOTYPE.shiftstate.getUrl();
			params.add(new BasicNameValuePair("shiftstate", info));
			break;
		case light:
			url_s = INFOTYPE.light.getUrl();
			params.add(new BasicNameValuePair("light", info));
			break;
		case oilcount:
			url_s = INFOTYPE.oilcount.getUrl();
			params.add(new BasicNameValuePair("oilcount", info));
			break;
		case order_time:
			url_s = INFOTYPE.order_time.getUrl();
			params.add(new BasicNameValuePair("order_time", info));
			break;
		case gas_station:
			url_s = INFOTYPE.gas_station.getUrl();
			params.add(new BasicNameValuePair("gas_station", info));
			break;
		case gas_type:
			url_s = INFOTYPE.gas_type.getUrl();
			params.add(new BasicNameValuePair("gas_type", info));
			break;
		case gas_num:
			url_s = INFOTYPE.gas_num.getUrl();
			params.add(new BasicNameValuePair("gas_num", info));
			break;
		case user_name:
			url_s = INFOTYPE.user_name.getUrl();
			params.add(new BasicNameValuePair("user_name", info));
			break;
		case user_age:
			url_s = INFOTYPE.user_age.getUrl();
			params.add(new BasicNameValuePair("user_age", info));
			break;
		case user_image_head:
			url_s = INFOTYPE.user_image_head.getUrl();
			params.add(new BasicNameValuePair("user_image_head", info));
			break;
		case user_sex:
			url_s = INFOTYPE.user_sex.getUrl();
			params.add(new BasicNameValuePair("user_sex", info));
			break;
		case user_schoolname:
			url_s = INFOTYPE.user_schoolname.getUrl();
			params.add(new BasicNameValuePair("user_schoolname", info));
			break;
		case user_password:
			url_s = INFOTYPE.user_password.getUrl();
			params.add(new BasicNameValuePair("user_password", info));
			break;
		case user_bg:
			url_s = INFOTYPE.user_bg.getUrl();
			params.add(new BasicNameValuePair("user_bg", info));
			break;
		case user_sign:
			url_s = INFOTYPE.user_sign.getUrl();
			params.add(new BasicNameValuePair("user_sign", info));
			break;
		case user_signtime:
			url_s = INFOTYPE.user_signtime.getUrl();
			params.add(new BasicNameValuePair("user_signtime", info));
			break;
		}
		try {
			JSONObject json = jsonParser.makeHttpRequest(url_up + url_s,
					"POST", params);
			String message = json.getString(TAG_MESSAGE);
			if (message.equals("NONET")) {
				USERYETEXIST.Set_isNetWork(false);
			} else {
				USERYETEXIST.Set_httpjsonsuccess(message.equals("YES"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return USERYETEXIST;
	}
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = Progress_Dialog.CreateProgressDialog(context);
		dialog.show();
	}
	@Override
	protected String doInBackground(String... params) {
		// TODO 自动生成的方法存根
		String ID = params[0];
		String INFO = params[1];
		String TYPE = params[2];
		Config_mysql LOG;
		LOG = Mysql_Change(ID, INFO, STRING_INFOTYPE(TYPE));
		String message;
		if (!LOG.Get_isNetWork()) {
			message = "1";
		} else if (LOG.Get_httpjsonsuccess()) {
			message = "2";
		} else {
			message = "3";
		}
		return message;
	}
/////////////////////////////////////////////////////////////////////////////////////
	public interface MysqlListener {         //回调接口
		public void Success();
		public void Fail();
	}
	private MysqlListener mysqlListener=null;
	public void setMysqlListener(MysqlListener mysqlListener) {
		this.mysqlListener = mysqlListener;
	}                                                                             

/////////////////////////////////////////////////////////////////////////////////////
	@SuppressLint("ShowToast")
	protected void onPostExecute(String message) {
		dialog.dismiss();
		if(mysqlListener!=null){
			if (message.equals("2")) {
				mysqlListener.Success();
			} else {
				mysqlListener.Fail();
			}
		}
		if (message.equals("1")) {
			Toast.makeText(context, "网络连接失败", 8000).show();
		} else if (message.equals("2")) {
			Toast.makeText(context, "修改成功", 8000).show();
		} else {
			Toast.makeText(context, "修改失败", 8000).show();
		}
	}

	public INFOTYPE STRING_INFOTYPE(String TYPE) {
		INFOTYPE type = null;
		switch (TYPE) {
		case "brand":
			type = INFOTYPE.brand;
			break;
		case "logo":
			type = INFOTYPE.logo;
			break;
		case "platenum":
			type = INFOTYPE.platenum;
			break;
		case "enginenum":
			type = INFOTYPE.enginenum;
			break;
		case "carlevel":
			type = INFOTYPE.carlevel;
			break;
		case "colometer":
			type = INFOTYPE.colometer;
			break;
		case "enginestate":
			type = INFOTYPE.enginestate;
			break;
		case "shiftstate":
			type = INFOTYPE.shiftstate;
			break;
		case "light":
			type = INFOTYPE.light;
			break;
		case "oilcount":
			type = INFOTYPE.oilcount;
			break;
		case "order_time":
			type = INFOTYPE.order_time;
			break;
		case "gas_station":
			type = INFOTYPE.gas_station;
			break;
		case "gas_type":
			type = INFOTYPE.gas_type;
			break;
		case "gas_num":
			type = INFOTYPE.gas_num;
			break;
		case "user_name":
			type = INFOTYPE.user_name;
			break;
		case "user_image_head":
			type = INFOTYPE.user_image_head;
			break;
		case "user_age":
			type = INFOTYPE.user_age;
			break;
		case "user_schoolname":
			type = INFOTYPE.user_schoolname;
			break;
		case "user_sex":
			type = INFOTYPE.user_sex;
			break;
		case "user_password":
			type = INFOTYPE.user_password;
			break;
		case "user_bg":
			type = INFOTYPE.user_bg;
			break;
		case "user_sign":
			type = INFOTYPE.user_sign;
			break;
		case "user_signtime":
			type = INFOTYPE.user_signtime;
			break;
		}
		return type;
	}

	public static String INFOTYPE_STRING(INFOTYPE TYPE) {
		String type = null;
		switch (TYPE) {
		case brand:
			type = "brand";
			break;
		case logo:
			type = "logo";
			break;
		case platenum:
			type = "platenum";
			break;
		case enginenum:
			type = "enginenum";
			break;
		case carlevel:
			type = "carlevel";
			break;
		case colometer:
			type = "colometer";
			break;
		case enginestate:
			type = "enginestate";
			break;
		case shiftstate:
			type = "shiftstate";
			break;
		case light:
			type = "light";
			break;
		case oilcount:
			type = "oilcount";
			break;
		case order_time:
			type = "order_time";
			break;
		case gas_station:
			type = "gas_station";
			break;
		case gas_type:
			type = "gas_type";
			break;
		case gas_num:
			type = "gas_num";
			break;
		case user_name:
			type = "user_name";
			break;
		case user_age:
			type = "user_age";
			break;
		case user_schoolname:
			type = "user_schoolname";
			break;
		case user_sex:
			type = "user_sex";
			break;
		case user_image_head:
			type = "user_image_head";
			break;
		case user_password:
			type = "user_password";
			break;
		case user_bg:
			type = "user_bg";
			break;
		case user_sign:
			type = "user_sign";
			break;
		case user_signtime:
			type = "user_signtime";
			break;
		}
		return type;
	}
}

Config_mysql.java

package com.example.matrix.mysql;

public class Config_mysql {

	public static String URLPATH="http://000.000.000.000/mysql/";
	public boolean httpjsonsuccess=false;
	public boolean isNetWork=true;//http请求是否成功
	public void Set_httpjsonsuccess(boolean httpjsonsuccess)
	{
		this.httpjsonsuccess=httpjsonsuccess;
	}
	public boolean Get_httpjsonsuccess()
	{
		return httpjsonsuccess;
	}
	public void Set_isNetWork(boolean isNetWork)
	{
		this.isNetWork=isNetWork;
	}
	public boolean Get_isNetWork()
	{
		return isNetWork;
	}
	public void Set_URLPATH(String URLPATH)
	{
		this.URLPATH=URLPATH;
	}
	public static String Get_URLPATH()
	{
		return URLPATH;
	}

}

Info_Type.java

package com.example.matrix.mysql;

public class Info_Type {

	public enum INFOTYPE{

		//keep保养
        brand {public String getUrl(){return "keep/change_brand.php";}public INFOTYPE getType(){return brand;}public String getName(){return "brand";}},

        logo {public String getUrl(){return "keep/change_logo.php";}public INFOTYPE getType(){return logo;}public String getName(){return "logo";}},

        platenum {public String getUrl(){return "keep/change_platenum.php";}public INFOTYPE getType(){return platenum;}public String getName(){return "platenum";}},

        enginenum {public String getUrl(){return "keep/change_enginenum.php";}public INFOTYPE getType(){return enginenum;}public String getName(){return "enginenum";}},

        carlevel {public String getUrl(){return "keep/change_carlevel.php";}public INFOTYPE getType(){return carlevel;}public String getName(){return "carlevel";}},

        colometer {public String getUrl(){return "keep/change_colometer.php";}public INFOTYPE getType(){return colometer;}public String getName(){return "colometer";}},

        enginestate {public String getUrl(){return "keep/change_enginestate.php";}public INFOTYPE getType(){return enginestate;}public String getName(){return "enginestate";}},

        shiftstate {public String getUrl(){return "keep/change_shiftstate.php";}public INFOTYPE getType(){return shiftstate;}public String getName(){return "shiftstate";}},

        light {public String getUrl(){return "keep/change_light.php";}public INFOTYPE getType(){return light;}public String getName(){return "light";}},

        oilcount {public String getUrl(){return "keep/change_oilcount.php";}public INFOTYPE getType(){return oilcount;}public String getName(){return "oilcount";}},

        //order预约
        order_time {public String getUrl(){return "order/change_time.php";}public INFOTYPE getType(){return order_time;}public String getName(){return "order_time";}},

        gas_station {public String getUrl(){return "order/change_gasstation.php";}public INFOTYPE getType(){return gas_station;}public String getName(){return "gas_station";}},

        gas_type {public String getUrl(){return "order/change_gastype.php";}public INFOTYPE getType(){return gas_type;}public String getName(){return "gas_type";}},

        gas_num {public String getUrl(){return "order/change_gasnum.php";}public INFOTYPE getType(){return gas_num;}public String getName(){return "gas_num";}},

        //用户
        user_name {public String getUrl(){return "user/change_nickname.php";}public INFOTYPE getType(){return user_name;}public String getName(){return "user_name";}},

        user_password {public String getUrl(){return "user/change_password.php";}public INFOTYPE getType(){return user_password;}public String getName(){return "user_password";}},

        user_image_head {public String getUrl(){return "user/change_head.php";}public INFOTYPE getType(){return user_image_head;}public String getName(){return "user_image_head";}},

        user_age {public String getUrl(){return "user/change_age.php";}public INFOTYPE getType(){return user_age;}public String getName(){return "user_age";}},

        user_sex {public String getUrl(){return "user/change_sex.php";}public INFOTYPE getType(){return user_sex;}public String getName(){return "user_sex";}},

        user_schoolname {public String getUrl(){return "user/change_schoolname.php";}public INFOTYPE getType(){return user_schoolname;}public String getName(){return "user_schoolname";}},

        user_sign {public String getUrl(){return "user/change_sign.php";}public INFOTYPE getType(){return user_sign;}public String getName(){return "user_sign";}},

        user_signtime {public String getUrl(){return "user/change_signtime.php";}public INFOTYPE getType(){return user_signtime;}public String getName(){return "user_signtime";}},

        user_bg {public String getUrl(){return "user/change_bg.php";}public INFOTYPE getType(){return user_bg;}public String getName(){return "user_bg";}};
        public abstract INFOTYPE getType();
        public abstract String getName();
        public abstract String getUrl();
	}

}

JSONParser.java

package com.example.matrix.mysql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

@SuppressWarnings("deprecation")
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public JSONParser() {
    }
    @SuppressWarnings("deprecation")
	public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();                

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            json = "{\"success\":\"2\",\"message\":NONET}"; //网络连接失败返回json
            Log.d("json", json.toString());
        }
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;

    }
}

Progress_Dialog.java

package com.example.matrix.mysql;

import android.app.ProgressDialog;
import android.content.Context;

public class Progress_Dialog {

	@SuppressWarnings("deprecation")
	public static ProgressDialog CreateProgressDialog(Context context)
	{
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage("数据加载中……");
		dialog.setCancelable(false);
		return dialog;
	}

}

代码已全部贴出,demo正在写,需要请留言……

时间: 2024-11-12 19:42:37

AsyncTask类插入数据到服务器与接口回调的相关文章

SQL server触发器、存储过程操作远程数据库插入数据,解决服务器已存在的问题

近期弄了一个小项目,也不是非常复杂,须要将一个数据库的一些数据备份到另外一个库.不是本地,可能是网络上其它的数据库.想了一下,用了存储过程和触发器. 也不是非常复杂,首先我须要操作远程数据库,于是写了一个存储过程: CREATE PROCEDURE sendInfoToRemoteDb @CardNo varchar(50), @CardStyle varchar(20), @userId varchar(20), @UserName varchar(30), @passDate datetim

接口回调和向上转型

抄别人的,但为了自己掌握更加的踏实,所以复制到这里,拜谢原创!http://blog.csdn.net/u014025369/article/details/24707525 接口回调是指:可以把使用实现了某一接口的类创建的对象的引用赋给该接口声明的接口变量,那么该接口变量就可以调用被类实现的接口的方法.实际上,当接口变量调用被类实现的接口中的方法时,就是通知相应的对象调用接口的方法,这一过程称为对象功能的接口回调.看下面示例.interface People {     void people

Java中的接口回调

接口回调是多态的另一种体现.接口回调是指:可以把使用某一个接口的类创建的对象的引用赋给该接口声明的接口变量中,那么该接口变量就可以调用被类实现的接口中的方法.当接口变量调用被类实现的接口中的方法时,就是通知相应的对象调用接口的方法,成为接口回调.不同的类在使用同一接口时,可能具有不同的功能体现.即接口的方法体不必相同,因此接口回调可能产生不同的行为. 接口回调会方便功能的扩展,在主功能外由框架层实现定制功能处理. 现在有两个类,一个是A,一个是B,回调就是A去调用B中的某个方法,然后B又回调A中

Linux服务器使用命令操作MySQL插入数据乱码问题

服务器上使用MySQL命令方式进行插入数据时,很多时候会遇到插入数据乱码问题,导出一个sql执行文件,再倒入到unbutn中,结果出现乱码,折腾7-8分钟, 解决方式 在导出mysql sql执行文件的时候,指定一下编码格式: 复制代码代码如下: mysqldump -uroot -p --default-character-set=utf8 mo(dbname) > E://xxxx.sql 导入的时候OK了 执行如下 复制代码代码如下: mysql -u root -p --default-

往数据库插入上万条数据避免服务器崩溃

<?php //mysql执行时间 ini_set('max_execution_time', '0'); ignore_user_abort(TRUE); //如果客户端断开连接,不会引起脚本abort //链接数据库:链接的服务器,拥有服务器进程的用户的名称,密码 $con[email protected]mysql_connect("localhost","root","root"); // 判断数据库是否连接 if(!$con){

.Net批量插入数据到SQLServer数据库,SqlBulkCopy类批量插入大数据到数据库

批量的的数据导入数据库中,尽量少的访问数据库,高性能的对数据库进行存储. 采用SqlBulkCopy来处理存储数据.SqlBulkCopy存储大批量的数据非常的高效,将内存中的数据表直接的一次性的存储到数据库中,而不需要一次一次的向数据库Insert数据. 经过几次实验,百万级别的数据表,也只需几秒时间内就可以完全的存入数据库中,其速度,比传统的Insert into方法不止快很多倍. 下面看代码: /// <summary> /// 批量插入数据 /// </summary> /

【数据源】24万数据集:社会发展类公开数据清单

[数据源]24万数据集:社会发展类公开数据清单 2016-01-06 周炜乐 数盟 数盟是一个开放的数据科学交流社区,致力于成为发现与培养“数据科学家”的基地,欢迎关注数盟或推荐数盟给身边的小伙伴- 公开数据能帮助记者找到好故事.验证信息.来自34个国家的24万数据如何一搜可得?有哪些关于社会发展议题的权威门户可以将数据一网打尽?遇到海量数据,想批量转换格式怎么办?深度君再次奉上公开数据门户清单,另外推荐转换文件格式神器,方便各位各取所需. 1.欧盟数据门户(European Data Port

AGS中通过FeatureServer插入数据失败、插入数据在WMTS请求中无法显示以及version概念的讨论

1.背景 在多个项目中,当我方接口给其他部门人员使用时出现了插入数据失败或者插入的数据在WMTS请求中无法显示出来的问题.针对这些问题,我在这篇文章中,将详细描述造成以上问题的原因.在此WebGIS产品的前台和后台接口中,此插入数据核心部分均是FeatureServer请求.所以我们首先对FeatureSever服务做一个大致的了解. 2.FeatureServer服务的大致了解 2.1 FeatureServer服务提供的功能 FeatureServer服务可以提供如下几种服务: 我们可以得出

Android提交数据到服务器的两种方式四种方法

Android应用开发中,会经常要提交数据到服务器和从服务器得到数据,本文主要是给出了利用http协议采用HttpClient方式向服务器提交数据的方法. /** * @author Dylan * 本类封装了Android中向web服务器提交数据的两种方式四种方法 */ public class SubmitDataByHttpClientAndOrdinaryWay { /** * 使用get请求以普通方式提交数据 * @param map 传递进来的数据,以map的形式进行了封装 * @p