我已经为另一个项目完成了这个任务并且它给了JSON值但是当我使用extends Fragment
时这个代码显示空值。
以下是Fragment
扩展类代码:
注意:我使用与之前项目相同的ServiceHandler
课程
public class NewsActivity extends Fragment {
private NewsActivity activity;
// url to get JSON
private static String url = "http://vikashparajuli.orgfree.com/zz/get_all_products.php";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
activity = this;
//TODO: if Internet is connected
if(AutoLifeUtils.isConnectedToInternet(getActivity())){
new Get_postlist().execute();
}else{
}
return rootView;
}
public class Get_postlist extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to API url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
这是ServiceHandler
类
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
/**
* Making service call
* @url - url to make request
* @method - http request method
* */
public String makeServiceCall(String url, int method){
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
private String makeServiceCall(String url, int method, List<NameValuePair> params) {
// TODO Auto-generated method stub
try{
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params)); // UrlEncodedFormEntity() is useful to send HTTP POST request
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(ClientProtocolException ex){
ex.printStackTrace();
}catch(IOException exc){
exc.printStackTrace();
}
return null;
}
}
答案 0 :(得分:0)
在makeServiceCall结束时,你有返回null;
将其更改为返回响应; ,如下所示。
private String makeServiceCall(String url, int method, List<NameValuePair> params) {
....
//return null;
return response; //this should fix your problem.
}