一個依賴于rxvolley網路框架的有道詞典查詞專案,代碼如下
package com.example.word;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.toolbox.Loger;
import org.json.JSONArray;
import org.json.JSONObject;
public class AddByInternet2 extends AppCompatActivity {
private EditText in;
private Button sure;
private TextView mean,mean2;
private String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addby_internet);
initView();
}
private void initView() {
in=(EditText)findViewById(R.id.in);
sure=(Button)findViewById(R.id.sure);
//為Button添加點擊事件
sure.setOnClickListener(new View.OnClickListener() {
private String h;
@Override
public void onClick(View v) {
/*
1、獲取輸入框的內容
2、判斷輸入是否為空
3、拼接api
4、向服務器發送請求
5、決議資料
6、在頂部顯示
*/
//1、獲取輸入框的內容
String s=in.getText().toString();
//判斷輸入是否為空
if(s==null){
Toast.makeText(AddByInternet2.this,"輸入框不能為空",Toast.LENGTH_LONG).show();
}
//輸入為空
//3.拼接url
String a= "/*此處為有道詞典的API*/";
//4.向服務器發送請求,使用rxvolley網路框架
//get請求簡潔版實作
RxVolley.get(a, new HttpCallback() {
@Override
public void onSuccess(String t) {
Loger.debug("請求到的資料:" + t);
h = eJson(t);
mean=findViewById(R.id.mean);
mean.setText(h);
}
});
}
}
);
}
//決議資料并顯示
private String eJson(String json){
try{
JSONObject jsonObject = new JSONObject(json);
JSONObject object = jsonObject.getJSONObject("basic");
s = "美式發音"+ object.getString("us-phonetic")+"\n"+
"英式發音"+object.getString("uk-phonetic")+"\n"+
"釋義:"+"\n"+object.getString("explains")+"\n"+"網路釋義:"+"\n";
JSONArray ja = jsonObject.getJSONArray("web");
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject3 = (JSONObject) ja.get(i);
s = s +jsonObject3.getString("value")+"\n";
s = s +jsonObject3.getString("key")+"\n";
}
//在頂部顯示
}
catch (Exception e){
e.printStackTrace();
}
return s;
}
}
文本控制元件mean的setText在三星虛擬機和部分機型上沒問題,在我的小米8(miui11)上卻沒辦法顯示出文本,網上查的很多方法都試過了都沒有作用。
uj5u.com熱心網友回復:
setText本身不會有問題,即使有問題也是eJson方法的問題,你還是逐步除錯一下,看看eJson的程序是否正常uj5u.com熱心網友回復:
Android不允許子執行緒中修改ui,請在主執行緒中使用setTextuj5u.com熱心網友回復:
兄弟,你確定,你那個onSuccess函式是在主執行緒中執行的嗎? 在主執行緒中和onSuccess中都列印下執行緒ID,如果不一樣的話,就說明你是在子執行緒中更新了UI,這是不起作用的;你可以用Handler或者rxjava來解決這個問題。轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/62744.html
標籤:Android
