master
unknown 2 years ago
parent 884784ee04
commit b7b77a9b72

15
.gitignore vendored

@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties

3
.idea/.gitignore vendored

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="11" />
</component>
</project>

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="jbr-11" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveExternalAnnotations" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="Android Studio default JDK" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

1
app/.gitignore vendored

@ -0,0 +1 @@
/build

@ -0,0 +1,45 @@
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.test'
compileSdk 33
defaultConfig {
applicationId "com.example.test"
minSdk 27
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
debuggable true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.github.gittjy:LoadingDialog:1.0.2'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.12'
implementation "com.squareup.okhttp3:okhttp:4.2.2"
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.github.crazyandcoder:citypicker:6.0.2'
implementation 'com.github.zzz40500:android-shapeLoadingView:1.0.3.2'
}

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

@ -0,0 +1,26 @@
package com.example.test;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.test", appContext.getPackageName());
}
}

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:targetApi="31">
<service
android:name=".service.MessageService"
android:exported="false" />
<activity
android:name=".activity.HomeActivity"
android:exported="false" />
<activity
android:name=".activity.RegisterActivity"
android:exported="false" />
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

@ -0,0 +1,96 @@
package com.example.test;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.test.activity.HomeActivity;
import com.example.test.activity.RegisterActivity;
import com.example.test.entity.User;
import com.example.test.netrequest.UserOkHttp;
import com.example.test.utils.Address;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button registerButton, loginButton;
private EditText usernameText, paswdEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
init();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.register:
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
break;
case R.id.login:
Thread thread = new Thread(login);
thread.start();
}
}
public void init(){
registerButton = findViewById(R.id.register);
registerButton.setOnClickListener(this);
loginButton = findViewById(R.id.login);
loginButton.setOnClickListener(this);
usernameText = findViewById(R.id.username);
paswdEdit = findViewById(R.id.password);
}
Runnable login = new Runnable() {
@Override
public void run() {
String name = usernameText.getText().toString();
String pass = paswdEdit.getText().toString();
UserOkHttp userOkHttp = new UserOkHttp();
User u = new User();
u.setUsername(name);
u.setPassword(pass);
try {
User result = userOkHttp.login(u);
if(result!=null){
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
Bundle bundle = new Bundle();
bundle.putString("username",result.getUsername());
bundle.putString("password",result.getPassword());
bundle.putString("sex",result.getSex());
bundle.putString("city",result.getCity());
bundle.putInt("id",result.getId());
intent.putExtras(bundle);
startActivity(intent);
}else{
Looper.prepare();
Toast.makeText(MainActivity.this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
}

@ -0,0 +1,306 @@
package com.example.test.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.test.R;
import com.example.test.adapter.HomeNavigationBottomAdapter;
import com.example.test.entity.Cart;
import com.example.test.entity.Product;
import com.example.test.entity.ProductKind;
import com.example.test.entity.ProductKindStorage;
import com.example.test.entity.ProductStorage;
import com.example.test.fragment.NavigationCartFragment;
import com.example.test.fragment.NavigationGoodFragment;
import com.example.test.fragment.NavigationHomeFragment;
import com.example.test.fragment.NavigationLoadingFragment;
import com.example.test.fragment.NavigationPersonFragment;
import com.example.test.netrequest.CartOkHttp;
import com.example.test.netrequest.ProductOkHttp;
import com.example.test.service.MessageService;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class HomeActivity extends AppCompatActivity {
public static final int Home = 1;
public static final int Good = 2;
public static final int Cart = 3;
public static final int Person = 4;
public static final int Navigation = 5;
public static final int InsertProductToCart = 6;
public static final int LoadingData = 7;
public static final int UpdateCart = 7;
private int selectedProductId;
private ProductKindStorage productKindStorage = new ProductKindStorage();
private ProductStorage hotProductStorage = new ProductStorage();
private NavigationHomeFragment homeFragment = new NavigationHomeFragment();
private NavigationGoodFragment goodFragment = new NavigationGoodFragment();
private NavigationLoadingFragment loadingFragment = new NavigationLoadingFragment();
private NavigationCartFragment cartFragment = new NavigationCartFragment();
private NavigationPersonFragment personFragment = new NavigationPersonFragment();
private int sectionImgs[] = {R.drawable.section_home,R.drawable.section_good,
R.drawable.section_cart,R.drawable.section_mine};
private String sectionNames[] ={"首页","商品","购物车","我"};
public FragmentManager getManager() {
return manager;
}
public FragmentManager manager = getSupportFragmentManager();
private Bundle extras;
public Handler getHandler() {
return handler;
}
public Bundle getBundle(){
return extras;
}
public ProductKindStorage getProductKindStorage() {
return productKindStorage;
}
public ProductStorage getHotProductStorage() {
return hotProductStorage;
}
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
switch (message.what){
case Good:
changeFragment(goodFragment);
return true;
case Cart:
changeFragment(new NavigationCartFragment());
return true;
case Navigation:
initNavigation();
changeFragment(homeFragment);
return true;
case InsertProductToCart:
// 添加商品进购物车
Map<String,Object> map = (Map<String, Object>) message.obj;
selectedProductId = (Integer) map.get("productId");
new Thread(insertProduct).start();
return true;
case LoadingData:
new Thread(getCart).start();
return true;
}
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
Intent service = new Intent(HomeActivity.this, MessageService.class);
startService(service);
//获取登陆所携带的用户信息
Intent intent = getIntent();
extras = intent.getExtras();
initData();
// 在initData中默认加载homeFragment
}
public void initData() {
//获取商品类别
new Thread(getProductKind).start();
// 获取热门商品
new Thread(getHotProduct).start();
}
public void changeFragment(Fragment fragment){
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.navigation_section,fragment);
transaction.commit();
}
//初始化底端导航栏
protected void initNavigation(){
GridView navigation = (GridView)findViewById(R.id.home_navigation_bottom_gridview);
HomeNavigationBottomAdapter navigationAdapter = new HomeNavigationBottomAdapter(sectionImgs,sectionNames,this);
navigation.setAdapter(navigationAdapter);
navigation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
changeFragment(homeFragment);
break;
case 1:
changeFragment(goodFragment);
break;
case 2:
changeFragment(loadingFragment);
break;
case 3:
changeFragment(personFragment);
break;
}
}
});
}
//获取产品种类
Runnable getProductKind = new Runnable() {
@Override
public void run() {
ProductOkHttp http = new ProductOkHttp();
try {
List<ProductKind> productKinds = http.getProductKind();
if(productKinds!=null){
for (ProductKind p : productKinds) {
productKindStorage.getNames().add(p.getName());
productKindStorage.getBitmaps().add(http.getImg(p.getImgUrl()));
}
}else
{
Looper.prepare();
Toast.makeText(HomeActivity.this,"商品种类获取失败",Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable getHotProduct = new Runnable() {
@Override
public void run() {
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
List<Product> products = productOkHttp.getHotProduct();
if(products != null){
for (Product product : products) {
hotProductStorage.getIds().add(product.getId());
hotProductStorage.getNames().add(product.getName());
hotProductStorage.getBitmaps().add(productOkHttp.getImg(product.getImgUrl()));
hotProductStorage.getPrices().add(product.getPrice());
hotProductStorage.getDescriptions().add(product.getDescription());
hotProductStorage.getTags().add(product.getTag());
hotProductStorage.getKinds().add(product.getKind());
}
Message message = new Message();
message.what = Navigation;
handler.sendMessage(message);
}else {
Looper.prepare();
Toast.makeText(HomeActivity.this,"商品获取失败",Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable getCart = new Runnable() {
@Override
public void run() {
CartOkHttp cartOkHttp = new CartOkHttp();
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
int userId = (int) extras.get("id");
List<Cart> carts = cartOkHttp.selectByUserId(userId);
if(carts.size()!=0){
cartFragment.clearLists();
List<Integer> ids = NavigationCartFragment.productIds;
List<String> names = NavigationCartFragment.names;
List<Bitmap> bitmaps = NavigationCartFragment.bitmaps;
List<Double> prices = NavigationCartFragment.prices;
List<Integer> nums = NavigationCartFragment.nums;
for (com.example.test.entity.Cart cart : carts) {
Integer productId = cart.getProductId();
Product product = productOkHttp.getProductById(productId);
ids.add(product.getId());
names.add(product.getName());
bitmaps.add(productOkHttp.getImg(product.getImgUrl()));
prices.add(product.getPrice());
nums.add(cart.getNum());
}
Message message = new Message();
message.what = Cart;
handler.sendMessage(message);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable insertProduct = new Runnable() {
@Override
public void run() {
Cart c = new Cart(extras.getInt("id"),selectedProductId,1);
CartOkHttp okHttp = new CartOkHttp();
// 是否包含该商品
int postion = containProduct(selectedProductId);
// 包含就加1
if(postion!=-1){
try {
int num = NavigationCartFragment.nums.get(postion);
c.setNum(num+1);
boolean updateResult = okHttp.updateCart(c);
if(!updateResult){
Looper.prepare();
Toast.makeText(HomeActivity.this,"添加失败",Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}else{ //不包含新增
try {
boolean insertResult = okHttp.insertCart(c);
if(!insertResult){
Looper.prepare();
Toast.makeText(HomeActivity.this,"添加失败",Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
};
public int containProduct(int id){
int positon = 0;
List<Integer> ids = NavigationCartFragment.productIds;
for (Integer integer : ids) {
if(id==integer){
return positon;
}
positon++;
}
return -1;
}
}

@ -0,0 +1,184 @@
package com.example.test.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.test.MainActivity;
import com.example.test.R;
import com.example.test.entity.User;
import com.example.test.netrequest.UserOkHttp;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import java.io.IOException;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
private EditText userEdit;
private EditText passEdit;
private EditText paEdit;
private RadioGroup sexBut;
private TextView adressText;
private String sex ="男";
private Button regBut;
CityPickerView citypv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
init();
}
public void init(){
citypv = new CityPickerView();
citypv.init(this);
initConfig();
citypv.setOnCityItemClickListener(new OnCityItemClickListener() {
@Override
public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
String pro = province.getName();
String ci = city.getName();
String dis = district.getName();
adressText.setText(String.format("%s %s %s",pro,ci,dis));
}
@Override
public void onCancel() {
}
});
userEdit = findViewById(R.id.reg_username);
passEdit = findViewById(R.id.reg_password);
paEdit = findViewById(R.id.reg_apassword);
adressText = findViewById(R.id.reg_adress);
adressText.setOnClickListener(this);
sexBut = findViewById(R.id.reg_sex);
sexBut.setOnCheckedChangeListener(this);
regBut = findViewById(R.id.reg_register);
regBut.setOnClickListener(this);
}
private void initConfig() {
CityConfig cityConfig = new CityConfig.Builder()
.title("选择城市")//标题
.titleTextSize(18)//标题文字大小
.titleTextColor("#585858")//标题文字颜 色
.titleBackgroundColor("#E9E9E9")//标题栏背景色
.confirTextColor("#585858")//确认按钮文字颜色
.confirmText("ok")//确认按钮文字
.confirmTextSize(16)//确认按钮文字大小
.cancelTextColor("#585858")//取消按钮文字颜色
.cancelText("cancel")//取消按钮文字
.cancelTextSize(16)//取消按钮文字大小
.setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类,只显示省份一级,显示省市两级还是显示省市区三级
.showBackground(true)//是否显示半透明背景
.visibleItemsCount(7)//显示item的数量
.province("浙江省")//默认显示的省份
.city("杭州市")//默认显示省份下面的城市
.district("滨江区")//默认显示省市下面的区县数据
.provinceCyclic(true)//省份滚轮是否可以循环滚动
.cityCyclic(true)//城市滚轮是否可以循环滚动
.districtCyclic(true)//区县滚轮是否循环滚动
.drawShadows(false)//滚轮不显示模糊效果
.setLineColor("#03a9f4")//中间横线的颜色
.setLineHeigh(5)//中间横线的高度
.setShowGAT(true)//是否显示港澳台数据,默认不显示
.build();
citypv.setConfig(cityConfig);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.reg_adress:
citypv.showCityPicker();
break;
case R.id.reg_register:
Thread thread = new Thread(register);
thread.start();
break;
}
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//根据用户选择来改变sex的值
sex = R.id.reg_male==checkedId?"男":"女";
}
Runnable register = new Runnable() {
@Override
public void run() {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
String username = userEdit.getText().toString();
String password = passEdit.getText().toString();
String apassword = paEdit.getText().toString();
String adress = adressText.getText().toString();
if(password.equals(apassword)){
if(username.isEmpty()||password.isEmpty()){
Looper.prepare();
Toast.makeText(RegisterActivity.this,"用户名或密码为空",Toast.LENGTH_SHORT).show();
Looper.loop();
}else {
if(adress.equals("")||adress.equals("地址选择")) {
Looper.prepare();
Toast.makeText(RegisterActivity.this, "未选择地址", Toast.LENGTH_SHORT).show();
Looper.loop();
}
else{
User u = new User(username,password,sex,adress);
UserOkHttp http = new UserOkHttp();
try {
boolean selectResult = http.selectUser(username);
if(!selectResult){
Looper.prepare();
Toast.makeText(RegisterActivity.this, "用户名已存在", Toast.LENGTH_SHORT).show();
Looper.loop();
return;
}
boolean register = http.register(u);
if(register)
{
startActivity(intent);
}else{
Looper.prepare();
Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
else {
Looper.prepare();
Toast.makeText(RegisterActivity.this,"两次密码不一致",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
};
}

@ -0,0 +1,177 @@
package com.example.test.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import com.example.test.entity.Cart;
import com.example.test.fragment.NavigationCartFragment;
import com.example.test.netrequest.CartOkHttp;
import com.example.test.utils.LoadingDialog;
import java.io.IOException;
import java.io.PipedReader;
import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;
public class CartAdapter extends BaseAdapter {
private List<Bitmap> bitmaps;
private List<String> names;
private List<Double> prices;
private List<Integer> nums;
private List<Integer> productIds;
private Context context;
private Handler handler;
private int userId;
public int selectedNum;
public int selectedProductId;
private viewHolder holder;
private List<Integer> status = new ArrayList<>();
public CartAdapter(List<Bitmap> bitmaps, List<String> names, List<Double> prices, List<Integer> nums , List<Integer> productIds, Handler handler,int userId , Context context) {
this.bitmaps = bitmaps;
this.names = names;
this.prices = prices;
this.nums = nums;
this.context = context;
this.userId = userId;
this.productIds = productIds;
this.handler = handler;
}
public CartAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return bitmaps.size();
}
@Override
public Object getItem(int i) {
List<Object> list = new ArrayList<>();
list.add(bitmaps.get(i));
list.add(names.get(i));
list.add(prices.get(i));
list.add(nums.get(i));
return list;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
if(convertView==null){
holder = new viewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.cart_listview_item,null);
holder.ivImg = convertView.findViewById(R.id.cart_good_img);
holder.tvName = convertView.findViewById(R.id.cart_good_name);
holder.tvPrice = convertView.findViewById(R.id.cart_good_price);
holder.tvNum = convertView.findViewById(R.id.cart_good_num);
holder.ibAdd = convertView.findViewById(R.id.cart_good_add);
holder.ibSub = convertView.findViewById(R.id.cart_good_minus);
holder.cbChecked = convertView.findViewById(R.id.cart_checked);
convertView.setTag(holder);
}else {
holder = (viewHolder) convertView.getTag();
}
holder.ivImg.setImageBitmap(bitmaps.get(i));
holder.tvName.setText(names.get(i));
holder.tvPrice.setText(prices.get(i)+"");
holder.tvNum.setText(nums.get(i)+"");
holder.ibAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//计算点击之后的数量
selectedNum = nums.get(i)+1;
selectedProductId = productIds.get(i);
new Thread(updateCart).start();
}
});
holder.ibSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//计算点击之后的数量
selectedNum = nums.get(i)-1;
selectedProductId = productIds.get(i);
new Thread(updateCart).start();
}
});
holder.cbChecked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
NavigationCartFragment.checkedProductIds.add(productIds.get(i));
}else{
NavigationCartFragment.checkedProductIds.remove(productIds.get(i));
}
Message message = new Message();
message.what = NavigationCartFragment.updatePrice;
handler.sendMessage(message);
}
});
return convertView;
}
static class viewHolder{
ImageView ivImg;
TextView tvName;
TextView tvPrice;
TextView tvNum;
ImageButton ibAdd;
ImageButton ibSub;
CheckBox cbChecked;
}
Runnable updateCart = new Runnable() {
@Override
public void run() {
Looper.prepare();
LoadingDialog dialog = new LoadingDialog.Builder(context, "加载中").create();
dialog.show();
CartOkHttp cartOkHttp = new CartOkHttp();
Cart cart = new Cart(userId, selectedProductId, selectedNum);
try {
boolean updateResult = cartOkHttp.updateCart(cart);
dialog.dismiss();
if(!updateResult){
Toast.makeText(context,"更新失败",Toast.LENGTH_SHORT).show();
Looper.loop();
}else{
holder.tvNum.setText(selectedNum+"");
Message message = new Message();
message.what = NavigationCartFragment.updateCart;
handler.sendMessage(message);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
}

@ -0,0 +1,63 @@
package com.example.test.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CartDetailAdapter extends BaseAdapter {
private Context context;
private List<Bitmap> bitmaps;
private viewHolder holder;
public CartDetailAdapter(Context context, List<Bitmap> bitmaps) {
this.context = context;
this.bitmaps = bitmaps;
}
@Override
public int getCount() {
return bitmaps.size();
}
@Override
public Object getItem(int i) {
return bitmaps.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
if(convertView==null){
holder = new viewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.cart_detail_item,null);
holder.ivImg = convertView.findViewById(R.id.cart_detail_gridview_img);
convertView.setTag(holder);
}else {
holder = (viewHolder) convertView.getTag();
}
holder.ivImg.setImageBitmap(bitmaps.get(i));
return convertView;
}
static class viewHolder{
private ImageView ivImg;
}
}

@ -0,0 +1,117 @@
package com.example.test.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.icu.text.DateFormat;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import com.example.test.entity.ProductStorage;
import java.io.PipedReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GoodItemAdapter extends BaseAdapter {
private List<Integer> ids;
private List<String> names;
private List<Bitmap> bitmaps;
private List<Double> prices;
private List<String> descriptions;
private List<String> tags;
private List<String> kinds;
private Context context;
private viewHolder holder;
private Handler handler;
public GoodItemAdapter(ProductStorage productStorage, Handler handler,Context context) {
this.ids = productStorage.getIds();
this.names = productStorage.getNames();
this.bitmaps = productStorage.getBitmaps();
this.prices = productStorage.getPrices();
this.descriptions = productStorage.getDescriptions();
this.tags = productStorage.getTags();
this.kinds = productStorage.getKinds();
this.context = context;
this.handler = handler;
}
@Override
public int getCount() {
return ids.size();
}
@Override
public Object getItem(int i) {
List<Object> list = new ArrayList();
list.add(ids.get(i));
list.add(names.get(i));
list.add(bitmaps.get(i));
list.add(prices.get(i));
list.add(descriptions.get(i));
list.add(tags.get(i));
list.add(kinds.get(i));
return list;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
if(convertView==null){
holder = new viewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.good_item_listview_item,null);
holder.ivImg = convertView.findViewById(R.id.good_item_listview_img);
holder.tvName = convertView.findViewById(R.id.good_item_listview_name);
holder.tvDescription = convertView.findViewById(R.id.good_item_listview_description);
holder.tvTag = convertView.findViewById(R.id.good_item_listview_tag);
holder.tvPrice = convertView.findViewById(R.id.good_item_listview_price);
holder.ivCart = convertView.findViewById(R.id.good_item_listview_cart);
holder.ivCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String,Object> map = new HashMap();
map.put("productId",ids.get(i));
Message message = new Message();
message.what = HomeActivity.InsertProductToCart;
message.obj = map;
handler.sendMessage(message);
}
});
convertView.setTag(holder);
}else {
holder = (viewHolder) convertView.getTag();
}
holder.ivImg.setImageBitmap(bitmaps.get(i));
holder.tvName.setText(names.get(i));
holder.tvDescription.setText(descriptions.get(i));
holder.tvTag.setText(tags.get(i));
holder.tvPrice.setText("¥"+prices.get(i)+"");
return convertView;
}
static class viewHolder{
ImageView ivImg;
TextView tvName;
TextView tvDescription;
TextView tvTag;
TextView tvPrice;
ImageView ivCart;
}
}

@ -0,0 +1,61 @@
package com.example.test.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.test.R;
import java.util.List;
public class GoodKindAdapter extends BaseAdapter {
private Context context;
private List<String> kinds;
private viewHolder holder;
private int selected =0;
public GoodKindAdapter(Context context, List<String> kinds) {
this.context = context;
this.kinds = kinds;
}
@Override
public int getCount() {
return kinds.size();
}
@Override
public Object getItem(int i) {
return kinds.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view==null){
view = LayoutInflater.from(context).inflate(R.layout.good_kind_listview_item,null);
if(i==selected){
view.setBackgroundColor(Color.rgb(192,192,192));
}
holder = new viewHolder();
holder.tvKind = view.findViewById(R.id.good_kind_listview_kind);
view.setTag(holder);
}else {
holder = (viewHolder) view.getTag();
}
holder.tvKind.setText(kinds.get(i));
return view;
}
static class viewHolder{
TextView tvKind;
}
}

@ -0,0 +1,66 @@
package com.example.test.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.test.R;
import java.util.HashMap;
import java.util.Map;
public class HomeNavigationBottomAdapter extends BaseAdapter {
private int imgs[];
private String names[];
private Context context;
public HomeNavigationBottomAdapter(int[] imgs, String[] names, Context context) {
this.imgs = imgs;
this.names = names;
this.context = context;
}
@Override
public int getCount() {
return imgs.length;
}
@Override
public Object getItem(int position) {
Map<String, Object> section = new HashMap<>();
section.put("img",imgs[position]);
section.put("name",names[position]);
return section;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder holder;
if(convertView==null){
holder = new viewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.home_navigation_bottom_item,null);
holder.ivImg = convertView.findViewById(R.id.home_navigation_bottom_img);
holder.tvName = convertView.findViewById(R.id.home_navigation_bottom_name);
convertView.setTag(holder);
}else {
holder = (viewHolder) convertView.getTag();
}
holder.ivImg.setImageResource(imgs[position]);
holder.tvName.setText(names[position]);
return convertView;
}
static class viewHolder{
ImageView ivImg;
TextView tvName;
}
}

@ -0,0 +1,97 @@
package com.example.test.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HomeProductAdapter extends BaseAdapter {
private List<String> names;
private List<Double> prices;
private List<Bitmap> bitmaps;
private List<Integer> ids;
private Context context;
private Handler handler;
public HomeProductAdapter(List<Bitmap> bitmaps, List<String> names, List<Double> prices, List<Integer> ids, Context context, Handler handler) {
this.bitmaps = bitmaps;
this.names = names;
this.prices = prices;
this.ids = ids;
this.context = context;
this.handler = handler;
}
@Override
public int getCount() {
return names.size();
}
@Override
public Object getItem(int position) {
Map<String, Object> fruit = new HashMap<>();
fruit.put("bitmap",bitmaps.get(position));
fruit.put("name",names.get(position));
fruit.put("price",prices.get(position));
return fruit;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder holder;
if(convertView==null){
holder = new viewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.home_goods_fruit_item,null);
holder.ivImg = convertView.findViewById(R.id.home_goods_fruit_img);
holder.tvName = convertView.findViewById(R.id.home_goods_fruit_name);
holder.tvPrice = convertView.findViewById(R.id.home_goods_fruit_price);
holder.ivCart = convertView.findViewById(R.id.navigation_cart);
holder.ivCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String, Object> cartItem = new HashMap<>();
cartItem.put("productId",ids.get(position));
Message message = new Message();
message.what = HomeActivity.InsertProductToCart;
message.obj = cartItem;
handler.sendMessage(message);
}
});
convertView.setTag(holder);
}else {
holder = (viewHolder) convertView.getTag();
}
holder.ivImg.setImageBitmap(bitmaps.get(position));
holder.tvName.setText(names.get(position));
holder.tvPrice.setText("¥"+prices.get(position)+"");
return convertView;
}
static class viewHolder{
ImageView ivImg;
TextView tvName;
TextView tvPrice;
ImageView ivCart;
}
}

@ -0,0 +1,55 @@
package com.example.test.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.test.R;
import java.util.ArrayList;
import java.util.List;
public class HomeProductKindAdapter extends BaseAdapter {
private List<String> names;
private List<Bitmap> bitmaps;
private Context context;
public HomeProductKindAdapter(List<Bitmap>bitmaps,List<String> names, Context context) {
this.bitmaps = bitmaps;
this.names = names;
this.context = context;
}
@Override
public int getCount() {
return names.size();
}
@Override
public Object getItem(int i) {
List<Object> fruit = new ArrayList<>();
fruit.add(bitmaps.get(i));
fruit.add(names.get(i));
return fruit;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View ConvertView, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.home_fruit_kind_item,null);
ImageView img = view.findViewById(R.id.home_fruit_kind_img);
TextView name = view.findViewById(R.id.home_fruit_kind_name);
img.setImageBitmap(bitmaps.get(i));
name.setText(names.get(i));
return view;
}
}

@ -0,0 +1,50 @@
package com.example.test.entity;
public class Cart {
private Integer id;
private Integer userId;
private Integer productId;
private Integer num;
public Cart(Integer userId, Integer productId, Integer num) {
this.id = id;
this.userId = userId;
this.productId = productId;
this.num = num;
}
public Cart() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}

@ -0,0 +1,52 @@
package com.example.test.entity;
import java.sql.Timestamp;
public class Message {
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getSendTime() {
return sendTime;
}
public void setSendTime(Timestamp sendTime) {
this.sendTime = sendTime;
}
public String getUsed() {
return used;
}
public void setUsed(String used) {
this.used = used;
}
private Integer id;
private String content;
private Timestamp sendTime;
private String used;
@Override
public String toString() {
return "OrangeMessage{" +
"id=" + id +
", content='" + content + '\'' +
", sendTime=" + sendTime +
", used='" + used + '\'' +
'}';
}
}

@ -0,0 +1,78 @@
package com.example.test.entity;
public class Product {
private int id;
private String name;
private double price;
private String description;
private String tag;
private String imgUrl;
private String kind;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Product() {
}
public Product(int id, String name, double price, String imgUrl) {
this.id = id;
this.name = name;
this.price = price;
this.imgUrl = imgUrl;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}

@ -0,0 +1,42 @@
package com.example.test.entity;
import java.sql.Timestamp;
public class ProductKind {
private int id;
private String name;
private String imgUrl;
public ProductKind() {
}
public ProductKind(String name, String imgUrl) {
this.name = name;
this.imgUrl = imgUrl;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}

@ -0,0 +1,44 @@
package com.example.test.entity;
import android.graphics.Bitmap;
import com.example.test.entity.ProductKind;
import com.example.test.netrequest.ProductOkHttp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ProductKindStorage {
private List<String> names;
private List<Bitmap> bitmaps;
public ProductKindStorage() {
}
public ProductKindStorage(List<String> names, List<Bitmap> bitmaps) {
this.names = names;
this.bitmaps = bitmaps;
}
public List<String> getNames() {
if(names == null)
names = new ArrayList<>();
return names;
}
public List<Bitmap> getBitmaps() {
if(bitmaps == null)
bitmaps = new ArrayList<>();
return bitmaps;
}
public void setNames(List<String> names) {
this.names = names;
}
public void setBitmaps(List<Bitmap> bitmaps) {
this.bitmaps = bitmaps;
}
}

@ -0,0 +1,86 @@
package com.example.test.entity;
import android.graphics.Bitmap;
import java.util.ArrayList;
import java.util.List;
public class ProductStorage {
private List<Integer> ids;
private List<String> names;
private List<Bitmap> bitmaps;
private List<Double> prices;
private List<String> descriptions;
private List<String> tags;
private List<String> kinds;
public List<Integer> getIds() {
if(ids == null)
ids = new ArrayList<>();
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
public List<String> getNames() {
if(names == null)
names = new ArrayList<>();
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public List<Bitmap> getBitmaps() {
if(bitmaps == null)
bitmaps = new ArrayList<>();
return bitmaps;
}
public void setBitmaps(List<Bitmap> bitmaps) {
this.bitmaps = bitmaps;
}
public List<Double> getPrices() {
if(prices == null)
prices = new ArrayList<>();
return prices;
}
public void setPrices(List<Double> prices) {
this.prices = prices;
}
public List<String> getDescriptions() {
if(descriptions == null)
descriptions = new ArrayList<>();
return descriptions;
}
public void setDescriptions(List<String> descriptions) {
this.descriptions = descriptions;
}
public List<String> getTags() {
if(tags == null)
tags = new ArrayList<>();
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<String> getKinds() {
if(kinds == null)
kinds = new ArrayList<>();
return kinds;
}
public void setKinds(List<String> kinds) {
this.kinds = kinds;
}
}

@ -0,0 +1,58 @@
package com.example.test.entity;
public class User {
private String username;
private String password;
private String sex;
private String city;
private int id;
public User() {
}
public User(String username, String password, String sex, String city) {
this.username = username;
this.password = password;
this.sex = sex;
this.city = city;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

@ -0,0 +1,7 @@
package com.example.test.fragment;
import androidx.fragment.app.Fragment;
public class GoodItemFragment extends Fragment {
}

@ -0,0 +1,35 @@
package com.example.test.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.fragment.app.Fragment;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import com.example.test.adapter.GoodKindAdapter;
import java.util.List;
public class GoodKindFragment extends Fragment {
private View view;
private HomeActivity activity;
private Handler handler;
private ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.good_kind_listview, container, false);
activity = (HomeActivity) getActivity();
handler = activity.getHandler();
listView = (ListView) view.findViewById(R.id.good_kind_listview);
GoodKindAdapter adapter = new GoodKindAdapter(activity, activity.getProductKindStorage().getNames());
listView.setAdapter(adapter);
return view;
}
}

@ -0,0 +1,266 @@
package com.example.test.fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import com.example.test.adapter.CartAdapter;
import com.example.test.adapter.CartDetailAdapter;
import com.example.test.entity.Cart;
import com.example.test.netrequest.CartOkHttp;
import com.example.test.utils.LoadingDialog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class NavigationCartFragment extends Fragment {
private View cartView;
private HomeActivity activity;
public static List<Bitmap> bitmaps = new ArrayList<>();
public static List<String> names = new ArrayList<>();
public static List<Double> prices = new ArrayList<>();
public static List<Integer> nums = new ArrayList<>();
public static List<Integer> productIds = new ArrayList<>();
private ListView listView;
private CheckBox cbChecked;
private TextView tvPrice;
private TextView tvDetail;
private Button pay;
public static int selectedNum = 0;
private int userId;
public Handler handler;
private boolean cartDetailShow = false;
private PopupWindow popupWindow;
private AlertDialog dialog;
private LoadingDialog loading;
public static List<Integer> checkedProductIds = new ArrayList<>();
private List<Bitmap> checkedBitmaps = new ArrayList<>();
public static final int updatePrice = 1;
public static final int updateCart = 2;
public static final int updateListview = 3;
Handler myHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
switch (message.what){
case updatePrice:
updatePrice();
return true;
case updateCart:
Message updateCartMsg = new Message();
updateCartMsg.what = HomeActivity.UpdateCart;
handler.sendMessage(updateCartMsg);
return true;
case updateListview:
CartAdapter adapter = new CartAdapter(bitmaps, names, prices, nums, productIds, myHandler, userId, activity);
listView.setAdapter(adapter);
tvPrice.setText("0");
loading.dismiss();
return true;
}
return false;
}
});
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
activity = (HomeActivity) getActivity();
userId = activity.getBundle().getInt("id");
handler = activity.getHandler();
if(productIds.size()==0){
cartView = inflater.inflate(R.layout.navigation_cart_empty, container, false);
goShopping();
}else{
cartView = inflater.inflate(R.layout.navigation_cart, container, false);
initListview();
initCashier();
}
return cartView;
}
public void clearLists(){
productIds.clear();
names.clear();
bitmaps.clear();
prices.clear();
nums.clear();
}
public void updatePrice(){
checkedBitmaps.clear();
double total = 0;
for (Integer productId : checkedProductIds) {
int index = productIds.indexOf(productId);
int num = nums.get(index);
double price = prices.get(index);
total += price*num;
checkedBitmaps.add(bitmaps.get(index));
}
tvPrice.setText(total+"");
if(total==0.0){
tvDetail.setVisibility(View.INVISIBLE);
}else{
tvDetail.setVisibility(View.VISIBLE);
}
}
public void setPrice(double price){
tvPrice.setText(price+"");
}
private void goShopping() {
Button button = cartView.findViewById(R.id.navigation_cart_shopping);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
activity.changeFragment(new NavigationGoodFragment());
}
});
}
// 初始化购物车item
public void initListview(){
if(listView == null) {
listView = (ListView) cartView.findViewById(R.id.navigation_cart_listview);
}
CartAdapter adpter = new CartAdapter(bitmaps, names, prices, nums, productIds, myHandler, userId,activity);
listView.setDivider(null);
listView.setDividerHeight(5);
listView.setAdapter(adpter);
}
public void initCashier() {
cbChecked = (CheckBox) cartView.findViewById(R.id.cashier_checked);
Log.i("view",cbChecked+"");
tvPrice = (TextView) cartView.findViewById(R.id.cashier_price);
pay =(Button) cartView.findViewById(R.id.cashier_pay);
tvDetail = (TextView) cartView.findViewById(R.id.cashier_detail);
if(selectedNum==0){
tvPrice.setText("0");
}
//全选绑定监听器
cbChecked.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(cbChecked.isChecked()){
tvDetail.setVisibility(View.VISIBLE);
double total=0.0;
for (int i = 0; i < prices.size(); i++) {
double price = prices.get(i);
total += price*nums.get(i);
}
tvPrice.setText(total+"");
}else{
tvDetail.setVisibility(View.INVISIBLE);
tvPrice.setText("0");
}
}
});
//查看明细绑定监听器
tvDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cartDetailShow = !cartDetailShow;
if(cartDetailShow) {
View detailView = LayoutInflater.from(activity).inflate(R.layout.cart_detail, null);
popupWindow = new PopupWindow(detailView, ViewGroup.LayoutParams.MATCH_PARENT, listView.getHeight());
GridView detailGridview = (GridView) detailView.findViewById(R.id.cart_detail_gridview);
detailGridview.setAdapter(new CartDetailAdapter(activity, checkedBitmaps));
LinearLayout rootView = (LinearLayout) cartView.findViewById(R.id.cart_detail_linearlayout);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
popupWindow.showAtLocation(rootView, Gravity.TOP, 0, 0);
}else{
popupWindow.dismiss();
}
}
});
pay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(popupWindow!=null&&cartDetailShow) {
popupWindow.dismiss();
}
if(Double.parseDouble(tvPrice.getText().toString())==0.0){
Toast.makeText(activity,"您未选中任何商品",Toast.LENGTH_SHORT).show();
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("您确认购买吗?");
builder.setCancelable(true);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialog.dismiss();
loading = new LoadingDialog.Builder(activity, "加载中").create();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
loading.show();
new Thread(deletCart).start();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
Runnable deletCart = new Runnable() {
@Override
public void run() {
CartOkHttp cartOkHttp = new CartOkHttp();
for (Integer id : checkedProductIds) {
int index = productIds.indexOf(id);
Cart cart = new Cart();
cart.setUserId(userId);
cart.setProductId(id);
productIds.remove(index);
bitmaps.remove(index);
names.remove(index);
prices.remove(index);
nums.remove(index);
try {
cartOkHttp.deleteCart(cart);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Message message = new Message();
message.what = updateListview;
myHandler.sendMessage(message);
}
};
}

@ -0,0 +1,255 @@
package com.example.test.fragment;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import com.example.test.adapter.GoodItemAdapter;
import com.example.test.adapter.GoodKindAdapter;
import com.example.test.entity.Product;
import com.example.test.entity.ProductStorage;
import com.example.test.netrequest.ProductOkHttp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class NavigationGoodFragment extends Fragment {
private List<Bitmap> bitmapsList = new ArrayList<>();
private String names[];
private double prices[];
private HomeActivity activity;
private View view;
private Handler handler;
private ListView kind;
private ListView item;
private List<String> productKind;
private ProductStorage productStorage = new ProductStorage();
private int selectedPostion = 0;
public static final int updateProduct = 1;
private TextView tvAll;
private TextView tvPrice;
private TextView tvTime;
private SearchView searchView;
private String keyword;
Handler myHandle = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
switch (message.what){
case updateProduct:
item.setAdapter(new GoodItemAdapter(productStorage,handler,activity));
return true;
}
return false;
}
});
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.navigation_good, container, false);
activity = (HomeActivity) getActivity();
productKind = activity.getProductKindStorage().getNames();
handler = activity.getHandler();
initListview();
initOptions();
return view;
}
public void initOptions() {
tvAll = view.findViewById(R.id.good_item_all);
tvPrice = view.findViewById(R.id.good_item_price);
tvTime = view.findViewById(R.id.good_item_time);
searchView = view.findViewById(R.id.good_searchview);
tvAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(getAllProduct).start();
}
});
tvPrice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(getProcutOrderByPrice).start();
}
});
tvTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(getProcutOrderByPrice).start();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
keyword= s;
new Thread(search).start();
searchView.setIconified(true);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
public void initListview() {
kind = (ListView) view.findViewById(R.id.good_kind_listview);
item = (ListView) view.findViewById(R.id.good_item_listview);
GoodKindAdapter kindAdapter = new GoodKindAdapter(activity, productKind);
kind.setAdapter(kindAdapter);
new Thread(updateItem).start();
kind.setDivider(null);
item.setDivider(null);
kind.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(selectedPostion!=i){
adapterView.getChildAt(selectedPostion).setBackgroundColor(Color.WHITE);
view.setBackgroundColor(Color.rgb(192,192,192));
}
selectedPostion = i;
new Thread(updateItem).start();
}
});
}
public void clearProductStorage(){
productStorage.getIds().clear();
productStorage.getNames().clear();
productStorage.getBitmaps().clear();
productStorage.getPrices().clear();
productStorage.getDescriptions().clear();
productStorage.getTags().clear();
}
private void setProductStorage(List<Product> products) throws IOException {
clearProductStorage();
ProductOkHttp productOkHttp = new ProductOkHttp();
List<String> storageNames = productStorage.getNames();
List<String> storageTags = productStorage.getTags();
List<String> storageDescriptions = productStorage.getDescriptions();
List<Double> storagePrices = productStorage.getPrices();
List<Bitmap> storageBitmaps = productStorage.getBitmaps();
List<Integer> storageIds = productStorage.getIds();
for (Product product : products) {
storageNames.add(product.getName());
storageTags.add(product.getTag());
storageDescriptions.add(product.getDescription());
storagePrices.add(product.getPrice());
storageBitmaps.add(productOkHttp.getImg(product.getImgUrl()));
storageIds.add(product.getId());
}
}
Runnable updateItem = new Runnable() {
@Override
public void run() {
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
List<Product> products = productOkHttp.getProductByKind(productKind.get(selectedPostion));
setProductStorage(products);
Message message = new Message();
message.what = updateProduct;
myHandle.sendMessage(message);
// Log.i("data",productStorage.getIds()+"names"+productStorage.getNames());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable getAllProduct = new Runnable() {
@Override
public void run() {
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
List<Product> products = productOkHttp.getProduct();
setProductStorage(products);
Message message = new Message();
message.what = updateProduct;
myHandle.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable getProcutOrderByPrice = new Runnable() {
@Override
public void run() {
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
List<Product> products = productOkHttp.getProductOrderByPrice();
setProductStorage(products);
Message message = new Message();
message.what = updateProduct;
myHandle.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable getProcutOrderByTime = new Runnable() {
@Override
public void run() {
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
List<Product> products = productOkHttp.getProductOrderByTime();
setProductStorage(products);
Message message = new Message();
message.what = updateProduct;
myHandle.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
Runnable search = new Runnable() {
@Override
public void run() {
ProductOkHttp productOkHttp = new ProductOkHttp();
try {
List<Product> products = productOkHttp.getProductByKeyword(keyword);
if(products==null){
Looper.prepare();
Toast.makeText(activity,"换个关键字",Toast.LENGTH_SHORT).show();
Looper.loop();
return;
}
setProductStorage(products);
Message message = new Message();
message.what = updateProduct;
myHandle.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
}

@ -0,0 +1,71 @@
package com.example.test.fragment;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
import com.example.test.adapter.HomeProductAdapter;
import com.example.test.adapter.HomeProductKindAdapter;
import com.example.test.entity.Cart;
import com.example.test.entity.ProductKindStorage;
import com.example.test.entity.ProductStorage;
import com.example.test.netrequest.CartOkHttp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NavigationHomeFragment extends Fragment {
private ProductStorage hotProductStorage;
private ProductKindStorage productKindStorage;
private HomeActivity activity;
private int productIDNow;
private View view;
private Handler handler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.navigation_home, container, false);
activity = (HomeActivity) getActivity();
handler = activity.getHandler();
initData();
initView();
return view;
}
public void initView() {
//初始化商品种类
GridView kindGridview = (GridView) view.findViewById(R.id.fruit_kind_gridview);
HomeProductKindAdapter kindAdapter = new HomeProductKindAdapter(productKindStorage.getBitmaps(), productKindStorage.getNames(), activity);
kindGridview.setAdapter(kindAdapter);
//初始化商品
GridView fruitGridview = (GridView) view.findViewById(R.id.home_goods_fruit_gridview);
HomeProductAdapter fruitAdapter = new HomeProductAdapter(hotProductStorage.getBitmaps(), hotProductStorage.getNames(), hotProductStorage.getPrices(),hotProductStorage.getIds(), activity, handler);
fruitGridview.setAdapter(fruitAdapter);
}
public void initData() {
productKindStorage = activity.getProductKindStorage();
hotProductStorage = activity.getHotProductStorage();
}
}

@ -0,0 +1,30 @@
package com.example.test.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
public class NavigationLoadingFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.navigation_cart_loading, container, false);
HomeActivity activity = (HomeActivity)getActivity();
Handler handler = activity.getHandler();
Message message = new Message();
message.what = HomeActivity.LoadingData;
handler.sendMessage(message);
return view;
}
}

@ -0,0 +1,41 @@
package com.example.test.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.test.R;
import com.example.test.activity.HomeActivity;
public class NavigationPersonFragment extends Fragment {
private TextView tvName;
private TextView tvSex;
private TextView tvCity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.user, container, false);
HomeActivity activity = (HomeActivity) getActivity();
Bundle bundle = activity.getBundle();
String username = bundle.getString("username");
String sex = bundle.getString("sex");
String city = bundle.getString("city");
tvName = view.findViewById(R.id.user_username);
tvSex = view.findViewById(R.id.user_sex);
tvCity = view.findViewById(R.id.user_city);
tvName.setText("用户名:"+username);
tvSex.setText("性别:"+sex);
tvCity.setText("城市:"+city);
return view;
}
}

@ -0,0 +1,88 @@
package com.example.test.netrequest;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.test.entity.Cart;
import com.example.test.utils.Address;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class CartOkHttp {
private OkHttpClient okHttpClient = new OkHttpClient();
public List<Cart> selectAll() throws IOException {
Request request = new Request.Builder()
.url("http://" + Address.ip + ":8081/orange/shoppingCart/search")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Cart> carts = JSON.parseObject(data, new TypeReference<List<Cart>>() {
});
return carts;
}
public List<Cart> selectByUserId(int userId) throws IOException {
RequestBody requestBody = RequestBody.create(userId+"",MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://" + Address.ip + ":8081/orange/shoppingCart/searchByUserId")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Cart> carts = JSON.parseObject(data, new TypeReference<List<Cart>>() {
});
return carts;
}
public boolean insertCart(Cart c) throws IOException {
String data = JSONObject.toJSONString(c);
RequestBody requestBody = RequestBody.create(data,MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/shoppingCart/insert")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
return jsonObject.getBoolean("flag");
}
public boolean updateCart(Cart c) throws IOException {
OkHttpClient client = new OkHttpClient();
String data = JSONObject.toJSONString(c);
RequestBody requestBody = RequestBody.create(data,MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/shoppingCart/update")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
return jsonObject.getBoolean("flag");
}
public boolean deleteCart(Cart c) throws IOException {
OkHttpClient client = new OkHttpClient();
String data = JSONObject.toJSONString(c);
RequestBody requestBody = RequestBody.create(data,MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/shoppingCart/delete")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
return jsonObject.getBoolean("flag");
}
}

@ -0,0 +1,32 @@
package com.example.test.netrequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.test.entity.Message;
import com.example.test.utils.Address;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MessageOkHttp {
public Message getMessage() throws IOException {
// 获取消息
OkHttpClient okHttpClient = new OkHttpClient();
Message data = null;
Request request = new Request.Builder()
.url("http://"+ Address.ip+":8081/orange/message/consumeMessage")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
data = JSON.parseObject(jsonObject.getString("data"), Message.class);
// 将获取到的消息设为已用
Request comsume = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/message/updateMessage")
.build();
Response execute = okHttpClient.newCall(comsume).execute();
return data;
}
}

@ -0,0 +1,169 @@
package com.example.test.netrequest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.util.TimeUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.test.entity.Product;
import com.example.test.entity.ProductKind;
import com.example.test.utils.Address;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.xml.datatype.Duration;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ProductOkHttp {
private OkHttpClient okHttpClient = new OkHttpClient();
public Bitmap getImg(String imgUrl) throws IOException {
// 替换ip
String url = Address.getImgUrl(imgUrl);
Request request = new Request.Builder()
.url(url)
.build();
Response response = okHttpClient.newCall(request).execute();
byte[] bytes = Objects.requireNonNull(response.body()).bytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
public Product getProductById(int productId) throws IOException {
RequestBody requestBody = RequestBody.create(productId+"", MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://"+ Address.ip +":8081/orange/product/searchById")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
Product p = JSON.parseObject(data, Product.class);
return p;
}
public List<ProductKind> getProductKind() throws IOException {
Request request = new Request.Builder()
.url("http://"+ Address.ip +":8081/orange/product/searchProductKind")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<ProductKind> productKinds = JSON.parseObject(data, new TypeReference<List<ProductKind>>() {
});
return productKinds;
}
public List<Product> getHotProduct() throws IOException {
Request request = new Request.Builder()
.url("http://"+ Address.ip +":8081/orange/product/searchHotProduct")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Product> products = JSON.parseObject(data, new TypeReference<List<Product>>() {
});
return products;
}
//获取全部商品
public List<Product> getProduct() throws IOException {
Request request = new Request.Builder()
.url("http://"+ Address.ip +":8081/orange/product/search")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Product> products = JSON.parseObject(data, new TypeReference<List<Product>>() {
});
return products;
}
//按照种类获取商品
public List<Product> getProductByKind(String kind) throws IOException {
RequestBody requestBody = RequestBody.create(kind, MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://"+ Address.ip +":8081/orange/product/searchProductByKind")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Product> products = JSON.parseObject(data, new TypeReference<List<Product>>() {
});
return products;
}
//按照关键字获取商品
public List<Product> getProductByKeyword(String keyword) throws IOException {
RequestBody requestBody = RequestBody.create(keyword, MediaType.parse("application/json;charset=UTF-8"));
Request request = new Request.Builder()
.url("http://"+ Address.ip +":8081/orange/product/searchProductByKeyword")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Product> products = JSON.parseObject(data, new TypeReference<List<Product>>() {
});
return products;
}
//按时间排序
public List<Product> getProductOrderByTime() throws IOException {
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/product/time")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Product> products = JSON.parseObject(data, new TypeReference<List<Product>>() {
});
return products;
}
// 价格排序
public List<Product> getProductOrderByPrice() throws IOException {
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/product/price")
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
String data = jsonObject.getString("data");
List<Product> products = JSON.parseObject(data, new TypeReference<List<Product>>() {
});
return products;
}
// 上传图片
public boolean uploadImg(byte[] bytes) throws IOException {
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "baixiangguo.png", RequestBody.create(bytes)).build();
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/product/uploadCover")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = JSON.parseObject(response.body().string());
return jsonObject.getBoolean("flag");
}
}

@ -0,0 +1,63 @@
package com.example.test.netrequest;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.test.MainActivity;
import com.example.test.entity.User;
import com.example.test.utils.Address;
import java.io.IOException;
import java.util.PrimitiveIterator;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class UserOkHttp {
private OkHttpClient okHttpClient = new OkHttpClient();
public User login(User u) throws IOException {
String JSONString = JSONObject.toJSONString(u);
MediaType type = MediaType.parse("application/json;charset=utf-8");
RequestBody requestBody = RequestBody.create(JSONString, type);
Request request = new Request.Builder()
.url("http://"+ Address.ip+":8081/orange/user/login")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject result = JSON.parseObject(response.body().string());
JSONObject data = result.getJSONObject("data");
User user = JSON.toJavaObject(data, User.class);
return user;
}
public boolean register(User u) throws IOException {
String jsonString = JSONObject.toJSONString(u);
MediaType type = MediaType.parse("application/json;charset=utf-8");
RequestBody requestBody = RequestBody.create(jsonString, type);
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/user/register")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject result = JSON.parseObject(response.body().string());
return result.getBoolean("flag");
}
public boolean selectUser(String username) throws IOException {
String jsonString = JSONObject.toJSONString(username);
MediaType type = MediaType.parse("application/json;charset=utf-8");
RequestBody requestBody = RequestBody.create(jsonString, type);
Request request = new Request.Builder()
.url("http://"+Address.ip+":8081/orange/user/selectUser")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject result = JSON.parseObject(response.body().string());
return result.getBoolean("flag");
}
}

@ -0,0 +1,106 @@
package com.example.test.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.example.test.R;
import com.example.test.entity.Message;
import com.example.test.netrequest.MessageOkHttp;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
public class MessageService extends Service {
private static Timer timer = null;
private NotificationManager manager;
private NotificationCompat.Builder builder;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
*
*/
private void cleanAllNotification() {
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancelAll();
if (timer != null) {
timer.cancel();
timer = null;
}
}
/**
*
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
long period = 60 * 1000; //1分钟一个周期
if (timer == null) {
timer = new Timer();
}
timer.schedule(new TimerTask() {
@Override
public void run() {
new ConsumeMessageTask().execute();
}
}, 0, period);
return super.onStartCommand(intent, flags, startId);
}
class ConsumeMessageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
/**
* NotificationChannelandroid8.0ApptargetSDKVersion>=26
* channel
* Failed to post notification on channel null
*/
Log.i("start service","enter");
MessageOkHttp http = new MessageOkHttp();
Message msg;
try {
msg = http.getMessage();
if (Objects.nonNull(msg)) {
Log.i("orangeMessage", "run: " + msg.getContent() );
NotificationChannel channel = new NotificationChannel("channel", "通知", NotificationManager.IMPORTANCE_HIGH);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(MessageService.this,"channel");
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
builder.setContentTitle("来自橙一色的系统通知消息");
builder.setSmallIcon(R.drawable.chengzi);
builder.setChannelId("channel");
builder.setContentText(msg.getContent());
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
manager.notify(1, notification);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}

@ -0,0 +1,22 @@
package com.example.test.utils;
import android.util.Log;
public class Address {
public static String ip = "192.168.43.226";
public static String getImgUrl(String url){
StringBuilder sb = new StringBuilder();
String start = url.substring(0,7);
String end = url.substring(7);
sb.append(start);
String[] splits = end.split(":");
for (int i = 0; i < splits.length; i++) {
if(i==0){
sb.append(ip).append(":");
}else{
sb.append(splits[i]);
}
}
return sb.toString();
}
}

@ -0,0 +1,64 @@
package com.example.test.utils;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.example.test.R;
public class LoadingDialog extends Dialog {
public LoadingDialog(@NonNull Context context) {
super(context);
}
public static class Builder{
private Context context;
private String message;
private boolean isShowMessage=true;
private boolean isCancelable=false;
private boolean isCancelOutside=false;
public Builder(Context context, String message) {
this.context = context;
this.message = message;
}
public void setShowMessage(boolean showMessage) {
isShowMessage = showMessage;
}
public void setMessage(String message) {
this.message = message;
}
public void setCancelable(boolean cancelable) {
isCancelable = cancelable;
}
public void setCancelOutside(boolean cancelOutside) {
isCancelOutside = cancelOutside;
}
public LoadingDialog create(){
View view = LayoutInflater.from(context).inflate(R.layout.loading_dialog, null);
LoadingDialog loadingDialog = new LoadingDialog(context);
TextView tvMessage = view.findViewById(R.id.loading_message);;
if(isShowMessage){
tvMessage.setText(message);
}else{
tvMessage.setVisibility(View.GONE);
}
loadingDialog.setContentView(view);
loadingDialog.setCancelable(isCancelable);
loadingDialog.setCanceledOnTouchOutside(isCancelOutside);
return loadingDialog;
}
}
}

@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 700 B

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/loading"
android:fromDegrees="0.0"
android:pivotX="50.0%"
android:pivotY="50.0%"
android:toDegrees="360.0" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape>
<solid android:color="#EFB81C" />
<corners android:radius="5dp" />
</shape>
</item>
<item android:state_pressed="true">
<shape>
<solid android:color="#c0c0c0" />
<corners android:radius="5dp" />
</shape>
</item>
</selector>

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape>
<solid android:color="#c0c0c0" />
</shape>
</item>
<item android:state_pressed="true">
<shape>
<solid android:color="#c0c0c0" />
<corners android:radius="10dp" />
</shape>
</item>
</selector>

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:radius="20dp"/>
<padding
android:left="20dp"
android:top="10dp"
android:right="20dp"
android:bottom="10dp"/>
<gradient
android:startColor="@color/gold"
android:endColor="@color/darkorange"/>
</shape>

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 801 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 790 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 448 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 B

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#008577"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 690 B

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/gray"/>
<corners
android:radius="20dp"/>
</shape>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 787 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 909 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 557 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 889 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save