如何使以下Java code异步任务 [英] How to make following java code Async Task

查看:235
本文介绍了如何使以下Java code异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并以下code。与异步任务。我看到很多的教程,并在code,但无法完全地做改变。这code是完全没问题,工作正确的,但有人告诉我,使它异步任务,这样,当登录成功的消息消失,被称作开始新的活动Move_to_next方法。因此,请某人添加异步任务code在它,以便其工作正确。

code -

 公共类LoActivity延伸活动{        我的意图;
        按钮登入;
        TextView的错误;
        复选框检查;
        字符串名称=,通=;
        字节[]数据;
        HttpPost httppost;
        StringBuffer的缓冲区;
        HTT presponse响应;
        HttpClient的HttpClient的;
        InputStream的InputStream的;
        共享preferences APP_ preferences;
        清单<&的NameValuePair GT; namevaluepairs中;
        的EditText editTextId,editTextP;        @覆盖
        公共无效的onCreate(捆绑savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.login);
            登入=(按钮)findViewById(R.id.signin);
            editTextId =(EditText上)findViewById(R.id.editTextId);
            editTextP =(EditText上)findViewById(R.id.editTextP);
            APP_ preferences = preferenceManager.getDefaultShared preferences(本);
            检查=(复选框)findViewById(R.id.check);
            字符串Str_user = APP_ preferences.getString(用户名,0);
            字符串Str_pass = APP_ preferences.getString(密码,0);
            字符串Str_check = APP_ preferences.getString(选中,无);
            如果(Str_check.equals(是))
            {
                editTextId.setText(Str_user);
                editTextP.setText(Str_pass);
                check.setChecked(真);
            }            signin.setOnClickListener(新View.OnClickListener()
            {
                公共无效的onClick(视图v)
                {
                    名称= editTextId.getText()的toString()。
                    通过= editTextP.getText()的toString()。
                    字符串Str_check2 = APP_ preferences.getString(选中,无);
                    如果(Str_check2.equals(是))
                    {
                        共享preferences.Editor编辑= APP_ preferences.edit();
                        editor.putString(用户名,名);
                        editor.putString(密码,通过);
                        editor.commit();
                    }
                    如果(name.equals()|| pass.equals())
                    {
                         Toast.makeText(Lo.this,空白Field..Please回车,Toast.LENGTH_SHORT).show();
                    }
                    其他
                    {                    尝试{
                        HttpClient的=新DefaultHttpClient();
                        httppost =新HttpPost(http://abc.com/register.php);
                        //添加数据
                        namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
                        nameValuePairs.add(新BasicNameValuePair(USEREMAIL,name.trim()));
                        nameValuePairs.add(新BasicNameValuePair(密码,pass.trim()));
                        httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                        //执行HTTP POST请求
                        响应= httpclient.execute(httppost);
                        的InputStream = response.getEntity()的getContent()。                        数据=新的字节[256];                        缓冲区=新的StringBuffer();
                        INT LEN = 0;
                        而(-1!=(LEN = inputStream.read(数据)))
                        {
                            buffer.append(新的String(数据,0,LEN));
                        }                        inputStream.close();
                    }                    赶上(例外五)
                    {
                        Toast.makeText(LoActivity.this,错误+ e.toString(),Toast.LENGTH_SHORT).show();
                    }
                    如果(buffer.charAt(0)=='Y')
                    {
                        Toast.makeText(LoActivity.this,登录全成,Toast.LENGTH_SHORT).show();
                    }
                    其他
                    {
                        Toast.makeText(LoActivity.this,无效的用户名或密码,Toast.LENGTH_SHORT).show();
                    }
                    }
                }
            });        check.setOnClickListener(新View.OnClickListener()
        {
            公共无效的onClick(视图v)
            {
                //在点击执行操作,取决于它是否现在检查
                共享preferences.Editor编辑= APP_ preferences.edit();
                如果(((复选框)V).isChecked())
                {
                     editor.putString(选中,是);
                     editor.commit();
                }
                其他
                {
                     editor.putString(选中,无);
                     editor.commit();
                }
        }
        });
        }
         公共无效Move_to_next()
         {
             startActivity(新意图(LoActivity.this,QnActivity.class));         }
    }


解决方案

试试这个方法。

我的编辑在code只是复制粘贴,并尝试

 公共类LoActivity延伸活动{    我的意图;
    按钮登入;
    TextView的错误;
    复选框检查;
    字符串名称=,通=;
    字节[]数据;
    HttpPost httppost;
    StringBuffer的缓冲区;
    HTT presponse响应;
    HttpClient的HttpClient的;
    InputStream的InputStream的;
    共享preferences APP_ preferences;
    清单<&的NameValuePair GT; namevaluepairs中;
    的EditText editTextId,editTextP;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.login);
        登入=(按钮)findViewById(R.id.signin);
        editTextId =(EditText上)findViewById(R.id.editTextId);
        editTextP =(EditText上)findViewById(R.id.editTextP);
        APP_ preferences = preferenceManager.getDefaultShared preferences(本);
        检查=(复选框)findViewById(R.id.check);
        字符串Str_user = APP_ preferences.getString(用户名,0);
        字符串Str_pass = APP_ preferences.getString(密码,0);
        字符串Str_check = APP_ preferences.getString(选中,无);
        如果(Str_check.equals(是)){
            editTextId.setText(Str_user);
            editTextP.setText(Str_pass);
            check.setChecked(真);
        }        signin.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图v){
                名称= editTextId.getText()的toString()。
                通过= editTextP.getText()的toString()。
                字符串Str_check2 = APP_ preferences.getString(选中,无);
                如果(Str_check2.equals(是)){
                    共享preferences.Editor编辑= APP_ preferences.edit();
                    editor.putString(用户名,名);
                    editor.putString(密码,通过);
                    editor.commit();
                }
                如果(name.equals()|| pass.equals()){
                    Toast.makeText(Lo.this,空白Field..Please回车,Toast.LENGTH_SHORT).show();
                }其他{
                    新LoginTask()执行();
                }
            }
        });        check.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图v){
                //在点击执行操作,取决于它是否现在
                //检查
                共享preferences.Editor编辑= APP_ preferences.edit();
                如果(((复选框)ⅴ).isChecked()){
                    editor.putString(选中,是);
                    editor.commit();
                }其他{
                    editor.putString(选中,无);
                    editor.commit();
                }
            }
        });
    }    公共无效Move_to_next(){
        startActivity(新意图(LoActivity.this,QnActivity.class));    }    私有类LoginTask扩展的AsyncTask<太虚,太虚,字符串> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();            //显示进度对话框这里
        }
        @覆盖
        保护字符串doInBackground(虚空......为arg0){
            尝试{
                HttpClient的=新DefaultHttpClient();
                httppost =新HttpPost(http://abc.com/register.php);
                //添加数据
                namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
                nameValuePairs.add(新BasicNameValuePair(USEREMAIL,name.trim()));
                nameValuePairs.add(新BasicNameValuePair(密码,pass.trim()));
                httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                //执行HTTP POST请求
                响应= httpclient.execute(httppost);
                的InputStream = response.getEntity()的getContent()。                数据=新的字节[256];                缓冲区=新的StringBuffer();
                INT LEN = 0;
                而(-1!=(LEN = inputStream.read(数据))){
                    buffer.append(新的String(数据,0,LEN));
                }                inputStream.close();
                返回buffer.toString();
            }赶上(例外五){
                e.printStackTrace();            }
            返回;
        }        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(结果);
            //隐藏进度对话框这里            如果(buffer.charAt(0)=='Y'){
                Toast.makeText(LoActivity.this,登录全成,Toast.LENGTH_SHORT).show();
                Move_to_next();
            }其他{
                Toast.makeText(LoActivity.this,无效的用户名或密码,Toast.LENGTH_SHORT).show();
            }
        }
    }
}

How to merge following code with Async Task. I see lots of tutorials and make changes in code but unable to do completly. This code is completely fine and working proper but some one advise me to make it Async Task so that when login successful message disappear Move_to_next method is called to start new activity. so please someone add async task code in it so that its work proper.

Code-

public class LoActivity extends Activity {

        Intent i;
        Button signin;
        TextView error;
        CheckBox check;
        String name="",pass="";
        byte[] data;
        HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        InputStream inputStream;
        SharedPreferences app_preferences ;
        List<NameValuePair> nameValuePairs;
        EditText editTextId, editTextP;

        @Override
        public void onCreate (Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            signin = (Button) findViewById (R.id.signin);
            editTextId = (EditText) findViewById (R.id.editTextId);
            editTextP = (EditText) findViewById (R.id.editTextP);
            app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
            check = (CheckBox) findViewById(R.id.check);
            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);
                check.setChecked(true);
            }

            signin.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    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(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {

                    try {
                        httpclient = new DefaultHttpClient();
                        httppost = new HttpPost("http://abc.com/register.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();
                    }

                    catch (Exception e)
                    {
                        Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
                    }
                    if(buffer.charAt(0)=='Y')
                    {
                        Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
                    }
                    }
                }
            });

        check.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                // Perform action on clicks, depending on whether it's now checked
                SharedPreferences.Editor editor = app_preferences.edit();
                if (((CheckBox) v).isChecked())
                {
                     editor.putString("checked", "yes");
                     editor.commit();
                }
                else
                {
                     editor.putString("checked", "no");
                     editor.commit();
                }
        }
        });
        }
         public void Move_to_next()
         {
             startActivity(new Intent(LoActivity.this, QnActivity.class));

         }
    }

解决方案

Try this way

I have edit in your code just copy paste and try

public class LoActivity extends Activity {

    Intent i;
    Button signin;
    TextView error;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signin = (Button) findViewById(R.id.signin);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        check = (CheckBox) findViewById(R.id.check);
        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);
            check.setChecked(true);
        }

        signin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                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(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                } else {
                    new LoginTask().execute();
                }
            }
        });

        check.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks, depending on whether it's now
                // checked
                SharedPreferences.Editor editor = app_preferences.edit();
                if (((CheckBox) v).isChecked()) {
                    editor.putString("checked", "yes");
                    editor.commit();
                } else {
                    editor.putString("checked", "no");
                    editor.commit();
                }
            }
        });
    }

    public void Move_to_next() {
        startActivity(new Intent(LoActivity.this, QnActivity.class));

    }

    private class LoginTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // Show progress dialog here
        }
        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://abc.com/register.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 "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                Move_to_next();
            } else {
                Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

这篇关于如何使以下Java code异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆