在android中使用httpget和asynctask登录页面

时间:2014-03-20 04:15:29

标签: android android-asynctask

您好我是android的新手,并且有权创建一个与服务器连接的登录页面,并使用 http获取AsyncTask以及 PHP检查用户是否存在API 已准备就绪。我在AsyncTask上经历了一些教程,我理解但我不确定如何使用 http Get AsyncTask。任何人都可以帮助如何链接和创建登录页面。

P.S:我有两个EditText接受用户名和密码,两个Buttons一个用于登录,另一个用于注册,并且还有相应的数据库。

1 个答案:

答案 0 :(得分:0)

这是示例代码 -

public class LoginActivity extends Activity 
{
    Intent i;
    Button signin, signup;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences, pref;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;
    SharedPreferences.Editor editor;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signin = (Button) findViewById(R.id.signin);
        signup = (Button) findViewById(R.id.signup);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String Str_user = app_preferences.getString("username", "0");
        String Str_pass = app_preferences.getString("password", "0");
        String Str_check = app_preferences.getString("checked", "no");
        if (Str_check.equals("yes")) 
        {
            editTextId.setText(Str_user);
            editTextP.setText(Str_pass);
        }

        signin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                signin.setEnabled(false);
                signup.setEnabled(false);
                name = editTextId.getText().toString();
                pass = editTextP.getText().toString();
                String Str_check2 = app_preferences.getString("checked", "no");
                if (Str_check2.equals("yes")) {
                    SharedPreferences.Editor editor = app_preferences.edit();
                    editor.putString("username", name);
                    editor.putString("password", pass);
                    editor.commit();
                }
                if (name.equals("") || pass.equals("")) 
                {
                    Toast.makeText(LoginActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                    signin.setEnabled(true);
                    signup.setEnabled(true);
                }
                else 
                {
                    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
                    if(name.matches(emailPattern))
                    new LoginTask().execute();
                    signin.setEnabled(false);
                    signup.setEnabled(false);
                }
             }
        });

        signup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v)
            {
                Move_next();
            }
        });
    }

    public void Move_to_next() 
    {
        final Handler handle = new Handler();
        Runnable delay = new Runnable() {
            public void run() {
                startActivity(new Intent(LoginActivity.this, SplashActivity.class));
                finish();
            }
        };
        handle.postDelayed(delay,2000); 
    }

    public void Move_next() 
    {
        startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
        finish();
    }

    @SuppressLint("NewApi")
    private class LoginTask extends AsyncTask <Void, Void, String> 
    {
        @SuppressLint("NewApi")
        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();
            // Show progress dialog here
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://website.com/yourpagename.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }
                inputStream.close();
                return buffer.toString();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();

            }
            return "";
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here
            if (buffer.charAt(0) == 'Y') 
            {
                Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                Move_to_next();
            } 
            else 
            {
                Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
                signin.setEnabled(true);
                signup.setEnabled(true);
            }
        }
    }
}