将值从一个活动返回到另一个活动

时间:2014-05-30 15:06:29

标签: java android

如果用户输入错误的密码或用户名,我想显示一条消息。

这是取值

的类
    public class Login extends Activity {

    Button submit_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        submit_login = (Button) findViewById(R.id.submit_login);
        submit_login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub.
                EditText usr_number = (EditText) findViewById(R.id.username);
                EditText password_main = (EditText) findViewById(R.id.password);
                String username = usr_number.getText().toString();
                String password = password_main.getText().toString();
                String[] Loginvalues = {username,password};

                new CheckUsername().execute(Loginvalues);

            }
        });
    }

}

现在在新的CheckUsername()之后执行(Loginvalues);这个电话我想在textview(id = loginStatus)

中显示一条消息
public class CheckUsername extends AsyncTask<String, Integer, String[]> {

    HttpClient Client;
    JSONObject json;
    final static String URL = "someurl";

    @Override
    protected String[] doInBackground(String... params) {
        // TODO Auto-generated method stub
        String username = params[0].toString();
        String password = params[1].toString();
        Client = new DefaultHttpClient();
        try {
            json = ValidateUsername(username, password);

            String status = json.getString("status");
            if (status.equals("ok")) {

                System.out.println(json.getString("response"));

                JSONObject user_values = new JSONObject(json.getString("user"));

                GlobalVariables newObj = new GlobalVariables();

                newObj.setUserId(user_values.getString("id"));

                newObj.setUserName(user_values.getString("name"));

                System.out.println(newObj.getUserId());

                System.out.println(newObj.getUserName());
            } else {

            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject ValidateUsername(String username, String password)
            throws ClientProtocolException, IOException, JSONException {
        StringBuilder url = new StringBuilder(URL);
        HttpPost post = new HttpPost(url.toString());
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("token", "ABCD"));
            nameValuePairs.add(new BasicNameValuePair("func_name",
                    "validate_user"));
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = Client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity e = response.getEntity();
                String data = EntityUtils.toString(e);

                JSONObject statusValue = new JSONObject(data);
                return statusValue;

            } else {
                System.out.println(status);
                return null;
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

}

status.equals(&#34; ok&#34;)这是让我们知道是否记录的标识符

由于

2 个答案:

答案 0 :(得分:1)

看起来您可能误解了AsyncTask的功能,或者只是没有过多地阅读它。一个重要的澄清是AsyncTask不是Activity。重要的是要了解Activity是什么以及如何使用它与UI进行交互(它是少数允许您这样做的类之一)。

帮助您解决问题,而不是单独上课,只需将AsyncTask作为主要班级的内部班级。

public class Login extends Activity {
    // Your code like onCreate and stuff

    public class CheckUsername extends AsyncTask<String[], Void, String> {
        // do your async task stuff
    }
}

AsyncTask上进行扩展,在完成后台操作后,您可以通过onPostExecute()

将数据返回到班级
public class CheckUsername extends AsyncTask<String[], Void, String> {
    @Override
    protected String doInBackground(String[]... params) {
        //... do your stuff
        return statusValue;
    }

    @Override
    protected void onPostExecute(String statusValue) {
        setText(statusValue);
    }
}

在您的主要课程中,使用setText之类的方法可以让您根据需要使用返回值

public void setText(String return) {
    if (return.equals("ok") {    // or whatever it is supposed to equal if it's ok
         // set your text to whatever, you are ok
    }
    else {
         // set your text to whatever, bad password
    }
}

简而言之,AsyncTask背后的设计理念是

public class AsyncTaskName extends AsyncTask<IN_PARAMETER, PROGRESS_PARAMETER, RETURN_PARAMETER> {
    @Override
    protected RETURN_PARAMETER doInBackground(IN_PARAMETER... params) {
         // do your stuff
         return (variable of type RETURN_PARAMETER);
    }

    @Override
    protected void onProgressUpdate(PROGRESS_PARAMETER... progress) {
         // do your stuff
    }

    @Override
    protected void onPostExecute(RETURN_PARAMETER returnParam) {
         // interact with your UI, like calling a method from your activity
    }
}

值得注意的是,除非您想直接通知​​用户onProgressUpdate的更新进度,否则任务通常不需要AsyncTask

AsyncTasks旨在通过UI执行操作,但仍能够轻松地与其进行交互。方法doInBackground告诉AsyncTask我们想要完成UI线程,但onPostExecute告诉我们我们已经完成,关闭我们的线程并返回我们的数据。在没有onPostExecute的情况下,就UI交互而言,你在水中漂浮着。您不必从onPostExecute调用方法并且可以直接使用UI(如textView.setText(returnValue);)但是使用方法可以更清楚地知道Activity正在完成工作,而不是AsyncTask本身。

答案 1 :(得分:0)

你可以使用

protected void onPostExecute(Void unused) {

// NOTE: You can call UI Element here.

 }

它可能会解决您的问题。