您的位置:首页 > 理论基础 > 计算机网络

android-async-http异步出现的问题

2015-08-22 23:01 633 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/u013235922/article/details/47866179

相信大家对android-async-http-master并不陌生,在实际开发中如果稍不注意有可能会出现数据不同步,应为框架是异步访问网络的。
建议阅读此文章前学习过Xutils和Gson两个框架的基础。
话不多说,看下面的项目, 上代码:

1、登录界面

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >

<ImageView
android:id="@+id/function"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp"
android:src="@drawable/ke" />

<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/relativeLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:background="@drawable/login"
android:text="登  录"
android:textColor="#FFFFFF" />

<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/function"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:background="@drawable/kuang" >

<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp"
android:src="@drawable/username" />

<ImageView
android:id="@+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imageView2"
android:layout_below="@+id/imageView2"
android:layout_marginTop="16dp"
android:src="@drawable/password" />

<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/imageView2"
android:layout_toRightOf="@+id/imageView2"
android:background="@null"
android:ems="10"
android:hint="用户名"
android:text="yanjun" >
</EditText>

<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/imageView3"
android:layout_toRightOf="@+id/imageView3"
android:background="@null"
android:ems="10"
android:hint="密码"
android:inputType="textPassword"
android:text="123456" />
</RelativeLayout>

<TextView
android:id="@+id/new_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/function"
android:text="注    册"
android:textColor="#18b4ed"
android:textSize="18sp" />

</RelativeLayout>

2、登录界面对应的Java类MainActivity.java

package com.example.asynchttp;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity
{
@ViewInject(R.id.login)
Button login;
@ViewInject(R.id.username)
EditText editUsername;
@ViewInject(R.id.password)
EditText editPassword;

private String username;
private String password;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewUtils.inject(this);

initView();
login.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (HttpUtil.login(username, password, MainActivity.this))
{
loginSuccess();
}
}
});
}

private void initView()
{
username = editUsername.getText().toString();
password = editPassword.getText().toString();
}

private void loginSuccess()
{
DbUtils dbUser = DbUtils.create(this);
UserInfo findFirst = null;
try
{
findFirst = dbUser.findFirst(UserInfo.class);
System.out.println(findFirst);
System.out.println(findFirst.getNickname());
}
catch (DbException e)
{
e.printStackTrace();
}
}
}

3、访问网络的工具类HttpUtil.java

package com.example.asynchttp;

import org.apache.http.Header;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.Toast;

@SuppressLint("ShowToast")
@SuppressWarnings("deprecation")
public class HttpUtil
{
private static AsyncHttpClient client;
private static boolean isLogin = true;

private static AsyncHttpClient getInstance(Context paramContext)
{
if (client == null)
{
client = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(
paramContext);
client.setCookieStore(myCookieStore);
}
return client;
}

// 用户登录
public static boolean login(final String uN, final String pW,
final Context con)
{
String url = URLS.API_LOGIN;
RequestParams params = new RequestParams();
params.put("username", uN);
params.put("password", pW);
client = getInstance(con);

client.post(url, params, new TextHttpResponseHandler()
{
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3)
{
Toast.makeText(con, "网络连接或服务器错误", 1);
}

@Override
public void onSuccess(int arg0, Header[] arg1, String response)
{
Result resp = GsonUtils.fromJson(response, Result.class);
UserInfo userinfo = resp.getUser();
DbUtils dbUser = DbUtils.create(con);
try
{
dbUser.deleteAll(UserInfo.class);
dbUser.save(userinfo);
isLogin = true;
}
catch (DbException e)
{
e.printStackTrace();
}
}
});
return isLogin;
}
}

4、解析json数据的工具类GsonUtils.java

package com.example.asynchttp;

import java.lang.reflect.Type;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class GsonUtils {
/**
* 年月日时分秒
*/
public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 年月日
*/
public static final String PATTERN2 = "yyyy-MM-dd";
/**
* 日期格式(年月日时分秒)
*/
private static Gson gson = new GsonBuilder().setDateFormat(PATTERN).create();
/**
* 日期格式(年月日)
*/
private static Gson gson2 = new GsonBuilder().setDateFormat(PATTERN2).create();
/**
* 对象转JSON
* @param src
* @return
* @throws JsonSyntaxException
*/
public static String toJson(Object src) throws JsonSyntaxException {
return gson.toJson(src);
}
/**
* JSON转对象-日期格式(年月日时分秒)
* @param json
* @param typeOfT
* @return
*/
public static <T> T fromJson(String json, Type typeOfT) {
return gson.fromJson(json, typeOfT);
}
/**
* JSON转对象-日期格式(年月日时分秒)
* @param json
* @param classOfT
* @return
*/
public static  <T> T fromJson(String json, Class<T> classOfT) {
return gson.fromJson(json, classOfT);
}
/**
* JSON转对象-日期格式(年月日)
* @param json
* @param typeOfT
* @return
*/
public static <T> T fromJson2(String json, Type typeOfT) {
return gson2.fromJson(json, typeOfT);
}
/**
* JSON转对象-日期格式(年月日)
* @param json
* @param classOfT
* @return
*/
public static <T> T fromJson2(String json, Class<T> classOfT) {
return gson2.fromJson(json, classOfT);
}
/**
* 根据 key得到json里面的value值
* @param jsonStr
* @param key
* @return
*/
public static Object getJsonValue(String jsonStr, String key) {
Object rulsObj = null;
Map<?, ?> rulsMap = jsonToMap(jsonStr);
if (rulsMap != null && rulsMap.size() > 0) {
rulsObj = rulsMap.get(key);
}
return rulsObj;
}
/**
* 将json格式转换成map对象
* @param jsonStr
* @return
*/
public static Map<?, ?> jsonToMap(String jsonStr) {
Map<?, ?> objMap = null;
if (gson != null) {
Type type = new TypeToken<Map<?, ?>>(){}.getType();
objMap = gson.fromJson(jsonStr, type);
}
return objMap;
}

}

5、下面是两个实体类不用多说
Result.java

package com.example.asynchttp;

public class Result
{
private int id;
private UserInfo user; // 用户
private int status;
private String message;
private String error;

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public int getStatus()
{
return status;
}

public void setStatus(int status)
{
this.status = status;
}

public String getMessage()
{
return message;
}

public void setMessage(String message)
{
this.message = message;
}

public String getError()
{
return error;
}

public void setError(String error)
{
this.error = error;
}

public UserInfo getUser()
{
return user;
}

public void setUser(UserInfo user)
{
this.user = user;
}

}

UserInfo.java

package com.example.asynchttp;

import java.util.Date;

public class UserInfo
{
/**
* ID
*/
private int id;
/**
* 邮箱
*/
private String email;
/**
* 昵称
*/
private String nickname;

private String head_img;

public String getHead_img()
{
return head_img;
}

public void setHead_img(String head_img)
{
this.head_img = head_img;
}

/**
* 手机号
*/
private String cellphone;
/**
* 性别0:男1:女
*/
private int gender;
/**
* 真实姓名
*/
private String realname;
/**
* 学号
*/
private String code;
/**
* 学校名称
*/
private String school_name;
/**
* 学校代码
*/
private int school_code;
/**
* 院系
*/
private String department;
/**
* 出售日期
*/
private Date birthday;
/**
* 是否已完善信息 1-是 0-否
*/
private int is_full;

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getEmail()
{
return email;
}

public void setEmail(String email)
{
this.email = email;
}

public String getNickname()
{
return nickname;
}

public void setNickname(String nickname)
{
this.nickname = nickname;
}

public String getCellphone()
{
return cellphone;
}

public void setCellphone(String cellphone)
{
this.cellphone = cellphone;
}

public int getGender()
{
return gender;
}

public void setGender(int gender)
{
this.gender = gender;
}

public String getRealname()
{
return realname;
}

public void setRealname(String realname)
{
this.realname = realname;
}

public String getCode()
{
return code;
}

public void setCode(String code)
{
this.code = code;
}

public String getSchool_name()
{
return school_name;
}

public void setSchool_name(String school_name)
{
this.school_name = school_name;
}

public int getSchool_code()
{
return school_code;
}

public void setSchool_code(int school_code)
{
this.school_code = school_code;
}

public String getDepartment()
{
return department;
}

public void setDepartment(String department)
{
this.department = department;
}

public Date getBirthday()
{
return birthday;
}

public void setBirthday(Date birthday)
{
this.birthday = birthday;
}

public int getIs_full()
{
return is_full;
}

public void setIs_full(int is_full)
{
this.is_full = is_full;
}

}

6、下面是通信接口URLS.java

/**
* 服务器地址
*/
public static String HOST="http://115.28.189.220/iclass";
/**
* 登录接口
*/
public static String API_LOGIN = HOST + "/login";

最后不要忘记加权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

当然这是错误的示范, 执行之后会出现异常,因为实际开发中是需要这样分层的,框架是异步的所以很容易出现数据不同步,细心的同学可能会去调试这个项目, 会发现在执行onSuccess的时候就会return true,所以把数据保存到数据库的时候就不一定什么时候执行了。
那么应该怎么解决,这是代码分层必须要处理的问题,:-(, 今天刚刚开学忙了一天, 决绝方法就不写了, 等下次更新博客的时候会处理这个问题,收拾收拾先睡了,还请亲们谅解啊。~~~~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐