1

Im trying to write a login service in the android by sending JSON to the web service i have in PHP after its processed in the web service JSON is returned back. My problem is sending JSON and then reading JSON in the android app. I have figured out basic posting in the app using ASyncTask but im not sure where to go from there, iv been doing a lot of searching on this and im kind of stumped right now. Any help is very appreciated!

Heres my .java file

package com.example.logintest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

private static final String APP_TAG = "demo";
public static EditText txtUserName;
public static EditText txtPassword;
Button btnLogin;
Button btnCancel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtUserName=(EditText)this.findViewById(R.id.txtUname);
        txtPassword=(EditText)this.findViewById(R.id.txtPwd);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new OnClickListener() {


    public void onClick(View v) {
        // TODO Auto-generated method stub
        new loginTask().execute();
        /*if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
            Toast.makeText(MainActivity.this, "Login Successful",Toast.LENGTH_LONG).show();
        } else{
        Toast.makeText(MainActivity.this, "Invalid Login",Toast.LENGTH_LONG).show();
        }*/

    }
   });   
   }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    public static String postHttpResponse(URI absolute) {
        Log.d(APP_TAG, "Going to make a post request");
        StringBuilder response = new StringBuilder();
        String username = txtUserName.getText().toString();
        String password = txtPassword.getText().toString();
        try {
            HttpPost post = new HttpPost();
            post.setURI(absolute);
            List params = new ArrayList();
            params.add(new BasicNameValuePair("tag", "login"));
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            post.setEntity(new UrlEncodedFormEntity(params));
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                Log.d(APP_TAG, "HTTP POST succeeded");
                HttpEntity messageEntity = httpResponse.getEntity();
                InputStream is = messageEntity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
            } else {
                Log.e(APP_TAG, "HTTP POST status code is not 200");
            }
        } catch (Exception e) {
            Log.e(APP_TAG, e.getMessage());
        }
        Log.d(APP_TAG, "Done with HTTP posting");
        return response.toString();
    }

    class loginTask extends AsyncTask<Object, Object, String> { 

        //check if server is online
        protected String doInBackground(Object... arg0) {
            URI absolute = null;
            try {
                absolute = new URI("http://10.0.2.2/service/");
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return postHttpResponse(absolute);
        }

        //set status bar to offline if flag is false
        protected void onPostExecute(String xml) {
            //XMLfromString(xml);
        }

    }

}
9
  • Do you have the actual response in Json Format available to you? Commented Jan 24, 2013 at 0:49
  • The JSON sent to the server will be processed through the database and depending on the information sent it will send back if it was a success or not and if not what error it was. Or do you mean you want the response that would be sent from the server? Commented Jan 24, 2013 at 0:54
  • For a great Java JSON library check out GSON. It's small, fast, and convenient to use: code.google.com/p/google-gson Commented Jan 24, 2013 at 0:58
  • @Adonai : your code looking f9 then where u are getting problem? and how u are receiving json on server from android device ? Commented Jan 24, 2013 at 1:16
  • @ρяσѕρєя K im not sending any JSON yet my problem is i cant quite figure out how to do so Commented Jan 24, 2013 at 1:20

2 Answers 2

3

you can send username and password as jsonobject as to server :

//your code here....
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);

HttpPost post = new HttpPost();
post.setURI(absolute);
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", "login"));
params.add(new BasicNameValuePair("loginjson",json.toString()));
post.setEntity(new UrlEncodedFormEntity(params));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(post);
//your code here....

on server side retrieve json object from loginjson queryString .

and for getting result back from server in json you will need to convert returned string from server to JsonObject ir JsonArray inside onPostExecute method of AsyncTask as :

protected void onPostExecute(String jsonstring) {
     // if server returning jsonobject 
       JSONObject jsonobj=new JSONObject(jsonstring);
          // get values from jsonobject

      // if server returning jsonArray
       JSONArray jsonarray=new JSONArray(jsonstring);
          // get values from JSONArray

}
Sign up to request clarification or add additional context in comments.

3 Comments

Im looking at this trying to to get it to do something with my web service just so you know im working with this and not ignoring it
Alright iv got it to respond in JSON format successfully thanks for the help. I used my original send code but used you onPostExecute code
@Adonai : can u mark it as answer if this answer help u i solving current issue . Thanks
0

well in our application we send json to our service using php. i do not send it in json format directly instead i send it in string array format and let the php encode the json as for receiving back the data when i get the response from the server i just put it in string and then using JSONObject in java i convert it to json and parse the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.