I am learning android development in Android Studio. I used Android-query library for easy HTTP call to get JSON data from my Grails web application. In my android UI, i have a button and a editText. I hope show JSON string returned from server after i click the button. here's the code:
public static class PlaceholderFragment extends Fragment {
private AQuery aq;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
aq = new AQuery(getActivity(), rootView);
aq.id(R.id.button1).clicked(this, "onButtonClick");
return rootView;
}
public void onButtonClick(View view) {
String url = "http://localhost:8090/MyProject/main/index";
aq.ajax(url, JSONObject.class, this, "jsonCallback");
}
public void jsonCallback(String url, JSONObject json, AjaxStatus status){
if(json != null){
aq.id(R.id.editText).text(json.toString());
}else{
aq.id(R.id.editText).text(status.getMessage());
}
}
}
At the Grails side, I just send back a json object directly:
class MainController {
def re = ['name' : 'abc']
def index() {
render re as JSON
}
}
I can visit my Grails web url in browser and get correct JSON data:
{
name: "abc"
}
if i run the android app in virtual device, i just got "network error" message. the JSON object returned is null.
if i use the same android code to visit http://ip.jsontest.com in place of my Grails web url. i can get correct json data returned without network error. why?
Can anyone give me some suggestions to let Android-query work well with Grails web?
Finally, I found the reason:
To visit local host web application on the PC from Android Emulator, we can't use localhost as server address. I changed URL to "http://10.0.3.2:8090/MyProject/main/index" (i use Genymotion Android Emulator), it works.