首页
<EditText
android:id="@+id/mobile_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号"
/>
<EditText
android:id="@+id/pwd_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册"
android:onClick="register"/>
注册的bean类
public class UserBean {
public String msg;
public String code;
}
View层
public interface IRegView {
void mobileVerify();
void mobileEmpty();
void pwdVerify();
void success(UserBean userBean);
void failure(String msg);
}
Model层
public class LoginModel {
private Handler handler = new Handler();
public void login(HashMap<String, String> params, final LoginCallback loginCallback){
OkHttpUtils.getInstance().postData(Api.LOGIN_URL, params, new RequestCallback() {
@Override
public void failure(Call call, IOException e) {
if(loginCallback!=null){
loginCallback.failure("请求失败");
}
}
@Override
public void onResponse(Call call, Response response) {
if(response.code() == 200){
String result = null;
try {
result = response.body().string();
parseJsonResult(result,loginCallback);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void parseJsonResult(String result, final LoginCallback loginCallback) {
if(result!=null){
final LoginBean loginBean = new Gson().fromJson(result, LoginBean.class);
handler.post(new Runnable() {
@Override
public void run() {
if (loginCallback!=null){
loginCallback.loginSuccess(loginBean);
}
}
});
}
}
public interface LoginCallback {
void failure(String errorMsg);//网络请求失败
void loginSuccess(LoginBean userBean);
}
}
Presenter层
public class RegisterPresenter {
private RegisterModel registerModel;
private IRegView iRegView;
public RegisterPresenter(IRegView iRegView) {
this.registerModel = new RegisterModel();
this.iRegView = iRegView;
}
public void register(String mobile,String pwd){
if(TextUtils.isEmpty(mobile)){
iRegView.mobileEmpty();
return;
}
if(!RegexValidateUtil.checkCellphone(mobile)){
iRegView.mobileVerify();
return;
}
if(TextUtils.isEmpty(pwd)){
iRegView.pwdVerify();
return;
}
HashMap<String,String> params = new HashMap<>();
params.put("mobile",mobile);
params.put("password",pwd);
registerModel.register(params, new RegisterModel.RegCallback() {
@Override
public void failure(String errorMsg) {
iRegView.failure(errorMsg);
}
@Override
public void success(UserBean userBean) {
iRegView.success(userBean);
}
});
}
}
API接口类
public class Api {
public final static String BASE_URL = "http://www.zhaoapi.cn/";
public final static String LOGIN_URL = BASE_URL+"user/login";
public final static String REG_URL = BASE_URL+"user/reg";
public final static String PRODUCT_URL = BASE_URL+"product/searchProducts";
}
OKhttp工具类
public class OkHttpUtils {
private static OkHttpUtils okHttpUtils;
private OkHttpClient okHttpClient;
private OkHttpUtils(){
okHttpClient = new OkHttpClient.Builder()
.writeTimeout(2000, TimeUnit.MICROSECONDS)
.build();
}
public static OkHttpUtils getInstance(){
if(okHttpUtils == null){
synchronized (OkHttpUtils.class){
if(okHttpUtils == null){
okHttpUtils = new OkHttpUtils();
}
}
}
return okHttpUtils;
}
public void getData(String url, HashMap<String,String> params, final RequestCallback requestCallback){
StringBuilder urlsb = new StringBuilder();
String allUrl = "";
for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
urlsb.append("?").append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
}
allUrl = url+urlsb.toString().substring(0,urlsb.length() - 1);
System.out.println("url:"+allUrl);
Request request = new Request.Builder()
.url(allUrl).get().build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(requestCallback!=null){
requestCallback.failure(call,e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (requestCallback!=null){
requestCallback.onResponse(call,response);
}
}
});
}
public void postData(String url, HashMap<String,String> prams, final RequestCallback requestCallback){
FormBody.Builder formbodyBuilder = new FormBody.Builder();
if(prams!=null&&prams.size()>0){
for (Map.Entry<String, String> stringStringEntry : prams.entrySet()) {
formbodyBuilder.add(stringStringEntry.getKey(),stringStringEntry.getValue());
}
}
Request request = new Request.Builder()
.url(url).post(formbodyBuilder.build()).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(requestCallback!=null){
requestCallback.failure(call,e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(requestCallback!=null){
requestCallback.onResponse(call,response);
}
}
});
}
}
//接口
public interface RequestCallback {
void failure(Call call, IOException e);
void onResponse(Call call, Response response);
}
//正则表达式类
public class RegexValidateUtil {
static boolean flag = false;
static String regex = "";
public static boolean check(String str, String regex) {
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
flag = matcher.matches();
} catch (Exception e) {
flag = false;
}
return flag;
}
/**
* 验证非空
*
* @param
* @return
*/
public static boolean checkNotEmputy(String notEmputy) {
regex = "^\\s*$";
return check(notEmputy, regex) ? false : true;
}
/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean checkEmail(String email) {
String regex = "^\\w+[-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$ ";
return check(email, regex);
}
/**
* 验证手机号码
*
* 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
* 联通号码段:130、131、132、136、185、186、145
* 电信号码段:133、153、180、189
*
* @param cellphone
* @return
*/
public static boolean checkCellphone(String cellphone) {
String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
return check(cellphone, regex);
}
/**
* 验证固话号码
*
* @param telephone
* @return
*/
public static boolean checkTelephone(String telephone) {
String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
return check(telephone, regex);
}
/**
* 验证传真号码
*
* @param fax
* @return
*/
public static boolean checkFax(String fax) {
String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
return check(fax, regex);
}
/**
* 验证QQ号码
*
* @param QQ
* @return
*/
public static boolean checkQQ(String QQ) {
String regex = "^[1-9][0-9]{4,} $";
return check(QQ, regex);
}
}
//主MainActivity
public class MainActivity extends AppCompatActivity implements IRegView{
private EditText useret,pwdet;
private RegisterPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initDatas();
}
private void initDatas() {
presenter = new RegisterPresenter(this);
}
private void initViews() {
useret = findViewById(R.id.mobile_et);
pwdet = findViewById(R.id.pwd_et);
}
public void register(View view) {
presenter.register(useret.getText().toString(),pwdet.getText().toString());
}
@Override
public void mobileVerify() {
Toast.makeText(this, "手机号需11位合法数字", Toast.LENGTH_SHORT).show();
}
@Override
public void mobileEmpty() {
Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
}
@Override
public void pwdVerify() {
Toast.makeText(this,"密码不合法" , Toast.LENGTH_SHORT).show();
}
@Override
public void success(UserBean userBean) {
Toast.makeText(this, userBean.msg, Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, LoginActivity.class));
}
@Override
public void failure(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
//登录页面
<EditText
android:id="@+id/mobile_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号"
/>
<EditText
android:id="@+id/pwd_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:onClick="login"/>
//登录Bean类
public class LoginBean {
public String msg;
public String code;
public User data;
public class User{
public String nickname;
public String icon;
public String mobile;
}
}
//登录接口
public interface ILoginView {
void mobileVerify();
void mobileEmpty();
void pwdVerify();
void success(LoginBean userBean);
void failure(String msg);
}
//登录Model
public class LoginModel {
private Handler handler = new Handler();
public void login(HashMap<String, String> params, final LoginCallback loginCallback){
OkHttpUtils.getInstance().postData(Api.LOGIN_URL, params, new RequestCallback() {
@Override
public void failure(Call call, IOException e) {
if(loginCallback!=null){
loginCallback.failure("请求失败");
}
}
@Override
public void onResponse(Call call, Response response) {
if(response.code() == 200){
String result = null;
try {
result = response.body().string();
parseJsonResult(result,loginCallback);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void parseJsonResult(String result, final LoginCallback loginCallback) {
if(result!=null){
final LoginBean loginBean = new Gson().fromJson(result, LoginBean.class);
handler.post(new Runnable() {
@Override
public void run() {
if (loginCallback!=null){
loginCallback.loginSuccess(loginBean);
}
}
});
}
}
public interface LoginCallback {
void failure(String errorMsg);//网络请求失败 void loginSuccess(LoginBean userBean);
}
}
//登录presenter
public class LoginPresenter {
private LoginModel loginModel;
private ILoginView iLoginView;
public LoginPresenter(ILoginView iLoginView) {
this.iLoginView = iLoginView;
this.loginModel = new LoginModel();
}
public void login(HashMap<String,String> params){
loginModel.login(params, new LoginModel.LoginCallback() {
@Override
public void failure(String errorMsg) {
iLoginView.failure(errorMsg);
}
@Override
public void loginSuccess(LoginBean userBean) {
iLoginView.success(userBean);
}
});
}
}
//登录Activity
public class LoginActivity extends AppCompatActivity implements ILoginView{
private EditText mobileEt,pwdEt;
private LoginPresenter loginPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initViews();
initDatas();
}
private void initDatas() {
loginPresenter = new LoginPresenter(this);
}
private void initViews() {
mobileEt = findViewById(R.id.mobile_et);
pwdEt = findViewById(R.id.pwd_et);
}
public void login(View view) {
HashMap<String,String> params = new HashMap<>();
params.put("mobile",mobileEt.getText().toString());
params.put("password",pwdEt.getText().toString());
loginPresenter.login(params);
}
@Override
public void mobileVerify() {
Toast.makeText(this, "手机号需11位合法数字", Toast.LENGTH_SHORT).show();
}
@Override
public void mobileEmpty() {
Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
}
@Override
public void pwdVerify() {
Toast.makeText(this,"密码不合法" , Toast.LENGTH_SHORT).show();
}
@Override
public void success(LoginBean userBean) {
startActivity(new Intent(this, RecyclerViewActivity.class));
} @Override
public void failure(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
//展示列表
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:onClick="requestProduct"
android:text="展示列表" />
<android.support.v7.widget.RecyclerView
android:id="@+id/productRv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
></android.support.v7.widget.RecyclerView>
//productBean类
public class ProductBean {
public String msg;
public String code;
public List<Product> data;
public class Product{
public String title;
public String images;
}
}
//适配器
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder>implements View.OnClickListener{
private Context context;
private List<ProductBean.Product> list;
private RecyItemOnclick recyItemOnclick=null;
public ProductAdapter(Context context, List<ProductBean.Product> list, RecyItemOnclick recyItemOnclick) {
this.context = context;
this.list = list;
this.recyItemOnclick = recyItemOnclick;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.product_item_layout,viewGroup,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
view.setOnClickListener( this);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
ProductBean.Product product = list.get(i);
String[] imageUrls = product.images.split("\\|");
if(imageUrls!=null&&imageUrls.length>0){
Glide.with(context).load(imageUrls[0]).into(myViewHolder.iv);
}
myViewHolder.tv.setText(product.title);
myViewHolder.itemView.setTag(i);
}
@Override
public int getItemCount() {
return list.size()==0?0:list.size();
}
@Override
public void onClick(View view) {
recyItemOnclick.onItemClickListener(view, ((int) view.getTag()));
}
class MyViewHolder extends RecyclerView.ViewHolder{
private ImageView iv;
private TextView tv;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
iv = itemView.findViewById(R.id.iv);
tv = itemView.findViewById(R.id.tv);
}
}
}
//productActivity类
public class RecyclerViewActivity extends AppCompatActivity {
private ProductBean productBean;
private Handler handler = new Handler();
private ProductAdapter productAdapter;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
initView();
}
private void initView() {
recyclerView = findViewById(R.id.productRv);
}
public void requestProduct(View view) {
HashMap<String,String> params = new HashMap<>();
params.put("keywords","手机");
OkHttpUtils.getInstance().postData(Api.PRODUCT_URL, params, new RequestCallback() {
@Override
public void failure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
String result = null;
if(response.code() == 200){
try {
result = response.body().string();
System.out.println("result:"+result);
parseProductBean(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void parseProductBean(String result) {
productBean = new Gson().fromJson(result, ProductBean.class);
handler.post(new Runnable() {
@Override
public void run() {
fillDatas();
}
});
}
private void fillDatas() {
productAdapter = new ProductAdapter(this, productBean.data, recyItemOnclick);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(productAdapter);
}
private RecyItemOnclick recyItemOnclick=new RecyItemOnclick() {
@Override
public void onItemClickListener(View v, int position) {
startActivity(new Intent(RecyclerViewActivity.this,SaoMaActivity.class));
}
};
}
//点击接口
public interface RecyItemOnclick {
void onItemClickListener(View v, int position);
}
//适配器展示列表xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv"
android:src="@mipmap/ic_launcher"
android:layout_width="80dp"
android:layout_height="80dp"/>
<TextView
android:id="@+id/tv"
android:layout_gravity="center"
android:text="商品标题"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
//扫二维码布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:onClick="scanBtn"
android:text="扫描二维码"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/scan_tv"
android:hint="输入字符"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:onClick="generateBtn"
android:text="生成二维码"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/scanIv"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
//扫二维码API
public class Api extends Application{
@Override
public void onCreate() {
super.onCreate();
ZXingLibrary.initDisplayOpinion(this);
}
}
//扫码类
public class SaoMaActivity extends AppCompatActivity {
private EditText inputEt;
private ImageView scanIv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sao_ma);
initView();
}
private void initView() {
inputEt = findViewById(R.id.scan_tv);
scanIv = findViewById(R.id.scanIv);
}
public void scanBtn(View view){
startActivity(new Intent(this, CaptureActivity.class));
}
public void generateBtn(View view) {
String content = inputEt.getText().toString();
if(TextUtils.isEmpty(content)){
Toast.makeText(this, "请输入关键字", Toast.LENGTH_SHORT).show();
return;
}
Bitmap bitmap = CodeUtils.createImage(content,400,400, BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
scanIv.setImageBitmap(bitmap);
}
}