Android 使用ServiceHandler和AsyncTask从localhost获取JSON文件
我已经在www文件夹中添加了一个Android 使用ServiceHandler和AsyncTask从localhost获取JSON文件,android,json,android-asynctask,Android,Json,Android Asynctask,我已经在www文件夹中添加了一个questions.json文件,我正在尝试检索它。 问题是响应总是返回null我猜异常出现在httpClient.execute(httpGet),但不确定 @SuppressLint("NewApi") public class QuestionListFragment extends android.app.ListFragment { private ProgressDialog pDialog; // url to make reque
questions.json
文件,我正在尝试检索它。
问题是响应总是返回null我猜异常出现在httpClient.execute(httpGet)代码>,但不确定
@SuppressLint("NewApi")
public class QuestionListFragment extends android.app.ListFragment
{
private ProgressDialog pDialog;
// url to make request
private static String url = "http://localhost/questions.json";
// JSON Node names
private static final String TAG_QUESTIONS = "Questions";
private static final String TAG_ID = "Question_Id";
private static final String TAG_BODY = "QuestionBody";
private static final String TAG_TITLE = "QuestionTitle";
private static final String TAG_NAME = "Asker_Name";
private static final String TAG_TIME = "Created At";
private static final String TAG_ANSWERS = "Answers";
private static final String TAG_ANSWER = "answer";
private static final String TAG_A_NAME = "Name";
private static final String TAG_RATING = "Rating";
// questions JSONArray
JSONArray questions = null;
ListView lv;
Context c;
JSONObject obj ;
ArrayList<HashMap<String, String>> questionsList = new ArrayList<HashMap<String, String>>();
@Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState )
{
View view = inflater.inflate(ask.code.R.layout.questions_list_frag, container, false);
new GetQuestions().execute();
return view;
}
private class GetQuestions extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_QUESTIONS);
// looping through All Questions
for(int i = 0; i < questions.length(); i++){
JSONObject c = questions.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String body = c.getString(TAG_BODY);
String name = c.getString(TAG_NAME);
String time = c.getString(TAG_TIME);
JSONObject answers = c.getJSONObject(TAG_ANSWERS);
String answer = answers.getString(TAG_ANSWER);
String a_name = answers.getString(TAG_A_NAME);
String a_rating = answers.getString(TAG_RATING);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, title);
map.put(TAG_BODY, body);
// adding HashList to ArrayList
questionsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(),
questionsList,
ask.code.R.layout.question_item,
new String[] {
TAG_NAME,
TAG_TITLE,
TAG_TIME},
new int[] {
ask.code.R.id.asker_name,
ask.code.R.id.question_title,
ask.code.R.id.question_rating});
setListAdapter(adapter);
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
// TODO Auto-generated method stub
}
如果您使用的是emulator,那么您必须编写10.0.2.2来代替localhost。
如果您正在使用您的设备,那么您必须连接到同一网络,并且必须用您的计算机ip地址替换localhost
我希望这将有助于您尝试通过指定localhost
作为承载服务的系统的地址来连接到服务器。Android仿真器在虚拟机(QEMU)中运行。因此,localhost
将是仿真器自己的环回地址,而不是系统的环回地址。
因此,您可以在Windows中转到CommandPrompt获取系统的IP地址,也可以使用http://10.0.2.2:8080/...
而不是使用localhost
私有静态字符串url=”http://10.0.2.2:8080/questions.json";代码>
公共字符串makeServiceCall(字符串url,int方法,
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
StringBuilder result = new StringBuilder();
try {
//URL urlObj = new URL(url);
URL urlObj = new URL(url.replace(" ","%20"));
urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
列表参数){
StringBuilder结果=新建StringBuilder();
试一试{
//URL urlObj=新URL(URL);
URL urlObj=新URL(URL.replace(“,“%20”);
urlConnection=(HttpURLConnection)urlObj.openConnection();
InputStream in=new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
弦线;
而((line=reader.readLine())!=null){
结果。追加(行);
}
}捕获(例外e){
e、 printStackTrace();
}
最后{
urlConnection.disconnect();
}
返回result.toString();
}
这可能会有帮助:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
HttpURLConnection urlConnection;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
StringBuilder result = new StringBuilder();
try {
//URL urlObj = new URL(url);
URL urlObj = new URL(url.replace(" ","%20"));
urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
}
公共类ServiceHandler{
静态字符串响应=null;
公共最终静态int GET=1;
公共最终静态int POST=2;
HttpURLConnection-urlConnection;
公共服务处理程序(){
}
公共字符串makeServiceCall(字符串url,int方法){
返回此.makeServiceCall(url,方法,null);
}
公共字符串makeServiceCall(字符串url,int方法,
列表参数){
StringBuilder结果=新建StringBuilder();
试一试{
//URL urlObj=新URL(URL);
URL urlObj=新URL(URL.replace(“,“%20”);
urlConnection=(HttpURLConnection)urlObj.openConnection();
InputStream in=new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
弦线;
而((line=reader.readLine())!=null){
结果。追加(行);
}
}捕获(例外e){
e、 printStackTrace();
}
最后{
urlConnection.disconnect();
}
返回result.toString();
}
}
下面这看起来像是soumit未解释代码转储的副本。请张贴事实上是问题答案的原始答案。
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
StringBuilder result = new StringBuilder();
try {
//URL urlObj = new URL(url);
URL urlObj = new URL(url.replace(" ","%20"));
urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
HttpURLConnection urlConnection;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
StringBuilder result = new StringBuilder();
try {
//URL urlObj = new URL(url);
URL urlObj = new URL(url.replace(" ","%20"));
urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
}