0

Ok, i am new to all this android developement. I am trying to make an app that can log in to a webpage, and i was being told that i need to use JSON. I tried to read about this, and tried to find some examples. But everything is so little cleared. Can someone provide me with step by step explanation, what do i need to do. Thank you very much in advance.

Goran
  • 1,239
  • 4
  • 23
  • 36

1 Answers1

1

Ok here goes,

First because you said you need to login to a website, you will definitely have to send the website some login credentials. Ideally you will want that also to be a JSON object.

private static String SendAndReceive(final JsonObject Json) {
    HttpClient HClient = new DefaultHttpClient();
    HttpPost HPost = new HttpPost(Constants.POST_URL);
    HttpResponse HResponse = null;
    String SResponse = null;

    try {
        List<NameValuePair> NVP = new ArrayList<NameValuePair>();
        NVP.add(new BasicNameValuePair("jsondata", Json.toString()));
        HPost.setEntity(new UrlEncodedFormEntity(NVP));
        HResponse = HClient.execute(HPost);
        if (HResponse != null) {
            InputStream in = HResponse.getEntity().getContent();
            SResponse = convertStreamToString(in);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return SResponse;
}

private static String convertStreamToString(InputStream InStream) {
    BufferedReader BReader = new BufferedReader(new InputStreamReader(
            InStream));
    StringBuilder SBuilder = new StringBuilder();
    String TmpLine = null;

    try {
        while ((TmpLine = BReader.readLine()) != null) {
            SBuilder.append(TmpLine + "\n");
        }
    } catch (Exception E) {
        E.printStackTrace();
    } finally {
        try {
            InStream.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
    }
    return SBuilder.toString();
}

So now that you know how to post data to a URL and retrieve its contents, you will just have to parse your resulting JSON data. I recommend using GSON API. Hope this helps you!!

Anand Sainath
  • 1,807
  • 3
  • 22
  • 48
  • Where do I need to put this part you wrote. in my Main Activity java file. Or i must create something new ?? I what i must do with this GSON. sorry but i am noob, i hope you can help :) – Goran Aug 10 '11 at 19:14
  • You can put these functions up in the same activity class. If you are going to build up a proper app, I suggest you keep such utility functions in a separate class. As far as GSON goes, [here](http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html) is a tutorial for it! – Anand Sainath Aug 11 '11 at 03:21
  • Or if that's too big, even [this](http://stackoverflow.com/questions/2864370/how-do-i-use-googles-gson-api-to-deserialize-json-properly) post might help ya! – Anand Sainath Aug 11 '11 at 03:23