我是Android中的新手,我正在获得服务响应null,但服务URL在浏览器中运行正常。当我运行的应用程序屏幕显示空白,没有数据来自我正在做的服务。错误地帮助我。
我的片段:
public class SpecificCountryScholorshipsFragment extends Fragment {
OKHttpRequest okHttpRequest = new OKHttpRequest();
ArrayList<ScholorshipsModel> arrayList;
ListView list
/***********************************************************************************/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
String getResponse = okHttpRequest.doGetRequest("http://192.168.100.7/scholar/web/app.php/scholarship");
if (getResponse != null) {
//Toast.makeText(getActivity(), getResponse, Toast.LENGTH_LONG).show();
JSONArray jArray = new JSONArray(getResponse);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jRealObject = jArray.getJSONObject(i);
ScholorshipsModel model = new ScholorshipsModel();
model.setScholorship_name(jRealObject.getString("name"));
model.setScholorship_detail(jRealObject.getString("details"));
model.setScholorship_pic(jRealObject.getString("picture"));
arrayList.add(model);
setAdapterValue();
}
}
View view = inflater.inflate(R.layout.scholorship_listing_main, container, false);
list = (ListView) view.findViewById(R.id.Scholorshiplist);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "List is clicked ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), ScholorshipDetailActivity.class);
getActivity().startActivity(intent);
}
});
return view;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/***********************************************************************************/
private void setAdapterValue() {
ScholorshipAdapter adapter = new ScholorshipAdapter(getActivity(), R.layout.scholorship_listing, arrayList);
list.setAdapter(adapter);
}
}
okhttp类:
public class OKHttpRequest {
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public String doGetRequest(String url) throws IOException {
try {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
String doPostRequest(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}}
首先要检查您的API,我认为您缺少Hader中的某个参数,或者由于IT的响应不是从服务器中出现的。另外,我建议用户为客户端 - 服务器通信
也可以使用REST-CLIENT(添加Chrome ANS Firefox),如果使用httpsurlconnection进行所有工作,则可以帮助您更好。