Commit 0f418747 authored by fallenstardust's avatar fallenstardust Committed by GitHub

Merge pull request #121 from zhuhongbozhuhongbo/master

修改先行卡服务器网址
parents f3d4f227 b98e223e
......@@ -6,7 +6,7 @@ import android.os.Parcelable;
/*
This class contains two types of card information:ex-card information and updating log, which is marked
by "type 0" and "type 1", respectively.
本类包括两种卡牌信息,先行卡信息和更新日志(分别由·type 0和type 1表示)。
本类包括两种卡牌信息,先行卡信息和更新日志(分别由·type 0和type 1表示)。
*/
public class ExCard implements Parcelable {
private String name;
......
......@@ -21,7 +21,7 @@ public class ExCardActivity extends BaseActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ex_card);
viewPager = findViewById(R.id.viewPager);
viewPager.setOffscreenPageLimit(2);
viewPager.setOffscreenPageLimit(1);
tabLayout = findViewById(R.id.packagetablayout);
createTabFragment();
......@@ -47,4 +47,19 @@ public class ExCardActivity extends BaseActivity {
return true;
}
//todo 当未下载完先行卡就退出页面时,会导致软件错误退出。未来通过监听返回事件,判断下载状态,若正在下载则阻拦返回键。
//若发生错误或已完成,则不阻拦返回。
@Override
public void onBackPressed() {
// 完全由自己控制返回键逻辑,系统不再控制,但是有个前提是:
// 不要在Activity的onKeyDown或者OnKeyUp中拦截掉返回键
// 拦截:就是在OnKeyDown或者OnKeyUp中自己处理了返回键
//(这里处理之后return true.或者return false都会导致onBackPressed不会执行)
// 不拦截:在OnKeyDown和OnKeyUp中返回super对应的方法
//(如果两个方法都被覆写就分别都要返回super.onKeyDown,super.onKeyUp)
super.onBackPressed();
}
}
package cn.garymb.ygomobile.ex_card;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class ExCardData {
@SerializedName("id")
@Expose
private Long id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("desc")
@Expose
private String desc;
@SerializedName("overallString")
@Expose
private String overallString;
@SerializedName("picUrl")
@Expose
private String picUrl;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getOverallString() {
return overallString;
}
public void setOverallString(String overallString) {
this.overallString = overallString;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
}
\ No newline at end of file
package cn.garymb.ygomobile.ex_card;
import static cn.garymb.ygomobile.Constants.URL_PRE_CARD;
import static cn.garymb.ygomobile.utils.StringUtils.mergeListDelimeter;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageView;
import com.bumptech.glide.RequestBuilder;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import cn.garymb.ygomobile.Constants;
import cn.garymb.ygomobile.lite.R;
import cn.garymb.ygomobile.loader.ImageLoader;
import cn.garymb.ygomobile.ui.plus.DialogPlus;
import cn.garymb.ygomobile.ui.plus.VUiKit;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.OkhttpUtil;
import cn.garymb.ygomobile.utils.glide.GlideCompat;
import okhttp3.Response;
public class ExCardListAdapter extends BaseQuickAdapter<ExCard, BaseViewHolder> {
public class ExCardListAdapter extends BaseQuickAdapter<ExCardData, BaseViewHolder> {
private static final String TAG = ExCardListAdapter.class.getSimpleName();
private ImageLoader imageLoader;
......@@ -34,78 +38,84 @@ public class ExCardListAdapter extends BaseQuickAdapter<ExCard, BaseViewHolder>
public void loadData() {
final DialogPlus dialog_read_ex = DialogPlus.show(getContext(), null, getContext().getString(R.string.fetch_ex_card));
VUiKit.defer().when(() -> {
//Connect to the website
Document document = Jsoup.connect(Constants.URL_YGO233_ADVANCE).get();
Element pre_card_content = document.getElementById("pre_release_cards");
Element tbody = pre_card_content.getElementsByTag("tbody").get(0);
Elements cards = tbody.getElementsByTag("tr");
if (cards.size() > 5000) {//Considering the efficiency of html parse, if the size of
// pre cards list is to large, return null directly.
return null;
}
ArrayList<ExCard> exCardList = new ArrayList<>();
for (Element card : cards) {
Elements card_attributes = card.getElementsByTag("td");
String imageUrl = card_attributes.get(0).getElementsByTag("a").attr("href") + "!half";
String name = card_attributes.get(1).text();
String description = card_attributes.get(2).text();
ExCard exCard = new ExCard(name, imageUrl, description, 0);
exCardList.add(exCard);
}
if (exCardList.isEmpty()) {
return null;
} else {
return exCardList;
}
LogUtil.d(TAG, "start fetch");
List<ExCardData> exCardDataList = null;
try {
Response response = OkhttpUtil.synchronousGet(URL_PRE_CARD, null, null);
String responseBodyString = response.body().string();
Type listType = new TypeToken<List<ExCardData>>() {
}.getType();
Gson gson = new Gson();
// Convert JSON to Java object using Gson
exCardDataList = gson.fromJson(responseBodyString, listType);
} catch (IOException e) {
Log.e(TAG, "Error occured when fetching data from pre-card server");
return null;
}
if (exCardDataList.isEmpty()) {
return null;
} else {
return exCardDataList;
}
})
.fail((e) -> {
//关闭异常
if (dialog_read_ex.isShowing()) {
try {
dialog_read_ex.dismiss();
} catch (Exception ex) {
}
}
LogUtil.i(TAG, "webCrawler fail");
})
.done((exCardDataList) -> {
if (exCardDataList != null) {
LogUtil.i(TAG, "webCrawler done");
getData().clear();
addData(exCardDataList);
notifyDataSetChanged();
}
if (dialog_read_ex.isShowing()) {
try {
dialog_read_ex.dismiss();
} catch (Exception ex) {
}
}
});
}).fail((e) -> {
//关闭异常
if (dialog_read_ex.isShowing()) {
try {
dialog_read_ex.dismiss();
} catch (Exception ex) {
}
}
LogUtil.i(TAG, "webCrawler fail");
}).done(exCardList -> {
if (exCardList != null) {
LogUtil.i(TAG, "webCrawler done");
}
getData().clear();
addData(exCardList);
notifyDataSetChanged();
private static Boolean isMonster(List<String> list) {
for (String data : list) {
if (data.equals("怪兽")) {
return true;
}
if (dialog_read_ex.isShowing()) {
try {
dialog_read_ex.dismiss();
} catch (Exception ex) {
}
}
});
}
return false;
}
@Override
protected void convert(BaseViewHolder helper, ExCard item) {
protected void convert(BaseViewHolder helper, ExCardData item) {
helper.setText(R.id.ex_card_name, item.getName());
helper.setText(R.id.ex_card_description, item.getDescription());
if (item.isUpdatingLog()) {
helper.setGone(R.id.ex_card_image, true);
} else {
helper.setGone(R.id.ex_card_image, false);
ImageView imageview = helper.getView(R.id.ex_card_image);
//the function cn.garymb.ygomobile.loader.ImageLoader.bindT(...)
//cn.garymb.ygomobile.loader.ImageLoader.setDefaults(...)
//is a private function,so I copied the content of it to here
RequestBuilder<Drawable> resource = GlideCompat.with(imageview.getContext()).load(item.getImageUrl());
resource.placeholder(R.drawable.unknown);
resource.error(R.drawable.unknown);
resource.into(imageview);
}
helper.setText(R.id.ex_card_description, item.getDesc());
helper.setText(R.id.ex_card_overall,item.getOverallString());
ImageView imageview = helper.getView(R.id.ex_card_image);
//the function cn.garymb.ygomobile.loader.ImageLoader.bindT(...)
//cn.garymb.ygomobile.loader.ImageLoader.setDefaults(...)
//is a private function,so I copied the content of it to here
RequestBuilder<Drawable> resource = GlideCompat.with(imageview.getContext()).load(item.getPicUrl());
resource.placeholder(R.drawable.unknown);
resource.error(R.drawable.unknown);
resource.into(imageview);
}
}
package cn.garymb.ygomobile.ex_card;
import static cn.garymb.ygomobile.Constants.URL_YGO233_ADVANCE;
import static cn.garymb.ygomobile.Constants.URL_YGO233_FILE;
import static cn.garymb.ygomobile.Constants.URL_YGO233_FILE_ALT;
import static cn.garymb.ygomobile.utils.DownloadUtil.TYPE_DOWNLOAD_EXCEPTION;
......@@ -31,27 +30,25 @@ import org.greenrobot.eventbus.ThreadMode;
import java.io.File;
import cn.garymb.ygomobile.AppsSettings;
import cn.garymb.ygomobile.Constants;
import cn.garymb.ygomobile.bean.events.ExCardEvent;
import cn.garymb.ygomobile.lite.R;
import cn.garymb.ygomobile.ui.activities.WebActivity;
import cn.garymb.ygomobile.ui.home.MainActivity;
import cn.garymb.ygomobile.utils.DownloadUtil;
import cn.garymb.ygomobile.utils.FileUtils;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.ServerUtil;
import cn.garymb.ygomobile.utils.SharedPreferenceUtil;
import cn.garymb.ygomobile.utils.UnzipUtils;
import cn.garymb.ygomobile.utils.YGOUtil;
import ocgcore.DataManager;
public class ExCardListFragment extends Fragment implements View.OnClickListener {
public class ExCardListFragment extends Fragment {
private static final String TAG = String.valueOf(ExCardListFragment.class);
private Context context;
private View layoutView;
private ExCardListAdapter mExCardListAdapter;
private RecyclerView mExCardListView;
private LinearLayout ll_Download;
private TextView textDownload;
private int FailedCount;
......@@ -99,26 +96,24 @@ public class ExCardListFragment extends Fragment implements View.OnClickListener
mExCardListView.setLayoutManager(linearLayoutManager);
mExCardListView.setAdapter(mExCardListAdapter);
mExCardListAdapter.loadData();
textDownload = layoutView.findViewById(R.id.text_download_prerelease);
ll_Download = layoutView.findViewById(R.id.btn_download_prerelease);
ll_Download.setOnClickListener(this);
changeDownloadText();
}
textDownload = layoutView.findViewById(R.id.text_download_precard);
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_download_prerelease:
LinearLayout clickLayout = layoutView.findViewById(R.id.layout_download_precard);
clickLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtil.i(TAG, "start download");
if (downloadState != DownloadState.DOWNLOAD_ING) {
downloadState = DownloadState.DOWNLOAD_ING;
downloadfromWeb(URL_YGO233_FILE);
}
break;
}
}
});
changeDownloadText();
}
/**
* 根据先行卡包状态改变按钮样式
*/
......@@ -129,15 +124,16 @@ public class ExCardListFragment extends Fragment implements View.OnClickListener
} else if (ServerUtil.exCardState == ServerUtil.ExCardState.NEED_UPDATE) {
textDownload.setText(R.string.Download);
} else if (ServerUtil.exCardState == ServerUtil.ExCardState.ERROR) {
/* 查询不到版本号时,提示toast */
textDownload.setText(R.string.Download);
Toast.makeText(getActivity(), R.string.ex_card_check_toast_message_iii, Toast.LENGTH_LONG).show();
WebActivity.open(getActivity(), getString(R.string.ex_card_list_title), URL_YGO233_ADVANCE);
//WebActivity.open(getActivity(), getString(R.string.ex_card_list_title), URL_YGO233_ADVANCE);
} else if (ServerUtil.exCardState == ServerUtil.ExCardState.UNCHECKED) {
//do nothing
//状态UNCHECKED仅在app启动后调用哦你Create()之前短暂存在,所以该情况进行处理
//the UNCHECKED state only exists temporarily before the check action, so we need not handle it.
}
}
//TODO eventbus receive event
@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
......@@ -150,18 +146,19 @@ public class ExCardListFragment extends Fragment implements View.OnClickListener
textDownload.setText(msg.arg1 + "%");
break;
case DownloadUtil.TYPE_DOWNLOAD_EXCEPTION:
downloadState = DownloadState.NO_DOWNLOAD;
++FailedCount;
if (FailedCount <= 2) {
Toast.makeText(getActivity(), R.string.Ask_to_Change_Other_Way, Toast.LENGTH_SHORT).show();
downloadfromWeb(URL_YGO233_FILE_ALT);
}
YGOUtil.showTextToast("error" + msg.obj);
break;
case UnzipUtils.ZIP_READY:
textDownload.setText(R.string.title_use_ex);
YGOUtil.showTextToast("error" + getString(R.string.Download_precard_failed));
break;
case UnzipUtils.ZIP_UNZIP_OK:
// case UnzipUtils.ZIP_READY:
// textDownload.setText(R.string.title_use_ex);
// break;
case DownloadUtil.TYPE_DOWNLOAD_OK:
downloadState = DownloadState.NO_DOWNLOAD;
/* 将先行服务器信息添加到服务器列表中 */
String servername = "";
if (AppsSettings.get().getDataLanguage() == AppsSettings.languageEnum.Chinese.code)
......@@ -196,10 +193,10 @@ public class ExCardListFragment extends Fragment implements View.OnClickListener
}
break;
case UnzipUtils.ZIP_UNZIP_EXCEPTION:
Toast.makeText(context, getString(R.string.install_failed_bcos) + msg.obj,
Toast.LENGTH_SHORT).show();
break;
// case UnzipUtils.ZIP_UNZIP_EXCEPTION:
// Toast.makeText(context, getString(R.string.install_failed_bcos) + msg.obj,
// Toast.LENGTH_SHORT).show();
// break;
// case HomeFragment.TYPE_GET_DATA_VER_OK:
// WebActivity.exCardVer = msg.obj.toString();
// String oldVer = SharedPreferenceUtil.getExpansionDataVer();
......@@ -228,29 +225,22 @@ public class ExCardListFragment extends Fragment implements View.OnClickListener
private void downloadfromWeb(String fileUrl) {
textDownload.setText("0%");//点击下载后,距离onDownloading触发要等几秒,这一延迟会造成软件响应慢的错觉,因此在下载函数开始就设置文本
File file = new File(AppsSettings.get().getResourcePath() + "-preRlease.zip");
String path = AppsSettings.get().getExpansionsPath().getAbsolutePath();
String fileName = Constants.officialExCardPackageName;
File file = new File(path + "/" + fileName);
if (file.exists()) {
/* 删除旧的先行卡包 */
FileUtils.deleteFile(file);
SharedPreferenceUtil.setExpansionDataVer(null);//删除先行卡后,更新版本状态
ServerUtil.exCardState = ServerUtil.ExCardState.NEED_UPDATE;
EventBus.getDefault().postSticky(new ExCardEvent(ExCardEvent.EventType.exCardPackageChange));//删除后,通知UI做更新
}
DownloadUtil.get().download(fileUrl, file.getParent(), file.getName(), new DownloadUtil.OnDownloadListener() {
DownloadUtil.get().download(fileUrl, path, fileName, new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
downloadState = DownloadState.NO_DOWNLOAD;
Message message = new Message();
message.what = UnzipUtils.ZIP_READY;
try {
File ydks = new File(AppsSettings.get().getDeckDir());
File[] subYdks = ydks.listFiles();
for (File files : subYdks) {
if (files.getName().contains("-") && files.getName().contains(" new cards"))
files.delete();
}
UnzipUtils.upZipSelectFile(file, AppsSettings.get().getResourcePath(), ".ypk");
} catch (Exception e) {
message.what = UnzipUtils.ZIP_UNZIP_EXCEPTION;
} finally {
message.what = UnzipUtils.ZIP_UNZIP_OK;//TODO 不对吧,finally是一定执行,这样即使有exception也会发unzip_ok啊
}
message.what = DownloadUtil.TYPE_DOWNLOAD_OK;
handler.sendMessage(message);
}
......@@ -265,11 +255,11 @@ public class ExCardListFragment extends Fragment implements View.OnClickListener
@Override
public void onDownloadFailed(Exception e) {
//下载失败后删除下载的文件
FileUtils.deleteFile(file);
Message message = new Message();
message.what = TYPE_DOWNLOAD_EXCEPTION;
message.obj = e.toString();
handler.sendMessage(message);
}
});
......
......@@ -12,6 +12,9 @@ import java.util.List;
import cn.garymb.ygomobile.lite.R;
/**
* 旧版本用于展示先行卡更新日志的页面,暂不使用。
*/
public class ExCardLogAdapter extends BaseExpandableListAdapter {
public ExCardLogAdapter(Context context) {
......
......@@ -26,6 +26,9 @@ import cn.garymb.ygomobile.ui.plus.DialogPlus;
import cn.garymb.ygomobile.ui.plus.VUiKit;
import cn.garymb.ygomobile.utils.LogUtil;
/**
* 配合cn.garymb.ygomobile.ex_card.ExCardLogAdapter,实现展示先行卡更新日志的页面,暂不使用。
*/
public class ExCardLogFragment extends Fragment implements View.OnClickListener {
private static final String TAG = String.valueOf(ExCardLogFragment.class);
private Context mContext;
......@@ -92,7 +95,7 @@ public class ExCardLogFragment extends Fragment implements View.OnClickListener
}
}).fail((e) -> {
//ر쳣
//关闭异常
if (dialog_read_ex.isShowing()) {
try {
dialog_read_ex.dismiss();
......@@ -111,7 +114,7 @@ public class ExCardLogFragment extends Fragment implements View.OnClickListener
if (exCardLogList != null) {
LogUtil.i(TAG, "webCrawler parse html complete");
}
//ر쳣
//关闭异常
if (dialog_read_ex.isShowing()) {
try {
dialog_read_ex.dismiss();
......
......@@ -29,15 +29,17 @@ public class ExPackageTabAdapter extends FragmentStatePagerAdapter {
Fragment fragment = null;
if (position == 0) {
fragment = new ExCardListFragment();
} else if (position == 1) {
fragment = new ExCardLogFragment();
}
/* 目前只显示一个tab,未来可能添加其他tab */
// else if (position == 1) {
// fragment = new ExCardLogFragment();
// }
return fragment;
}
@Override
public int getCount() {
return 2;
return 1;
}
@Override
......@@ -46,9 +48,10 @@ public class ExPackageTabAdapter extends FragmentStatePagerAdapter {
if (position == 0) {
title = context.getString(R.string.ex_card_list_title);
} else if (position == 1) {
title = context.getString(R.string.ex_card_log_title);
}
// else if (position == 1) {
// title = context.getString(R.string.ex_card_log_title);
// }
return title;
}
}
......@@ -29,6 +29,7 @@ import ocgcore.enums.LimitType;
* 包括LimitManager、CardManager、LimitList
* LimitList负责判断禁止卡等
* field包括LimitManager、CardManager
* 未封装成单例,使用时要构造实例
*/
public class CardLoader implements ICardSearcher {
private final LimitManager mLimitManager;
......
......@@ -307,7 +307,7 @@ public class HomeFragment extends BaseFragemnt implements OnDuelAssistantListene
}
/**
* 根据同服务器状态设置展示列表中每项的颜色(服务器不可用就设置为灰色)
* 根据同服务器状态设置展示列表中每项的颜色(服务器不可用就设置为灰色)
*/
private void changeColor() {
/* 同步设置服务器列表的状态,在syncLoadData()里更新recyclerview的数据,在更新数据时convert()方法自动更改item的颜色 */
......@@ -794,15 +794,10 @@ public class HomeFragment extends BaseFragemnt implements OnDuelAssistantListene
// break;
// }
if (ServerUtil.exCardState == ServerUtil.ExCardState.ERROR) {
WebActivity.open(getContext(), getString(R.string.action_download_expansions), Constants.URL_YGO233_ADVANCE);
LogUtil.i(TAG, "cannot connect to ex card server, open webactivity");
} else {
/* using Web crawler to extract the information of pre card */
LogUtil.i(TAG, "connect to ex card http server, open webactivity");
Intent exCardIntent = new Intent(getActivity(), ExCardActivity.class);
startActivity(exCardIntent);
}
/* 查不到版本号也打开excard安卓原生activity */
Intent exCardIntent = new Intent(getActivity(), ExCardActivity.class);
startActivity(exCardIntent);
break;
case R.id.action_help: {
final DialogPlus dialog = new DialogPlus(getContext());
......
......@@ -22,6 +22,7 @@ public class DownloadUtil {
private final OkHttpClient okHttpClient;
public static final int TYPE_DOWNLOAD_EXCEPTION = 1;
public static final int TYPE_DOWNLOAD_ING = 2;
public static final int TYPE_DOWNLOAD_OK = 3;
//暂时关闭
private static final boolean ENABLE_CACHE = false;
private static final Map<String, Call> cache = new HashMap<>();
......@@ -83,8 +84,8 @@ public class DownloadUtil {
@Override
public void onResponse(Call call, Response response) throws IOException {
if(!response.isSuccessful()){
listener.onDownloadFailed(new Exception("error:"+response.code()));
if (!response.isSuccessful()) {
listener.onDownloadFailed(new Exception("error:" + response.code()));
return;
}
String contentLen = response.header("Content-Length");
......@@ -104,10 +105,11 @@ public class DownloadUtil {
try {
is = response.body().byteStream();
long total = response.body().contentLength();
if(contentLength > 0 && total != contentLength){
if (contentLength > 0 && total != contentLength) {
listener.onDownloadFailed(new Exception("file length[" + total + "] < " + contentLen));
} else {
out = new FileOutputStream(file);
/* 入参为false时,向file覆盖写入 */
out = new FileOutputStream(file, false);
long sum = 0;
while ((len = is.read(buf)) != -1) {
out.write(buf, 0, len);
......@@ -126,11 +128,11 @@ public class DownloadUtil {
IOUtils.close(is);
}
if (saved) {
if (contentLength > 0 && file.length() < contentLength) {
listener.onDownloadFailed(new Exception("file length[" + file.length() + "] < " + contentLen));
} else {
listener.onDownloadSuccess(file);
}
if (contentLength > 0 && file.length() < contentLength) {
listener.onDownloadFailed(new Exception("file length[" + file.length() + "] < " + contentLen));
} else {
listener.onDownloadSuccess(file);
}
}
if (ENABLE_CACHE) {
synchronized (cache) {
......
......@@ -4,6 +4,7 @@ import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
......@@ -197,6 +198,25 @@ public class OkhttpUtil {
client.newCall(request.build()).enqueue(callback);
}
public static Response synchronousGet(String address, Map<String, Object> map, String cookie) throws IOException {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder httpBuilder = HttpUrl.parse(address).newBuilder();
if (map != null) {
for (Map.Entry<String, Object> param : map.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
}
}
Request.Builder request = new Request.Builder()
.url(httpBuilder.build());
Log.e("OkhttpUtil", "为" + httpBuilder.build());
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("cookie", cookie);
}
return client.newCall(request.build()).execute();
}
public static void del(String address, Map<String, Object> map, String cookie, Callback callback) {
OkHttpClient client = new OkHttpClient();
......@@ -292,10 +312,18 @@ public class OkhttpUtil {
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("cookie", cookie);
}
Log.e("OkhttpUtil",json+" 状态 "+ request.build());
Log.e("OkhttpUtil", json + " 状态 " + request.build());
okHttpClient.newCall(request.build()).enqueue(callback);
}
/**
* 将byte[]类型的十六进制数据(不进行解码)转为字符串格式。如,byte[]中存储的值为0xab78,则转换后的字符串的内容为“ab78”,
* byte[]中存储的值为0xb78,则转换后的字符串的内容为“0b78”
* 可用于将byte中的数据不做改变地打印到log中。
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte[] buf) {
if (null == buf) {
return null;
......
......@@ -4,7 +4,7 @@ import static cn.garymb.ygomobile.Constants.ASSET_SERVER_LIST;
import static cn.garymb.ygomobile.Constants.URL_YGO233_DATAVER;
import static cn.garymb.ygomobile.utils.StringUtils.isHost;
import static cn.garymb.ygomobile.utils.StringUtils.isNumeric;
import static cn.garymb.ygomobile.utils.StringUtils.isValidIP;
import static cn.garymb.ygomobile.utils.WebParseUtil.isValidIP;
import android.content.Context;
import android.text.TextUtils;
......@@ -76,8 +76,13 @@ public class ServerUtil {
public void onResponse(Call call, Response response) throws IOException {
failCounter = 0;//充值计数器
String newVer = response.body().string();
/* 服务器有点怪,返回的版本号带个\n,要去掉 */
if (newVer.endsWith("\n")) {
newVer = newVer.substring(0, newVer.length() - 2);
}
serverExCardVersion = newVer;
LogUtil.i(TAG, "ServerUtil fetch pre-card version:" + newVer);
if (!TextUtils.isEmpty(newVer)) {
......
......@@ -51,8 +51,8 @@ public class SharedPreferenceUtil {
return getShareRecord().getInt("StartTimes", 0);
}
public static void setExpansionDataVer(String json) {
getShareRecord().edit().putString("ExpansionsDataVer", json).commit();
public static void setExpansionDataVer(String dataVer) {
getShareRecord().edit().putString("ExpansionsDataVer", dataVer).commit();
}
public static String getExpansionDataVer() {
......
......@@ -3,6 +3,7 @@ package cn.garymb.ygomobile.utils;
import android.text.TextUtils;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
......@@ -82,28 +83,24 @@ public class StringUtils {
return isurl;
}
/**
* 检查字符串是否是IPv4
* 使用分隔符,将List<String>合为一个String
*/
public static boolean isValidIP(String s) {
if (TextUtils.isEmpty(s)) {
return false;
public static String mergeListDelimeter(List<String> list) {
if (list == null || list.isEmpty()) {
return "";
}
String[] arr = s.split("\\.");
if (arr.length != 4) {
return false;
}
for (String value : arr) {
try {
int n = Integer.parseInt(value);
if (!(n >= 0 && n <= 255)) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.size() - 1; i++) {
stringBuilder.append(list.get(i));
stringBuilder.append("|");
}
return true;
stringBuilder.append(list.get(list.size() - 1));
return stringBuilder.toString();
}
}
......@@ -16,6 +16,7 @@ public class UnzipUtils {
public static final int ZIP_READY = 600;
public static final int ZIP_UNZIP_OK = 601;
public static final int ZIP_UNZIP_EXCEPTION = 602;
/**
* 解压缩一个文件
*
......@@ -82,7 +83,7 @@ public class UnzipUtils {
if (entry.isDirectory()) {
continue;
}
if (entry.getName().contains(nameContains)) {
if (entry.getName().contains(nameContains)) {//如果zip中包含.ypk格式的文件,则将其放到/storage/emulated/0/Android/data/cn.garymb.ygomobile.CN/files/ygocore目录下
InputStream is = zf.getInputStream(entry);
String str = folderPath + File.separator + entry.getName();
str = new String(str.getBytes("8859_1"), StandardCharsets.UTF_8);
......
package cn.garymb.ygomobile.utils;
import android.text.TextUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cn.garymb.ygomobile.Constants;
import cn.garymb.ygomobile.ex_card.ExCard;
/**
* 用于解析html网页内容的工具类
*/
public class WebParseUtil {
/**
* 检查字符串是否是IPv4
*/
public static boolean isValidIP(String s) {
if (TextUtils.isEmpty(s)) {
return false;
}
String[] arr = s.split("\\.");
if (arr.length != 4) {
return false;
}
for (String value : arr) {
try {
int n = Integer.parseInt(value);
if (!(n >= 0 && n <= 255)) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
}
return true;
}
public static List<ExCard> loadData() throws IOException {
//Connect to the website
Document document = Jsoup.connect(Constants.URL_YGO233_ADVANCE).get();
Element pre_card_content = document.getElementById("pre_release_cards");
Element tbody = pre_card_content.getElementsByTag("tbody").get(0);
Elements cards = tbody.getElementsByTag("tr");
if (cards.size() > 5000) {//Considering the efficiency of html parse, if the size of
// pre cards list is to large, return null directly.
return null;
}
ArrayList<ExCard> exCardList = new ArrayList<>();
for (Element card : cards) {
Elements card_attributes = card.getElementsByTag("td");
String imageUrl = card_attributes.get(0).getElementsByTag("a").attr("href") + "!half";
String name = card_attributes.get(1).text();
String description = card_attributes.get(2).text();
ExCard exCard = new ExCard(name, imageUrl, description, 0);
exCardList.add(exCard);
}
if (exCardList.isEmpty()) {
return null;
} else {
return exCardList;
}
}
}
......@@ -14,18 +14,29 @@
android:padding="5dp"
android:scrollbars="vertical" />
<!-- 不知道为啥,android:focusableInTouchMode="true"就导致必须按两次linearylayout才触发点击事件
有帖子说:
一个View的点击事件在第一次点击时无效,第二次点击之后才会响应。
最后发现是因为焦点问题,第一次点击实际上是获取焦点,第二次点击才会响应点击事件。
只要在相关控件属性里面加了两个焦点相关的属性:
android:focusable="true"
android:focusableInTouchMode="false"
版权声明:本文为CSDN博主「qiqiname1989」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qiqiname1989/article/details/82177869-->
<LinearLayout
android:id="@+id/btn_download_prerelease"
android:id="@+id/layout_download_precard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginRight="20dp"
android:layout_marginBottom="70dp"
android:layout_marginRight="30dp"
android:layout_marginBottom="100dp"
android:clickable="true"
android:focusableInTouchMode="true"
android:focusableInTouchMode="false"
android:orientation="vertical"
android:padding="10dp">
<Button
android:id="@+id/btn_download_precard"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
......@@ -34,7 +45,7 @@
android:clickable="false" />
<TextView
android:id="@+id/text_download_prerelease"
android:id="@+id/text_download_precard"
android:layout_width="60dp"
android:layout_height="30dp"
android:background="@drawable/ic_radius_bg"
......
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:sml="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:background="@drawable/list_item_bg"
android:orientation="horizontal">
android:orientation="horizontal"
android:paddingBottom="10dp">
<!-- set the layout_height in the linear layout to “wrap_content”
so it doesn’t only show one TextView per page.-->
......@@ -14,16 +13,16 @@
android:id="@+id/ex_card_image"
android:layout_width="@dimen/card_width_middle"
android:layout_height="@dimen/card_height_middle"
android:padding="10dp"
android:layout_gravity="center_vertical"
android:paddingRight="2dp"
android:scaleType="fitXY"
tools:src="@drawable/unknown" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:orientation="vertical">
android:orientation="vertical"
android:padding="10dp">
<cn.garymb.ygomobile.ui.widget.AlwaysMarqueeTextView
android:id="@+id/ex_card_name"
......@@ -40,12 +39,19 @@
android:textSize="15sp"
tools:text="Card Name" />
<TextView
android:id="@+id/ex_card_overall"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/ex_card_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
\ No newline at end of file
......@@ -269,6 +269,7 @@
<string name="Checking_Update">检查更新中,请稍候</string>
<string name="Found_Update">发现新版本,前往下载?</string>
<string name="Checking_Update_Failed">检查更新失败</string>
<string name="Download_precard_failed">先行卡下载失败</string>
<string name="Ask_to_Change_Other_Way">主线获取失败,尝试备选线路中...</string>
<string name="DuelAssistant">决斗助手启用中</string>
<string name="masterrule">学习大师规则</string>
......
......@@ -266,6 +266,7 @@
<string name="Checking_Update">Now Checking Update</string>
<string name="Found_Update">New upGrade is Founded, Download?</string>
<string name="Checking_Update_Failed">Checking Update Failed</string>
<string name="Download_precard_failed">Download pre-cards failed</string>
<string name="Ask_to_Change_Other_Way">trying other way...</string>
<string name="DuelAssistant">DuelAssiatant is On</string>
<string name="masterrule">Master Rule</string>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment