MVP乞丐完整版
程序员文章站
2022-06-13 20:36:35
...
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener,DataCall {
private EditText mMobile,mPassword;
LoginPresenter model = new LoginPresenter(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMobile = findViewById(R.id.login_moblie);
mPassword = findViewById(R.id.login_psw);
findViewById(R.id.login_btn).setOnClickListener(this);
}
@Override
public void onClick(View v) {
final String mobile = mMobile.getText().toString();
final String password = mPassword.getText().toString();
model.login(mobile,password);
}
@Override
public void callback(User data) {
Toast.makeText(getBaseContext(),data.getCode()+" "+data.getMsg(),Toast.LENGTH_LONG).show();
}
}
bean
public class User {
String msg;
String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
datacall接口
public interface DataCall {
void callback(User data);
}
http
public class Utils {
public static String get(String urlString){
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
/* urlConnection.setRequestMethod("GET");//若果是get请求可以不用配置; 其他请求必须配置
urlConnection.setConnectTimeout(8000);//设置链接超时间*/
InputStream inputStream = urlConnection.getInputStream();//获取网络返回的输入流;
//可拼接的字符串
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp = "";
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp);
temp = "";
}
//这个是网络获取的数据
String data = stringBuilder.toString();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
model
public class LoginModel {
public static User login(String mobile, String password){
String loginData = Utils.get("http://www.zhaoapi.cn/user/login?mobile="
+mobile+"&password="+password);
Gson gson = new Gson();
User user = gson.fromJson(loginData,User.class);
return user;
}
}
presenter
public class LoginPresenter {
private DataCall call;
public LoginPresenter(DataCall dataCall){
call = dataCall;
}
private Handler mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
User loginData = (User) msg.obj;
Log.i("dt",""+loginData.getMsg());
call.callback(loginData);
}
};
public void login(final String mobile, final String password){
new Thread(new Runnable() {
@Override
public void run() {
User loginData = LoginModel.login(mobile,password);
Message message = mHandler.obtainMessage();
message.obj = loginData;
mHandler.sendMessage(message);
}
}).start();
}
}
上一篇: 达梦-读写分离集群部署-完整版
下一篇: Intellij Idea配置