[英]A very easy parse json PHP on Android
我對此很陌生。 我已經閱讀,觀看並嘗試了很多教程,但是為了理解它的工作原理,我找不到非常簡單的東西。
我已經制作了一個php
文件,您可以在其中查看"result.php"
形式的結果。 在表格中,您可以插入First-name
和Last-name
。 那些被保存在數據庫中。
在"result.php"
,您可以看到以下結果:
{"nametable":[{"fname":"","lname":""},{"fname":"ni","lname":"gi"}]}
現在,我想在我的Android代碼上找到一種簡單的方法,以便理解它,它只是一個文本視圖並顯示名字。.我不想與按鈕混淆,只是一個頁面,它將顯示數據庫中的變量!
有沒有人可以幫助我編寫代碼,以了解其工作方式?
謝謝!!
這是我使用org.json庫和OkHttp客戶端制作的一個簡單代碼示例。
它將從服務器檢索JSON,並在TextViews中顯示每個名字。
注意:我沒有測試它,它可能無法編譯,但是您明白了。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewWrapper"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TextView's will be appended here -->
</LinearLayout>
MyActivity.java
//...other imports
import org.json.*;
import okhttp3.*;
public class MyActivity extends AppCompatActivity {
private LinearLayout textViewWrapper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get TextView Wrapper
textViewWrapper = (LinearLayout) findViewById(R.id.textViewWrapper);
fillTextView();
}
/**
* Fill TextViews with API response.
*
*/
public void fillTextView() {
get("http://example.com/result.php", new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String body = response.body().string(); //Get API response
//OKHttp callback isn't in the main thread,
//UI operations need to be run in the main thread
//That's why you should use runOnUiThread
MyActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject JSON = null;
try {
//Parse JSON
JSON = new JSONObject(body);
//Get "nametable" array
JSONArray nameTable = JSON.getJSONArray("nametable");
//Loop through "nametable" array
for (int i = 0; i < nameTable.length(); i++) {
JSONObject item = nameTable.getJSONObject(i);
//Create TextView
TextView rowTextView = new TextView(MyActivity.this);
//Set fname
rowTextView.setText(item.getString("fname"));
// add the textview
textViewWrapper.addView(rowTextView);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
/**
* OKHttp GET helper function (You should probably put this in a Request Utils class)
*
*/
public Call get(String url, Callback callback) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
有關此問題中的JSON解析的更多信息: 如何在Java中解析JSON
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.