SaleemKhair SaleemKhair - 2 months ago 16
Android Question

Getting JSON file from localhost using ServiceHandler and AsyncTask

I have added a

questions.json
file to www folder and I'm trying to retrieve it.
problem is the response always returns null I'm guessing the exception is at
httpClient.execute(httpGet);
, not sure though

@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







}


ServiceHandler

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
* 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
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
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));
}

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 e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return response;

}


}

questions.json

{
"Questions": [
{
"CreatedAt": "2013-07-31T09: 57: 34.618Z",
"Asker_Name": "Cloyd",
"QuestionTitle": "temporadoloremquevoluptatemestquisquamundevoluptatemsuntearum\nsitfugaducimusnequeomnisin\npariaturminusdebitisquaeratrerumnamvelitveritatisrem",
"QuestionBody": "voluptatemtemporadignissimosanimivelitdelectusconsequaturcumquedeserunt\nillumaperiamquisminimaeumremveniam\nutnumquamdoloremconsequaturvoluptatemofficiaveniam\nutarchitectoiddelenitiuteiuscumpossimus\ndolorumprovidentmollitianullarerum\n\r\tquiainarchitectodebitislaboreerror\nvoluptatibussitquaeratdoloreassumendadoloremdoloresconsectetur\nsedetevenietsaepeconsequaturvelarchitecto\n\r\tdolorumvoluptatemquaevoluptatebeatae\ndoloremqueutofficiisquibusdamiustopariaturiureautdolorem\nidquialiquideosvelet",
"Question_Id": 0,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1997-08-05T20: 13: 37.888Z",
"Asker_Name": "Alexander",
"QuestionTitle": "fugaetnequequoettemporibus\natvoluptatumessesit\nnullaadipisciquaeducimus",
"QuestionBody": "quiainciduntetquoserror\ncumqueetautsitidexcepturiaccusantiumpariaturconsequatur\nlaudantiummaioressedillomagniexplicabo\nindolorprovidentvoluptasearumdelenitidelectusmollitia\n\r\tsapienteinnemo\nexpeditaautinnon\nprovidentabveniamut\n\r\tenimducimussuntrerumnamsed\nsaepepraesentiumaliquamverolaborumdeseruntidex\nautsedvelittemporibusexplicaboveniamvoluptatemin\nisteetutnobisprovidentasperiores\nexpeditaitaqueullam",
"Question_Id": 1,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1990-02-16T06: 37: 46.327Z",
"Asker_Name": "Kade",
"QuestionTitle": "nisidelectusasperioresveletidtempore\nrationeautautet\neaquenisiestrerumodioasperiorescupiditate",
"QuestionBody": "exrepellendusliberoeosautemetdictaautemsed\nabconsequaturetsitvoluptatemassumendavelitsint\nautconsequaturveniamodioquodoloremdolorem\neligendirerumexplicaboquiquiadolorem\n\r\tminusvoluptatemnamvelcupiditateaperiamsedrerumearum\nautrepudiandaeeavelsitreprehenderiteterrorfugiat\nsedeaquidemveritatisiure\n\r\tdoloremqueidsuntatquiacorruptimolestiaeexpeditavoluptate\nnontemporevelitestrepellendus\nessequaeinsit\nporronihilfacereautnecessitatibusquosunt\natlaborumatemporaullam",
"Question_Id": 2,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1987-02-28T20: 39: 36.422Z",
"Asker_Name": "Madaline",
"QuestionTitle": "omnisnesciuntexcepturieligendirerumquam\netmolestiasfugiatremvoluptasvelitautet\nsedoccaecatidelectuseoset",
"QuestionBody": "inciduntquosbeataevoluptasidcommodideseruntexvero\netitaquemollitialaborumnemosedvoluptatibusperferendisdoloremque\nestsuscipitnonveniamutquaeaperiam\nveroetquiaautillo\nasperioressimiliquetempora\n\r\tvoluptatemaccusantiumconsequunturetconsequaturrepellataut\naspernaturnesciunteavoluptasnatusmaxime\nmaioresatconsequaturnequereiciendis\nadipiscienimrationeipsummagnamveniamsed\n\r\treiciendisutundequi\naperiamcorporisnesciuntid\nculpaetreprehenderittemporibusofficiaplaceataccusantiumcum\nquassitmaioresdelectusesse\nconsequaturtotamdolor",
"Question_Id": 3,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1991-11-22T12: 50: 21.965Z",
"Asker_Name": "Lizzie",
"QuestionTitle": "quiaremnatus\nnatusofficiisquamomnisquifuga\nquiasitavoluptatem",
"QuestionBody": "quisvoluptasquilaborumsednostrumfugaea\nipsumquaeratveritatis\nporrouterrorex\nauteiusexplicabononfugaadutvoluptatumnihil\nabnoninarchitectocommodiminusquasanimi\n\r\tenimdebitisbeataemollitiadoloresiureiustoquia\ncommodiquiapossimusatemporibus\nidutnobisvoluptatumfugaaccusamusharum\netdictaquiamollitiaaccusamuspossimusvoluptatibusautalias\nautemdoloremnamaliquam\n\r\tsitdeseruntautestexcepturiquasi\nquibusdamevenietexcepturiducimusquosdicta\nearumsitenimautquisquamaliquam\nmagnamnesciuntinciduntvelitarchitectoomnis\nomnisminimaerrorfuga",
"Question_Id": 4,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1987-05-09T15: 46: 08.048Z",
"Asker_Name": "Colleen",
"QuestionTitle": "rerumetaccusamussedabdolorenonest\nestperspiciatisquisedsintmolestiaeautcorporisomnis\nperferendisvelenim",
"QuestionBody": "iustomolestiasrerummollitiafacilisatquecumque\neumquaeatqueaspernaturadoloresestomnis\ndolornihilexcepturinecessitatibus\n\r\tidveniamevenietquifugiat\nreprehenderiterrornumquamautetquiquiarerum\ndolorummaximequasicorporismodiin\neosnostrumutsapientedoloremque\nquaeratconsequunturveniamperferendisautnisidoloresnonest\n\r\tquisuscipitadconsequaturrepellatvoluptatemmollitia\nquidemverocum\nmodidelenitivoluptasadipisciodio",
"Question_Id": 5,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "2002-05-04T05: 31: 45.704Z",
"Asker_Name": "Carlotta",
"QuestionTitle": "impeditquodillumconsequunturlabore\nsitundeblanditiisitaqueiustoutcorporisut\ndeseruntquasquam",
"QuestionBody": "illumevenietdolor\ndoloribusdistinctiorerumvoluptatumquibusdamest\ndoloremquevoluptassitautemeos\nexcepturiquieasuntverodictaatque\n\r\tisteullamut\nanimivoluptasautdoloresoccaecatiuttenetur\neaimpeditautaquispossimusperspiciatisestaccusantium\nutconsequaturminimabeataemolestiae\ndoloresdolorethic\n\r\tquisquamquidempariaturassumendalaborumveritatisquasdolore\ncommodiquaedebitisipsafugitcorporissitharumquam\nvoluptasbeataeeaetetutaperiam\naiurenihilnamnonaut\ndoloresprovidenthicetveroautmagnimaximelabore",
"Question_Id": 6,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
}
]
}

Answer

You are trying to connect to the server by specifying localhost as the address of the system hosting the service. The Android emulator runs inside a Virtual Machine (QEMU). Hence, localhost would be the emulator's own loop back address, and not that of the system.

So, you can either go to CommandPrompt in your Windows to get the IP address of your system or just use http://10.0.2.2:8080/... instead of using localhost.

private static String url = "http://10.0.2.2:8080/questions.json";

Comments