0

My Aysnc task not displaying next Activity using Intent. Also Where to call Intent if I want to switch to next Activity using Async task. below is my code.

btn_login.setOnClickListener(new View.OnClickListener() {

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

                new Login_LC(getApplicationContext.this).execute();
                countriesList();

            }else {
            }
        }
    });


 private class Login_LC extends AsyncTask<String, Void, String> {
    private ProgressDialog dialog;
    String status = "";
    Context ctx;
    //  String auth_token;
    public Login_LC(Context context) {
        dialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("Please wait...");
        this.dialog.setCancelable(false);
        this.dialog.setCanceledOnTouchOutside(false);
        this.dialog.show();
    }

    @Override
    protected String doInBackground(String... urls) {
        String response = "";

        response = new SOAPService().authUser(urls[0], urls[1]);
        System.out.println("RESPONSE= " + response);

        status = new Auth_token().getStatus(response);
        System.out.println("STATUS= " + status);
        return status;
    }

    protected void onPostExecute(String s) {

        System.out.println("S= " + s);

                try{
                    JSONObject jsonObj = MainActivity.jsonObj.getJSONObject("data");
                    if(jsonObj!=null){
                        String req_Token = jsonObj.getString("request_token");
                        //      req_token = req_Token;
                        new GetSubAccount(someclass.this, req_Token).execute();    //Async task Below called here
                    }
                }
                catch(Exception e){
                    System.out.print("----" +e);
                }
                Toast.makeText(someclass.this, "Login successfull", Toast.LENGTH_LONG).show();

                try{

                Intent loginIntent = new Intent(ctx, Dialpad.class);
                ctx.startActivity(loginIntent);
                }
                catch(Exception e){
                    System.out.print("-----"+e);
                }

            }else if(s.equals("failed")){
                Toast.makeText(someclass.this,"Wrong username/password!",Toast.LENGTH_SHORT).show();
            }

            else {

                Toast.makeText(someclass.this, "Login failed!",
                        Toast.LENGTH_LONG).show();
            }

        }else{
            if(dialog.isShowing()){
                dialog.dismiss();
            }

            Toast.makeText(someclass.this,"No response from server!Please try again.",Toast.LENGTH_LONG).show();
        }
    }
}

SubAccount:

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

    JSONObject jsonObj;
    String req_Token;
    Vector numberList;
    Context ctx;

    private ProgressDialog dialog;

    public GetSubAccount(Context context, String req_Token) {
        // TODO Auto-generated constructor stub
        dialog = new ProgressDialog(context);
        this.req_Token = req_Token;
    }

    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("Please wait...");
        this.dialog.setCancelable(false);
        this.dialog.setCanceledOnTouchOutside(false);
        this.dialog.show();
    }

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

        String response  = null;

        try{
            response = new SOAPService().subAccount(req_Token);
            jsonObj = new JSONObject(response);

        }catch(Exception e){
            System.out.print("Exception-----"+e);
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        if(s!=null){
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            try{
                if (s.equals("success")) {
                    try{    
                        numberList = new Vector();
                                            myNumbers = new Vector();   //  this Vector used in next Activity   
                        JSONObject jObj1 = jsonObj.getJSONObject("data");
                        JSONArray jArr = jObj1.getJSONArray("PhoneNumber");
                        for(int i=0;i<=jArr.length();i++){
                            numberList.add(jArr.getString(i));
                            System.out.print("number-----  "+numberList);

                            JSONObject jObj2 = jArr.getJSONObject(i);
                            myNumbers.add(jObj2.getString("number"));       
                        }                       
                    }
                    catch(Exception e){
                        System.out.print("Device Exception---" +e);
                    }
                }
            }
            catch(Exception e){
                System.out.print("------"+e);
            }
        }else{
        }
    }
}

// Intent not working? where to call Intent? Please help. thanks. :)

Shandroid
  • 73
  • 1
  • 7

4 Answers4

3

You have the below in onPostExecute which is fine. But intent needs a valid context as a param. You say you get NullPointerException. Looking at the code context ctx is not initialized

Intent loginIntent = new Intent(ctx, Dialpad.class);
ctx.startActivity(loginIntent);

You have not initialize context

Context ctx;
//  String auth_token;
public Login_LC(Context context) {
    dialog = new ProgressDialog(context);
    ctx =context;  
}

But if AsyncTask is an inner class you don't need to initialize you can use startActivity directly.

Also you have

new Login_LC(getApplicationContext.this).execute();

Use

new Login_LC(ActivityName.this).execute();

Similarly

 Context ctx;

    private ProgressDialog dialog;

    public GetSubAccount(Context context, String req_Token) {
        // TODO Auto-generated constructor stub
        dialog = new ProgressDialog(context);
        this.req_Token = req_Token;
        ctx = context;
    }

Also check the answer by commonsware @

When to call activity context OR application context?

I want when login button press it call login_LC async task and then in it call subaccount Async task and then Next Activity shows up. Also in next Activity I am using subaccount post result.

You have

new GetSubAccount(someclass.this, req_Token).execute();

in onPostExecute of first AsyncTask fine. I guess someclass.this is the Activity context.

Remove the startActivity code in first Asynctask an move it to onPostExecue of second Asynctask

   @Override
    protected void onPostExecute(String s) {
        if(s!=null){
              dialog.dismiss();
              try{
                if (s.equals("success")) {

                        numberList = new Vector();
                        myNumbers = new Vector();   //  this Vector used in next Activity   
                        JSONObject jObj1 = jsonObj.getJSONObject("data");
                        JSONArray jArr = jObj1.getJSONArray("PhoneNumber");
                        for(int i=0;i<=jArr.length();i++){
                            numberList.add(jArr.getString(i));
                            System.out.print("number-----  "+numberList);
                            JSONObject jObj2 = jArr.getJSONObject(i);
                            myNumbers.add(jObj2.getString("number"));       
                        } 
                        Intent loginIntent = new Intent(ctx, Dialpad.class);
                       ctx.startActivity(loginIntent);
                }else{

                }                      

            }
            catch(Exception e){
                System.out.print("------"+e);
            }
        }
  }
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Man `Q` is Where to call `startActivity(intent)`, your ans does not mention that. – Arshad Ali Mar 06 '14 at 05:36
  • @SuperUser he has this `Intent loginIntent = new Intent(ctx, Dialpad.class); ctx.startActivity(loginIntent);` in `onPostExecute` its fine. Its needs a context as pointed out rightly. op points @ NPE in his comment – Raghunandan Mar 06 '14 at 05:38
  • I am getting "number" array in next activity like String[] = new String[someclass.myNumbers.size()]; , and it is giving error there? – Shandroid Mar 06 '14 at 06:45
1

You didn't initialize your Context object ctx...initialize it as below.

In Login_LC class...

Context ctx;
public Login_LC(Context context) {

    this.ctx = context;
    dialog = new ProgressDialog(context);
}

In GetSubAccount class...

Context ctx;
public GetSubAccount(Context context, String req_Token) {

    this.ctx = context;

    // TODO Auto-generated constructor stub
    dialog = new ProgressDialog(context);
    this.req_Token = req_Token;
}

And pass your Activity Context in btn_login's OnCLickListener as below...

new Login_LC(YourActivity).execute();

Update:

If you want to start your GetSubAccount asynctask from Login_LC then pass the Context which you got from Login_LC constructor as below...

new GetSubAccount(ctx).execute();

Update your onPostExecute() of Login_LC class as below...

@Override
protected void onPostExecute(String s) {

    System.out.println("S= " + s);

            try{
                JSONObject jsonObj = ctx.jsonObj.getJSONObject("data");
                if(jsonObj!=null){
                    String req_Token = jsonObj.getString("request_token");
                    //      req_token = req_Token;
                    new GetSubAccount(ctx, req_Token).execute();    //Async task Below called here
                }
            }
            catch(Exception e){
                System.out.print("----" +e);
            }
            Toast.makeText(ctx, "Login successfull", Toast.LENGTH_LONG).show();

            try{

            Intent loginIntent = new Intent(ctx, Dialpad.class);
            ctx.startActivity(loginIntent);
            }
            catch(Exception e){
                System.out.print("-----"+e);
            }

        }else if(s.equals("failed")){
            Toast.makeText(ctx,"Wrong username/password!",Toast.LENGTH_SHORT).show();
        }

        else {

            Toast.makeText(ctx, "Login failed!", Toast.LENGTH_LONG).show();
        }

    }else{
        if(dialog.isShowing()){
            dialog.dismiss();
        }

        Toast.makeText(ctx,"No response from server!Please try again.",Toast.LENGTH_LONG).show();
    }
}

Update your onPostExecute() method of GetSubAccount class as below...

@Override
protected void onPostExecute(String s) {
    if(s!=null){
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        try{
            if (s.equals("success")) {
                try{    
                    numberList = new Vector();
                                        myNumbers = new Vector();   //  this Vector used in next Activity   
                    JSONObject jObj1 = jsonObj.getJSONObject("data");
                    JSONArray jArr = jObj1.getJSONArray("PhoneNumber");
                    for(int i=0;i<=jArr.length();i++){
                        numberList.add(jArr.getString(i));
                        System.out.print("number-----  "+numberList);

                        JSONObject jObj2 = jArr.getJSONObject(i);
                        myNumbers.add(jObj2.getString("number"));       
                    }                       
                }
                catch(Exception e){
                    System.out.print("Device Exception---" +e);
                }
            }
        }
        catch(Exception e){
            System.out.print("------"+e);
        }

        //start your activity here
        Intent loginIntent = new Intent(ctx, Dialpad.class);
        ctx.startActivity(loginIntent);

    }else{
    }
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
  • Login_LC Async task is called in login button press and GetSubAccount Async task is in Login_LC. This is the confuson. now where to call Intent Also it is giving null pointer exception. – Shandroid Mar 06 '14 at 05:46
  • @Shandroid when do you want to start the activity? after some condition or some code is executed? – Raghunandan Mar 06 '14 at 05:47
  • I want when login button press it call login_LC async task and then in it call subaccount Async task and then Next Activity shows up. Also in next Activity I am using subaccount post result. – Shandroid Mar 06 '14 at 05:50
  • @Shandroid...see my updated answer and post the `LogCat` of `NullPointerException`. – Hamid Shatu Mar 06 '14 at 05:53
  • 1
    @Shandroid when login is successfull you don't invoke the other asynctask?. So when login is successfull start the new activity. If not invoke asynctask and start activtiy in onPostexecute of othere asynctask – Raghunandan Mar 06 '14 at 05:56
  • in Login_LC Async postexecute, I am running subaccount Async task like (new subaccount.execute()) and then Intent, it will run or not? – Shandroid Mar 06 '14 at 05:59
  • @Shandroid if you want to start activity after the second asynctask does the background computation start Activity in onPostExecute of the second asynctask it will work. check the edit in my post. To pass psot results use `intent.putExtra` and `intent.getExtra` – Raghunandan Mar 06 '14 at 06:03
  • no its not working..it is again giving me null pointer exception. I think error is in subaccount postExecute(), I am getting value from here and passing to next activity. – Shandroid Mar 06 '14 at 06:37
1

Try starting new activity like this:

    @Override
    protected void onPostExecute(Void result) 
    {
        super.onPostExecute(result);
        Intent intent = new Intent(MyAsyncTaskActivity.this, NextActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        getApplicationContext().startActivity(intent);
    }
pratiti-systematix
  • 792
  • 11
  • 28
0

Since you didnt initialize the context... replace loginIntent in onPostexcecute

Intent loginIntent = new Intent(ctx, Dialpad.class);
ctx.startActivity(loginIntent);

to

Intent loginIntent = new Intent(dialog.getContext(), Dialpad.class);
dialog.getContext().startActivity(loginIntent);
Santhosh
  • 1,867
  • 2
  • 16
  • 23