Question

I'm new in android development. So plz help to add http in this code to get response when i click on submit button. I've done all validations of username and password. But i don't know how can I use JSON RESTFUL in this code. So plz help me to solve this problem.

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.Button;
    import android.widget.EditText;

 public class MainActivity extends Activity {


 private static final String SERVICE_URI = "http://www.safepestadmin.com.au/windex.php?itfpage=login";
    public  EditText edittext_username, edittext_password;
Button button_submit;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  



    edittext_password = (EditText) findViewById(R.id.login_edittext_password);
    edittext_username = (EditText) findViewById(R.id.login_edittext_username);
    button_submit = (Button) findViewById(R.id.login_button_submit);




    button_submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

               String email = edittext_username.getText().toString().trim();
               String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
               String pwd = edittext_password.getText().toString();



               if (email.matches("")   && pwd.matches(""))
               {
                   Toast.makeText(getApplicationContext(), "Please enter a username and a password", Toast.LENGTH_SHORT).show();
               }
               else if (email.matches(emailPattern)    && pwd.matches(""))
                   {
                   Toast.makeText(getApplicationContext(),"Please enter a password",Toast.LENGTH_SHORT).show();
                   }

                  else if (email.matches("") && pwd.length()>0) 
                  {
                  Toast.makeText(getApplicationContext(),"Please enter a username", Toast.LENGTH_SHORT).show();
                  }         

                  else if (!email.matches(emailPattern) && pwd.length()>0) {
                      Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
                  }
                  else if (!email.matches(emailPattern)  && pwd.matches("")) {
                      Toast.makeText(getApplicationContext(), "Please enter a password", Toast.LENGTH_SHORT).show();
                  }
                  else if (email.matches("alam@gmail.com") && pwd.matches("12345")) {
                      Toast.makeText(getApplicationContext(), "Successfully Logged In", Toast.LENGTH_LONG).show();
                  }
                  else {
                      Toast.makeText(getApplicationContext(), "Please enter registered email and password", Toast.LENGTH_LONG).show();
                  }

        }       
    });

}

   }
Was it helpful?

Solution

You can try this:

  • Send your password and username to server
  • In your server keep password as encrypted in your database
  • When username and password comes to webservice you can get users password and decypte it and compare with the password which comes from client
  • I the passwords are matched you can send client just true if wrong you can send false
  • In client if it comes true from webservice you can give permission to enter person

client code:

you can create a class like this:

public class web_api_get  extends AsyncTask<Object, Object, String> {

     @Override
    public String doInBackground(Object... params) {
        StringBuilder builder = new StringBuilder();

        HttpParams params2 = new BasicHttpParams();
        HttpProtocolParams.setVersion(params2, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params2, "UTF-8");
        params2.setBooleanParameter("http.protocol.expect-continue", false);


        HttpClient client = new DefaultHttpClient(params2); 
        HttpGet httpGet = new HttpGet(params[0]+""); 
        try {       
          HttpResponse response = client.execute(httpGet);
          StatusLine statusLine = response.getStatusLine(); 
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {  
             HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
          } else {
           // Log.e(ParseJSON.class.toString(), "Failed to download file");
          } 

            } catch (Exception e) { 
            }

        return builder.toString(); 
    } 

}

And then you can call it like this :

String result= new web_api_get().execute("your link here include your password and username").get() ;

and then the result is getting you true or false from webservice

OTHER TIPS

try to execute the piece of code in AsyncTask Class.

@Override
protected Integer doInBackground(Context... params) {
// TODO Auto-generated method stub
try {

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(("http://URL/Login_Auth? Username="+username+"").replace(" ","%20"));
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity =response.getEntity();
    String responseData = EntityUtils.toString(entity);

            Log.d("====Response====",""+responseData.toString());
    }
    }

In Log.d() you get the Response from URL.

use aysctask and send username and password to server. use this code and call this asyctask after clicking on login button

 private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
        }

        @Override
        protected Void doInBackground(Void... params) {

            //Create new default HTTPClient
            httpclient = new DefaultHttpClient();

            //Create new HTTP POST with URL to php file as parameter
            httppost = new HttpPost("http://10.0.2.2/myteamapp/index.php"); 

            //Assign input text to strings
            username = etUser.getText().toString();
            password = etPass.getText().toString();



            //Next block of code needs to be surrounded by try/catch block for it to work
            try {
                //Create new Array List
                nameValuePairs = new ArrayList<NameValuePair>(2);

                //place them in an array list
                nameValuePairs.add(new BasicNameValuePair("user", "username"));
                nameValuePairs.add(new BasicNameValuePair("pass", "password"));

                //Add array list to http post
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                //assign executed form container to response
                response = httpclient.execute(httppost); //response from the PHP file

                //check status code, need to check status code 200
                if(response.getStatusLine().getStatusCode() == 200){

                    //assign response entity to http entity
                    entity = response.getEntity();

                    //check if entity is not null
                    if(entity != null){


                        //Create new input stream with received data assigned
                        InputStream instream = entity.getContent();

                        //Create new JSON Object. assign converted data as parameter.
                        JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                        //assign json responses to local strings
                        String retUser = jsonResponse.getString("user");//mySQL table field
                        String retPass = jsonResponse.getString("pass");

                        //Validate login
                        if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password 

                            //Display a Toast saying login was a success
                            Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();


                        } else {
                            //Display a Toast saying it failed.

                            Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                        }

                    }


                }


            } catch(Exception e){

               // e.printStackTrace();
                //Display toast when there is a connection error
                //Change message to something more friendly
               Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
               Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();

               return null;
            }



            return null;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top