新的开始,新的知识。
在学习android的过程中,mooc课程中有一个让我们使用Spinner下拉框选择省、市、区三个操作,无奈我是一个懒人,我不想写那么多的地点,而且还是一个安卓新手,所以我就打起了调用api这个心思,本来是有点后端的基础的,于是我就学习了一下android中的OkHttp。话不多说,我们来看现象吧。
在AndroidManinfest.xml文件中添加这行代码。详细位置可以在文章最后面查看。
<uses-permission android:name="android.permission.INTERNET" />
在gradle中添加一下配置文件,主要看最后三行,为jar文件。
由于我对fastJOSN比较熟悉,所以和GSON混用,勿见怪。
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.alibaba:fastjson:1.1.71.android'
}
接下来,对以下网址进行get请求即可。
//获取省
http://guolin.tech/api/china
//获取市
http://guolin.tech/api/china/20
//获取区
http://guolin.tech/api/china/20/158
以下举一个最简单的例子:
void getProvinces() {
okHttpUtils = OkHttpUtils.getInstance();
okHttpUtils.getRequest(BaseUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
showMessageAllProv(json);
}
public void showMessageAllProv(String str) {
runOnUiThread(() -> {
try {
JSONArray jsonArray = new JSONArray(str);
provArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject param = JSONObject.parseObject(jsonArray.get(i).toString());
provArray[i] = param.getString("name");
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_dropdown_item_1line, provArray);
spinner1.setAdapter(arrayAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
});
}
});
}
最后是所有的文件。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fifthwork">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
gradle文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.fifthwork"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.alibaba:fastjson:1.1.71.android'
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00BCD4"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="@+id/spinner1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"></Spinner>
<Spinner
android:id="@+id/spinner2"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"></Spinner>
<Spinner
android:id="@+id/spinner3"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"></Spinner>
</LinearLayout>
<TextView
android:textSize="60dp"
android:text="安卓9、10可能会不兼容"
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
MainActivity.java
package com.example.fifthwork;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Spinner spinner1, spinner2, spinner3;
private OkHttpUtils okHttpUtils;
String BaseUrl = "http://guolin.tech/api/china";
String[] noAnyElem = new String[]{""};
//省
int provNum = 1;
String[] provArray;
//市
int cityNum = 1;
String[] cityArray;
Map<String,Integer> cityMap;
//区
String[] districtArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("workfive");
setSupportActionBar(toolbar);
initView();
getProvinces();
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
provNum = position+1;
getCities();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String cityName = parent.getItemAtPosition(position).toString();
cityNum = cityMap.get(cityName);
getDistricts();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
void initView() {
textView = findViewById(R.id.show);
spinner1 = findViewById(R.id.spinner1);
spinner2 = findViewById(R.id.spinner2);
spinner3 = findViewById(R.id.spinner3);
}
void getProvinces() {
okHttpUtils = OkHttpUtils.getInstance();
okHttpUtils.getRequest(BaseUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
showMessageAllProv(json);
}
public void showMessageAllProv(String str) {
runOnUiThread(() -> {
try {
JSONArray jsonArray = new JSONArray(str);
provArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject param = JSONObject.parseObject(jsonArray.get(i).toString());
provArray[i] = param.getString("name");
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_dropdown_item_1line, provArray);
spinner1.setAdapter(arrayAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
});
}
});
}
void getCities() {
okHttpUtils = OkHttpUtils.getInstance();
okHttpUtils.getRequest(BaseUrl+"/"+provNum, new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
showMessageAllCities(json);
}
public void showMessageAllCities(String str) {
runOnUiThread(() -> {
try {
JSONArray jsonArray = new JSONArray(str);
cityArray = new String[jsonArray.length()];
cityMap = new HashMap<String,Integer>();
if(cityMap!=null){
cityMap.clear();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject param = JSONObject.parseObject(jsonArray.get(i).toString());
cityArray[i] = param.getString("name");
cityMap.put(param.getString("name"),param.getInteger("id"));
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_dropdown_item_1line, cityArray);
spinner2.setAdapter(arrayAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
});
}
});
}
void getDistricts() {
okHttpUtils = OkHttpUtils.getInstance();
okHttpUtils.getRequest(BaseUrl+"/"+provNum+"/"+cityNum, new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
showMessageAllDis(json);
}
public void showMessageAllDis(String str) {
runOnUiThread(() -> {
try {
JSONArray jsonArray = new JSONArray(str);
districtArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject param = JSONObject.parseObject(jsonArray.get(i).toString());
districtArray[i] = param.getString("name");
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_dropdown_item_1line, districtArray);
spinner3.setAdapter(arrayAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
});
}
});
}
}
OkHttpUtil工具类:
package com.example.fifthwork;
import android.util.Log;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* create by zy on 08/22/2019
* consult zhy OkHttpUtils
*/
public class OkHttpUtils {
private volatile static OkHttpUtils mInstance;
private OkHttpClient mokHttpClient;
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
public OkHttpUtils(OkHttpClient okHttpClient) {
if (okHttpClient == null) {
mokHttpClient = new OkHttpClient();
} else {
mokHttpClient = okHttpClient;
}
}
public static OkHttpUtils initClient(OkHttpClient okHttpClient) {
if (mInstance == null) {
synchronized (OkHttpUtils.class) {
if (mInstance == null) {
mInstance = new OkHttpUtils(okHttpClient);
}
}
}
return mInstance;
}
public static OkHttpUtils getInstance() {
return initClient(null);
}
/**
* Get Request
*
* @param getUrl request url(get)
* @param callback callback interface by okHttp
*/
public void getRequest(String getUrl, final Callback callback) {
new Thread(() -> {
Request request = new Request.Builder()
.url(getUrl)
.build();
mokHttpClient.newCall(request).enqueue(callback);
}).start();
}
/**
* POST Request
*
* @param data afferent json data we can be afferent Map List pojo...
* @param postUrl request url(post)
* @param callback callback interface by okHttp
*/
public void postRequest(final Object data, String postUrl, final Callback callback) {
new Thread(() -> {
String json = FastJsonUtil.ToJson(data);
Log.d("Send Json -->",json);
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
mokHttpClient.newCall(request).enqueue(callback);
}).start();
}
}
FastJsonUtil工具类:
package com.example.fifthwork;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* create by zy on 08/25/19
*/
public class FastJsonUtil {
//take json format data to java bean
public static <T> T toBean(String jsonData, Class<T> tClass) {
return JSON.parseObject(jsonData, tClass);
}
//take arbitrary object to json format data
public static String ToJson(Object obj) {
return JSON.toJSONString(obj);
}
//get json string one of single values
public static Object getSingleValue(String jsonData, String key) {
JSONObject jsonObject = JSONObject.parseObject(jsonData);
return jsonObject.get(key);
}
//get multiple values in the json string
public static List<String> getValue(String jsonData, String...key){
List<String> jsonList = new ArrayList<>();
JSONObject jsonObject = JSONObject.parseObject(jsonData);
for (int i = 0; i < key.length; i ++){
jsonList.add(String.valueOf(jsonObject.get(key[i])));
}
return jsonList;
}
//take json string to Java List Array
public static <T> List<T> toList(String jsonData, Class<T> tClass) {
return JSON.parseArray(jsonData, tClass);
}
//take json string to Java Map Array
public static Map<String, Object> toMap(String jsonData){
return JSON.parseObject(jsonData,new TypeReference<Map<String, Object>>(){});
}
//take json string to List<Map<String,Object>> Array
public static List<Map<String, Object>> toListMap(String jsonData){
return JSON.parseObject(jsonData,new TypeReference<List<Map<String, Object>>>(){});
}
}
三个实体类:
package com.example.fifthwork;
public class City {
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
package com.example.fifthwork;
public class County {
private int id;
private String countyName;
private String weatherId;
private int cityId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getWeatherId() {
return weatherId;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
package com.example.fifthwork;
public class Province {
private int id;
private String provinceName;
private int provinceCode;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public int getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(int provinceCode) {
this.provinceCode = provinceCode;
}
}