我一直在关注如何在Android上显示Json数组的教程,我经常得到"无法从服务器获取json。检查互联网连接!"我无法弄清楚原因。我的Json是从一个php文件生成的,当我在浏览器上创建一个列表时,这个工作正常。所以我确定我的Json有效。
编辑:我需要做哪些调整才能从这个网址中读取数据?
来自" https://www.googleapis.com/books/v1/volumes?q=bond"
的JSON数组机器人:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class HomeScreen extends AppCompatActivity{
private ListView lv;
private ProgressDialog progress;
private String url="https://www.googleapis.com/books/v1/volumes?q=bond";
ArrayList<HashMap<String,String>> booklist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
booklist=new ArrayList<>();
lv= (ListView) findViewById(R.id.list);
new getBooks().execute();
}
public class getBooks extends AsyncTask<Void,Void,Void> {
protected void onPreExecute(){
super.onPreExecute();
progress=new ProgressDialog(HomeScreen.this);
progress.setMessage("Fetching JSON.,.");
progress.setCancelable(false);
progress.show();
}
protected Void doInBackground(Void...arg0){
HTTP_Handler hh = new HTTP_Handler();
String jString = hh.makeHTTPCall(url);
if (jString != null) {
try {
JSONObject jObj = new JSONObject(jString);
JSONArray books = jObj.getJSONArray("bookinfo");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String name=book.getString("name");
String author=book.getString("author");
HashMap<String, String> bookdata = new HashMap<>();
bookdata.put("name", name);
bookdata.put("author", author);
booklist.add(bookdata);
}
} catch (final JSONException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check internet connection!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
protected void onPostExecute(Void Result){
super.onPostExecute(Result);
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter=new SimpleAdapter(
HomeScreen.this,
booklist,
R.layout.bucket_list,
new String[]{"name","author"},
new int[]{R.id.list_Name,R.id.list_author);
lv.setAdapter(adapter);
}
}
}
答案 0 :(得分:0)
您的浏览器是否必须针对&#39; website / filename.php&#39;进行身份验证?返回JSON?我在代码中看不到任何身份验证步骤。如果您的代码是免费提供的,这可能不是问题。乍一看,似乎现在从服务器返回JSON,这可能是一个问题。