0

I'm wondering how I can access the return statement with a static function. I have a static function with Async and I want to then get the return statement in another class - I know it sounds complex but, I'm sure it's an easy solution.

Login.class

public class LogIn extends Activity {
    Button login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        TextView top = (TextView) findViewById(R.id.textView2);
        final EditText user = (EditText) findViewById(R.id.etUser);
        final EditText pass = (EditText) findViewById(R.id.etPass);
        CheckBox stay = (CheckBox) findViewById(R.id.cBStay);
        Button login = (Button) findViewById(R.id.btLogin);





    login.setOnClickListener( new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            String user1 = user.getText().toString();
             String pass1 = pass.getText().toString();
            if(user1 !=null &user1.length()>=1 & pass1 !=null &pass1.length()>=1) {
                ComHelper.SendLogin(user1, pass1);

            }
        }
    });


    }



}

ComHelper.class

public class ComHelper extends AsyncTask<String, Void, String> {
    static String adress ="http://gta5news.com/login.php";
    String user;
    String pass;
    public static boolean SendLogin(String user1, String pass1){
    String user = user1.toString();
    String pass = pass1.toString();
    new ComHelper().execute(user1, pass1, adress);
    return true;

    }


    private static StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Return full string
        return total;

    }



    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        InputStream inputStream = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(adress);
        try {
            /*Add some data with NameValuePairs */
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("user", user));
            nameValuePairs.add(new BasicNameValuePair("password", pass));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            /*Execute */
            HttpResponse response = httpclient.execute(post);
            String str = inputStreamToString(response.getEntity().getContent())
                    .toString();
            Log.w("HttpPost", str);

            if (str.toString().equalsIgnoreCase("true"))
                return str;

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

        }



        return null;




        }
    }

Now, I want to see if ComHelper.SendLogin() returned true/or at least returned something.

EDIT: When the code is executed nothing happens, I guess that's because I'm not doing anything with the return statement.

TheBlueCat
  • 1,147
  • 5
  • 19
  • 38
  • Hunter's answer is correct... although since it always returns `true`, it's a bit superfluous. – Dave Newton Jun 04 '12 at 14:59
  • @DaveNewton Yes, I'm keep on changing the Async params I must have changed a variable by accident. Thanks anyway! – TheBlueCat Jun 04 '12 at 15:00
  • 1
    ComHelper.SendLogin(user1, pass1); -> methods in Java always should start with lower case, so that you can differentiate between Classes and methods... http://www.oracle.com/technetwork/java/codeconventions-150003.pdf – hovanessyan Jun 04 '12 at 15:00
  • @hovanessyan I was aware of the that rule, I just didn't know the specifics. :) – TheBlueCat Jun 04 '12 at 15:02
  • You want the result of SendLogin() right? Not if it just returns true or false. That is you want it to login and then return you a result? If so the answer marked below is not entirely correct since it is Async and you won't know the answer until it finishes. – NKijak Jun 04 '12 at 18:17
  • @NKijak How would I implement that? Just write a while statement. – TheBlueCat Jun 04 '12 at 18:21
  • Implement protected void onPostExecute (Result result) on your AsyncTask. Result is the Type you specified in the definition of your AsyncTask, in your case you want Boolean. This will run on the UI thread so you can modify the UI if you want. – NKijak Jun 06 '12 at 19:33

2 Answers2

1

You want to implement

protected void onPostExecute (Result result) 

on your AsyncTask implementation. The result parameter will be whatever you return from the doInBackground method. Since this runs in the UI thread you can modify the UI how you want at that time.

NKijak
  • 1,174
  • 9
  • 19
  • No. You shouldn't ever block on the UI thread. Are you asking because you want something to happen only when the result is returned? What ever you would do elsewhere by checking the result, just do that code in the onPostExecute. – NKijak Jun 07 '12 at 14:45
  • Yes, I want to display a toast and then create an intent. How do I construct it? The result is the parameter I computed from the do in background, correct? – TheBlueCat Jun 07 '12 at 14:47
  • Yep. In your case you have it typed as a String so the actual signature will be onPostExecute(String result). You can do whatever you need with that value and pop up your toast, etc. Are you asking how to make your ComHelper class more generic? I don't understand what you mean by "How do I construct it?" – NKijak Jun 07 '12 at 14:53
  • I just meant how do I construct the onPostExecute but, I know how to and I read through the AsynTask docs yesterday. – TheBlueCat Jun 07 '12 at 14:54
0

If you want to look at the value, then you need to save the return value of the method in a local variable

if(user1 !=null && user1.length() > 0 && pass1 !=null && pass1.length() > 0) 
{
     boolean comLogin = ComHelper.SendLogin(user1, pass1);
     if(comLogin)
     {
         //do something
     }
}
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • Ignore, I managed to figure it out by myself. 'if(comLogin = true) { /*do something */ }' – TheBlueCat Jun 04 '12 at 15:02
  • @TheBlueCat `if (comLogin)`, like in the answer? – Dave Newton Jun 04 '12 at 15:04
  • @TheBlueCat `if(comLogin)` is equivalent to `if(comLoogin == true)` – Hunter McMillen Jun 04 '12 at 15:04
  • @DaveNewton I managed to do it, the if statement now reads. if(comLogin = true) – TheBlueCat Jun 04 '12 at 15:05
  • @TheBlueCat That is incorrect, however... at least in the general case. – Dave Newton Jun 04 '12 at 15:05
  • @DaveNewton Care to explain? Should I put == instead? – TheBlueCat Jun 04 '12 at 15:06
  • @TheBlueCat Yes, because a single `=` is the assignment operator. No, because it's redundant, and should be simply `if (comLogin)`, as in the answer, and as explained by Hunter. – Dave Newton Jun 04 '12 at 15:07
  • You don't have to explicitly test if boolean values equal true or false. They are evaluated automatically. Though, if you want to throw in more clarity in your code, try to think of names like: isLoginSuccessful etc. So it will look like 'if(isLogginSuccessful) {/* do */ }' – hovanessyan Jun 04 '12 at 15:08
  • @TheBlueCat A single equals sign `=` is used to denote assignment, as in `int x = 5`; now `x` has the value of 5. A double equals sign `==` is used to test equality of primitive types `x == 5` will return `true` because `x` has the value of 5. – Hunter McMillen Jun 04 '12 at 15:08
  • FWIW, IMO the answer should be improved to use boolean `&&` operators. – Dave Newton Jun 04 '12 at 15:08
  • @DaveNewton I will edit above, put I copied that chunk from the OP's code – Hunter McMillen Jun 04 '12 at 15:09
  • 1
    Silly me! So, I should say `if (comLogin) comLogin.equals(true); ` – TheBlueCat Jun 04 '12 at 15:09
  • 1
    @TheBlueCat No, that would basically say "If it's true, see if it's true, and do nothing with the result." – Dave Newton Jun 04 '12 at 15:10
  • @TheBlueCat `comLogin` isn't an object and as such has no `.equals(...)` method – Hunter McMillen Jun 04 '12 at 15:11
  • @HunterMcMillen OH! Basically, when my helper class returns something we're testing that in the if statement? Is that correct? – TheBlueCat Jun 04 '12 at 15:11
  • @TheBlueCat You might want to check out some basic Java tutorials before proceeding *too* much further; it'll save time in the long run. – Dave Newton Jun 04 '12 at 15:14
  • @DaveNewton I also have two Apps on the market and this is just a rewrite with a few extra features and a new UI. http://i.imgur.com/IJ6OE.png – TheBlueCat Jun 04 '12 at 15:22
  • @TheBlueCat Great. I don't see *how*, if you don't know how to use the return value of a function, or check to see if a boolean is true, but ok. "The Java Docs" are *thousands* of pages, I have to say that I really don't believe you, not that it matters. Good luck, and carry on. – Dave Newton Jun 04 '12 at 15:32
  • @TheBlueCat [this one?](https://play.google.com/store/apps/details?id=com.gta5news.quik) Hm, well. – Dave Newton Jun 04 '12 at 15:35
  • I have read the Tutorial section and most the the classes and basic IO. Okay, https://play.google.com/store/apps/details?id=com.gta5news.quik&feature=more_from_developer#?t=W251bGwsMSwxLDEwMiwiY29tLmd0YTVuZXdzLnF1aWsiXQ.. – TheBlueCat Jun 04 '12 at 15:35
  • @DaveNewton What's wrong with it? It's a good first attempt. As I said, I'm rewriting all the code. Have you got any Apps? Oh, please turn down the patronizing comments. Do you really think I haven't read the Java docs and using static functions? – TheBlueCat Jun 04 '12 at 15:37
  • @TheBlueCat Correct, I do not believe you have, based on this question, and the number of comments it took to communicate how to check the return value of a function for being true--Java 101. Believing you're not very good at Java is a far different thing than being patronizing--I can have a low opinion of your Java skills without making a value judgement regarding you as a person. Do I have any *Android* apps on the market? No (although two are pending completion), but I fail to see the relevance.I *have* been developing in Java for 13 years now, and this wasn't an Android question. – Dave Newton Jun 04 '12 at 15:42
  • @TheBlueCat To clarify, you may well have read "the java docs" five times, but that does not change my belief that some time spent with some basic Java would be beneficial. Java is all about methods, using their return values, conditional logic, etc--most procedural and OOP languages are. That it escaped you, to me, is indicative that there are some missing fundamentals. Sorry if you view that as a personal attack--it isn't, it's advice from someone that's been doing this for decades. – Dave Newton Jun 04 '12 at 15:47
  • Read the chat. Yes, I've been using Java for four months, it's also my 'first' OOP language. – TheBlueCat Jun 04 '12 at 15:48
  • @TheBlueCat Great... My suggestion still stands. Good luck. – Dave Newton Jun 04 '12 at 15:52
  • @DaveNewton No, I'll keep on plugging away to Android -- I'll get better over time. – TheBlueCat Jun 04 '12 at 15:53
  • @TheBlueCat Of course you will--repetition reinforces knowledge. And I guarantee you it will go faster if you get very good at the fundamentals, which is what studying language fundamentals brings to the table. YMMV, although IMO outright ignoring advice from people that develop and educate for a living is short-sighted. – Dave Newton Jun 04 '12 at 15:57
  • @DaveNewton Book recommendations? I have the basics, I just get confused and then make silly questions on SO - I know what I'm doing it's just remembering Syntax/functions. and not making silly OOP mistakes. – TheBlueCat Jun 04 '12 at 15:59
  • Please move this conversation to chat. – Hunter McMillen Jun 04 '12 at 16:02
  • @Hunter Tried; I get an error message, now I can't. You can move it too, IIRC. – Dave Newton Jun 04 '12 at 16:03
  • @TheBlueCat But you *don't* have the basics, that's precisely what I'm saying--this question didn't have anything to do with OOP, either, really. IMO practicing without the overhead of complete frameworks/etc. is the easiest way to focus on language basics, because all you're dealing with is the language proper, not the additional cognitive load of the environment it's running in. I don't have any book recommendations; no idea what's on the market these days. – Dave Newton Jun 04 '12 at 16:03
  • @TheBlueCat Well, my degree is in compsci (with a few liberal arts minors) but I started programming in 1977 at a very young age (and made money at it--I was hooked), college was 1986, so mostly it's just been programming, essentially forever. – Dave Newton Jun 04 '12 at 16:30