Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

if you are using the Genymotion Android Emulator then the URL should be like "//192.168.56.1:8090/MyProject/main/index" which is your local ip address or if you are using the default emulator then should be like "//10.0.0.2:8090/MyProject/main/index"

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top