您的位置:首页 > 移动开发 > Android开发

android端通过接口获取数据库中数据

2016-07-29 09:00 337 查看
   百度了下,好像都没找到想要的,或许是我百度错了关键字吧。我这就介绍一种我现在刚学的方法。   首先web端费给我们一个接口文档。我这就接触到两块内容:(1)通过接口传递单纯的数字,例如登录啊,我把用户输的账号密码获取 传给服务器,它会返回给我成功或失败。  我现在的登录接口参数如下:服务器返回给我的参数:其他的参数不用在意,我这登录只用到userInfo里的phoneNum和userPsw(账号和密码)。把里面的userInfo抽出来形成一个类(例:UserInfo.java。名字要跟接口是一样的,没试过是不是必须的..)UserInfo.java:(也就是对着参数一堆get set方法+构造函数)
package xxxxxxx;
public class UserInfo {
public UserInfo(int userId, String userName, String phoneNum, String address, String userPsw, String picAddr) {
this.userId = userId;
this.userName = userName;
this.phoneNum = phoneNum;
this.address = address;
this.userPsw = userPsw;
this.picAddr = picAddr;
}
private int userId;
private String userName;
private String phoneNum;
private String address;
private String userPsw;
private String picAddr;

public int getUserId() {
return userId; }
public void setUserId(int userId) {
this.userId = userId; }
public String getUserName() {
return userName; }
public void setUserName(String userName) {
this.userName = userName;}
public String getPhoneNum() {
return phoneNum; }
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum; }
public String getAddress() {
return address;}
public void setAddress(String address) {
this.address = address;}
public String getUserPsw() {
return userPsw; }
public void setUserPsw(String userPsw) {
this.userPsw = userPsw;}
public String getPicAddr() {
return picAddr;}
public void setPicAddr(String picAddr) {
this.picAddr = picAddr;}
}
LoginModel.java:(恩,这也是一堆get set方法.注意下UserInfo,我们前面已经把它抽成一个类了)
package xxxxxx;
public class LoginModel {
private boolean success;
private String message;
private int readNum;
private int score<
4000
/strong>;
[b]private int contribution;

public LoginModel(boolean success, String message, int readNum, int score, int contribution, UserInfo userInfo) {
this.success = success;
this.message = message;
this.readNum = readNum;
this.score = score;
this.contribution = contribution;
this.userInfo = userInfo;
}
private UserInfo userInfo;
public boolean isSuccess() {
return success; }
public void setSuccess(boolean success) {
this.success = success; }
public String getMessage() {
return message; }
public void setMessage(String message) {
this.message = message; }
public int getReadNum() {
return readNum; }
public void setReadNum(int readNum) {
this.readNum = readNum; }
public int getScore() {
return score; }
public void setScore(int score) {
this.score = score; }
public int getContribution() {
return contribution; }
public void setContribution(int contribution) {
this.contribution = contribution; }
public UserInfo getUserInfo() {
return userInfo; }
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo; }
}
LoginActivity.java:如下是我的一个布局:
package xxxxx;
import xxxx;(这导一堆的包 我就不叙述了 as功能强大)

public class LoginActivity extends Activity {
EditText et_phone;
EditText et_pwd;
Button btn_login;

public static String phone;
String pwd;

String url = xxxx; //这是web端提供给你的url
public static LoginModel myModel;

protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);  //这是我的一个布局

btn_login = (Button) findViewById(R.id.btn_login);
et_phone = (EditText) findViewById(R.id.et_phone);
et_pwd = (EditText) findViewById(R.id.et_pwd);

btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phone = et_phone.getText().toString().trim();
pwd = et_pwd.getText().toString().trim();
loadData();
}
});
}
//这就是通过接口获取数据库中的数据的核心
private void loadData() {
RequestParams params = new RequestParams();
params.addBodyParameter("phoneNum", phone);   //phoneNum要跟接口中的参数名一致
params.addBodyParameter("psw", pwd);
HttpUtils http = new HttpUtils();

http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Gson gson = new Gson();
myModel = gson.fromJson(responseInfo.result, LoginModel.class);
//成功的话,跳转另一个界面
if (myModel.isSuccess()) {
Intent intent = new Intent(LoginActivity.this,BookCrossingMain.class);
//因为我队友要一些数据,所以我把从数据库获得的数据通过Intent传给他
UserInfo myInfo = myModel.getUserInfo();
intent.putExtra("userId",myInfo.getUserId());
intent.putExtra("phoneNum",phone);
intent.putExtra("pwd",pwd);
startActivity(intent);
LoginActivity.this.finish();
}else if(!myModel.isSuccess()){
Toast.makeText(LoginActivity.this,myModel.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(LoginActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
}
});
}
}
(2)通过接口获取listview中数据(栗子:获取评论)
我现在的评论接口参数如下:服务器返回给我的参数:首先还是将commentLis抽成一个类出来,我这就不抽出来啦,将model和commentLis写一起BookCommentModel.java:package xxxxxx;import java.util.List;public class BookCommentModel {public BookCommentModel(boolean success, String message, Object totalpages, int currentpage, int totalrecords, int pagerows, List<CommentLis> commentLis) {this.success = success;this.message = message;this.totalpages = totalpages;this.currentpage = currentpage;this.totalrecords = totalrecords;this.pagerows = pagerows;this.commentLis = commentLis;}private boolean success;private String message;private Object totalpages;private int currentpage;private int totalrecords;private int pagerows;private List<CommentdabaLis> commentLis;public boolean isSuccess() {return success; }public void setSuccess(boolean success) {this.success = success;}public String getMessage() {return message; }public void setMessage(String message) {this.message = message; }public Object getTotalpages() {return totalpages;}public void setTotalpages(Object totalpages) {this.totalpages = totalpages; }public int getCurrentpage() {return currentpage; }public void setCurrentpage(int currentpage) {this.currentpage = currentpage; }public int getTotalrecords() {return totalrecords; }public void setTotalrecords(int totalrecords) {this.totalrecords = totalrecords; }public int getPagerows() {return pagerows; }public void setPagerows(int pagerows) {this.pagerows = pagerows; }public List<CommentLis> getCommentLis() {return commentLis; }public void setCommentLis(List<CommentLis> commentLis) {this.commentLis = commentLis; }
public static class CommentLis {
private int commentId;
private String bookId;
private int userId;
private String comment;
private String commentTime;

public int getCommentId() {
return commentId; }
public void setCommentId(int commentId) {
this.commentId = commentId;  }
public String getBookId() {
return bookId; }
public void setBookId(String bookId) {
this.bookId = bookId; }
public int getUserId() {
return userId; }
public void setUserId(int userId) {
this.userId = userId;  }
public String getComment() {
return comment; }
public void setComment(String comment) {
this.comment = comment;  }
public String getCommentTime() {
return commentTime;  }
public void setCommentTime(String commentTime) {
this.commentTime = commentTime; }
}
}
TabFragmentSecond.java:(这是个fragment,跟activity也一样)
首先这是我的dynamic_list_item.xml
fragment_tab_second:里面只有一个listview
package xxxxxxx;import xxxxx;public class TabFragmentSecond extends Fragment {private ListView lv;BookCommentModel myModel;String url = URL_ADDR.DYNAMIN_URL;View v;private List<View> mViews = new ArrayList<>();//头像private int[] mImgs = {R.drawable.icon_book_head1, R.drawable.icon_book_head2, R.drawable.icon_book_head3,R.drawable.icon_book_head4,R.drawable.icon_book_head5,R.drawable.icon_book_head6};//人名private int[] mNames={1,2,3,4};//评论private String[] mOpinion={"1111111","2222222222222","3333333333","444444444"};//private int count;//评论列表private ListView mListView;//private List<Map<String,Object>> list_data;private TextView dynamic_title;private TextView dynamic_comment;private final String DYNAMIC_PINGLUN="评论 ";@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {v = inflater.inflate(R.layout.fragment_tab_second,container,false);init();return v;}private void init(){mListView=(ListView)v.findViewById(R.id.lv_dynamic);mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {//listview条目 的点击事件}});LoadData();InitData();}private void LoadData() {RequestParams params = new RequestParams();params.addBodyParameter("userId","888");params.addBodyParameter("pages","1");params.addBodyParameter("num","4");HttpUtils http=new HttpUtils();http.send(HttpRequest.HttpMethod.POST,url, params, new RequestCallBack<String>() {@Overridepublic void onSuccess(ResponseInfo<String> responseInfo) {Gson gson=new Gson();BookCommentModel mComment=gson.fromJson(responseInfo.result,BookCommentModel.class);if (mComment.isSuccess()) {count=4;mNames=new int[count];mOpinion=new String[count];for (int i = 0; i < count; i++){mNames[i]=mComment.getCommentLis().get(i).getUserId();mOpinion[i]=mComment.getCommentLis().get(i).getComment();}InitData();}else{Log.i("comment user link","fail");InitData();}}@Overridepublic void onFailure(HttpException error, String msg) {Log.i("comment user onFailure",error.toString());InitData();}});}private void InitData(){list_data=new ArrayList<>();Map<String,Object> map_item;for(int i=0;i<4;i++){map_item=new HashMap<>();map_item.put("image",mImgs[i]);map_item.put("title",mNames[i]);map_item.put("comment",mOpinion[i]);list_data.add(map_item);}SimpleAdapter simpleAdapter=new SimpleAdapter(getActivity(),list_data,R.layout.dynamic_list_item,new String[]{"image","title","comment"},new int[]{R.id.iv_dynamic_icon, R.id.iv_dynamic_title,R.id.iv_dynamic_content});mListView.setAdapter(simpleAdapter);}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 数据库 web