Search code examples
androidandroid-asynctaskasmxksoap2android-spinner

Android AsyncTask Runtime Error


I develop a shopping app. I'm using web service for getting items. I call web service function in asynctask and I get items successfully. But I added login page and when user logged in, user navigate to items page, then asynctask can't get result. On debugging asynctask works, but when run the app normally asynctask doesn't work. If I select category on spinner, asynctask works. I think, its about calling asynctask on spinner selected items but I don't know how to fix it.

Again, on debugging program works as expected, but when I run the app normally asynctask can't get items. I have to select category in spinner for works as expected.

Login Page:

public class LoginUser extends AsyncTask<String,String,String>{

        private ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
        private String UName;
        private String PWord;

        public LoginUser(String user_name,String pass_word){
            this.UName = user_name;
            this.PWord = pass_word;
        }

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

        @Override
        protected String doInBackground(String... params) {
            String uid = GetUser(UName,PWord);
            return uid;
        }

        protected void onPostExecute(String uid){

            if(uid.equals("0")){
                Toast toast = Toast.makeText(getBaseContext(), "Login failed.", Toast.LENGTH_SHORT);
                toast.show();
            }
            else{
                SPE = SP.edit();
                SPE.putString("username", username);
                SPE.putString("password", password);
                SPE.putString("user_id", user_id);
                SPE.commit();
                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                bundle.putString("login", "login");
                intent.putExtras(bundle);
                startActivity(intent);
            }
            dialog.dismiss();
        }

    }

Item Page:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent = new Intent(MainActivity.this,ItemActivity.class);
        bundle = new Bundle();

        veriler = getIntent().getExtras();       
        String PageLogin = "";
        PageLogin = veriler.getString("login");

        spn = (Spinner)findViewById(R.id.spinner1);
        items = new String[4][0];
        categories = new String[11];
        categories[0] = "All";
        categories[1] = "Computers";
        categories[2] = "Mobile";
        categories[3] = "Home Electronics";
        categories[4] = "Fashion";
        categories[5] = "Magazines";
        categories[6] = "Health & Beauty";
        categories[7] = "Movie & Music";
        categories[8] = "Furnitures";
        categories[9] = "Toys";
        categories[10] = "Accessories";

        ArrayAdapter<String> spn_adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, categories);
        spn_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn.setAdapter(spn_adapter); 

        if(PageLogin.equals("login")){
            CatID="0";
            new GetAllItemsAS().execute();
        }

        spn.setOnItemSelectedListener(new OnItemSelectedListener(){

            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                selectedCat = spn.getSelectedItem().toString().trim();  
                if(selectedCat.equals("All")){
                    CatID="0";
                }
                else if(selectedCat.equals("Computers")){
                    CatID="1";
                }
                else if(selectedCat.equals("Mobile")){
                    CatID="2";
                }
                else if(selectedCat.equals("Home Electronics")){
                    CatID="3";
                }
                else if(selectedCat.equals("Fashion")){
                    CatID="4";
                }
                else if(selectedCat.equals("Magazines")){
                    CatID="5";
                }
                else if(selectedCat.equals("Health & Beauty")){
                    CatID="6";
                }
                else if(selectedCat.equals("Movie & Music")){
                    CatID="7";
                }
                else if(selectedCat.equals("Furnitures")){
                    CatID="8";
                }
                else if(selectedCat.equals("Toys")){
                    CatID="9";
                }
                else if(selectedCat.equals("Accessories")){
                    CatID="10";
                }
                new GetAllItemsAS().execute();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                CatID="0";
                new GetAllItemsAS().execute();
            }                   
        }); 
    }

All codes:

LoginActivity:

public class LoginActivity extends Activity {

    SharedPreferences SP;
    SharedPreferences.Editor SPE;
    private String username;
    private String password;
    private String user_id;

    private Bundle bundle;

    private String _username;
    private String _password;

    private TextView _usernameTxt;
    private TextView _passwordTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bundle = new Bundle();

        SP = getSharedPreferences("UserInfoXML", MODE_PRIVATE);

        _usernameTxt = (TextView)findViewById(R.id.userNameSignInTxt);
        _passwordTxt = (TextView)findViewById(R.id.PasswordSignInTxt);
        Button login = (Button)findViewById(R.id.SignInButton);

        login.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                username = _usernameTxt.getText().toString();
                password = _passwordTxt.getText().toString();
                new LoginUser(username,password).execute();
            }
        });

    }

    public class LoginUser extends AsyncTask<String,String,String>{

        private ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
        private String UName;
        private String PWord;

        public LoginUser(String user_name,String pass_word){
            this.UName = user_name;
            this.PWord = pass_word;
        }

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

        @Override
        protected String doInBackground(String... params) {
            String uid = GetUser(UName,PWord);
            return uid;
        }

        protected void onPostExecute(String uid){

            if(uid.equals("0")){
                Toast toast = Toast.makeText(getBaseContext(), "Login failed.", Toast.LENGTH_SHORT);
                toast.show();
            }
            else{
                SPE = SP.edit();
                SPE.putString("username", username);
                SPE.putString("password", password);
                SPE.putString("user_id", user_id);
                SPE.commit();
                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                bundle.putString("login", "login");
                intent.putExtras(bundle);
                startActivity(intent);
            }
            dialog.dismiss();
        }

    }


    public String GetUser(String user_name,String pass_word){
        String id = null;

        PropertyInfo kulad = new PropertyInfo();
        kulad.name= "username";
        kulad.setValue(user_name);
        kulad.type = PropertyInfo.STRING_CLASS;

        PropertyInfo parola = new PropertyInfo();
        parola.name= "password";
        parola.setValue(pass_word);
        parola.type = PropertyInfo.STRING_CLASS;

        SoapObject request = new SoapObject("http://shopar.org/", "Login");
        request.addProperty(kulad);
        request.addProperty(parola);


        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut=request;
        envelope.dotNet = true; 
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE("http://service.melihmucuk.com/ShopArWS.asmx");
        androidHttpTransport.debug = true;

       try {

       androidHttpTransport.call("http://shopar.org/Login", envelope);
       SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
       id = String.valueOf(response.toString());
} 
        catch (Exception e) {           
            e.printStackTrace();
            id = "0";
       }
        return id;
    }

MainActivity:

public class MainActivity extends Activity {

    private String[] categories;
    private String[][] items;
    private String selectedCat = "All";
    private String CatID = "0";
    private Spinner spn;
    private Intent intent;
    private Bundle bundle;
    private Bundle veriler;

private String[][] GetAllItems(){

        SoapObject request = new SoapObject("http://shopar.org/", "GetAllItem");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;     
        envelope.setOutputSoapObject(request);
        //http://192.168.2.240/ShopArService/ShopArWS.asmx
        HttpTransportSE androidHttpTransport = new HttpTransportSE("http://service.melihmucuk.com/ShopArWS.asmx");
        androidHttpTransport.debug = true;

       try {

       androidHttpTransport.call("http://shopar.org/GetAllItem", envelope);
       SoapObject response = (SoapObject) envelope.getResponse();
       int allCounter=0;
       int catCounter=0;
       String cat_id="";

       for(int i=0;i<response.getPropertyCount();i++){    
           Object property = response.getProperty(i);
           if(property instanceof SoapObject){
               SoapObject item = (SoapObject) property;
               cat_id = item.getProperty("cat_id").toString();
               if(CatID.equals("0")){
                   allCounter++;
               }
               else if(CatID.equals(cat_id)){
                   catCounter++;
               }
           }
       }

       if(CatID.equals("0")){
           items[0] = new String[response.getPropertyCount()]; //item_id
           items[1] = new String[response.getPropertyCount()]; //price
           items[2] = new String[response.getPropertyCount()]; //title
           items[3] = new String[response.getPropertyCount()]; //desc


           for(int i=0;i<response.getPropertyCount();i++){    
               Object property = response.getProperty(i);
               if(property instanceof SoapObject){
                   SoapObject item = (SoapObject) property;
                   String item_id = item.getProperty("item_id").toString();
                   String price = item.getProperty("price").toString() + " TL";
                   String title = item.getProperty("title").toString();
                   String desc = item.getProperty("desc").toString();
                       items[0][i] = item_id;
                       items[1][i] = price;
                       items[2][i] = title;
                       items[3][i] = desc;
               }    
       }

       }
       else{
           items[0] = new String[catCounter]; //item_id
           items[1] = new String[catCounter]; //price
           items[2] = new String[catCounter]; //title
           items[3] = new String[catCounter]; //desc

           for(int k=0;k<catCounter;k++){
               for(int i=0;i<response.getPropertyCount();i++){    
                   Object property = response.getProperty(i);
                   if(property instanceof SoapObject){
                       SoapObject item = (SoapObject) property;
                       String item_id = item.getProperty("item_id").toString();
                       String price = item.getProperty("price").toString() + " TL";
                       String title = item.getProperty("title").toString();
                       String desc = item.getProperty("desc").toString();
                       String catid = item.getProperty("cat_id").toString();
                       List <String> list = Arrays.asList(items[0]);
                       if(CatID.equals(catid)){
                           if(list.contains(item_id)){

                           }
                           else{
                               items[0][k] = item_id;
                               items[1][k] = price;
                               items[2][k] = title;
                               items[3][k] = desc;
                               break;
                           }
                       }
                   } 
               } 
           }   
       }
    }
        catch (Exception e) {           
            e.printStackTrace();
       }   
       return items;
    }

public class GetAllItemsAS extends AsyncTask<String,String,String[][]>{

    private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
    @Override
     protected void onPreExecute() {
        dialog.setMessage("Loading...");
        dialog.show();
     }

    @Override
    protected String[][] doInBackground(String... params) {
        GetAllItems();
        return items;
    }

    protected void onPostExecute(String[][] items){
        ASFinish();
        dialog.dismiss();
    }

}

public void ASFinish(){
    ListView liste = (ListView)findViewById(R.id.listView1);
    ListArrayAdapter adapter = new ListArrayAdapter(MainActivity.this,items[2],items[3],items[1],items[0]);
    liste.setAdapter(adapter);
    liste.setOnItemClickListener(new AdapterView.OnItemClickListener(){

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {                
            bundle.putString("item_id", items[0][arg2]);
            intent.putExtras(bundle);
            startActivity(intent);              
        }           
    });
}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//      intent = new Intent(MainActivity.this,ItemActivity.class);
//        bundle = new Bundle();

        veriler = getIntent().getExtras();       
        String PageLogin = "";
        if(veriler != null){
            PageLogin = veriler.getString("login");
        }

        spn = (Spinner)findViewById(R.id.spinner1);
        items = new String[4][0];
        categories = new String[11];
        categories[0] = "All";
        categories[1] = "Computers";
        categories[2] = "Mobile";
        categories[3] = "Home Electronics";
        categories[4] = "Fashion";
        categories[5] = "Magazines";
        categories[6] = "Health & Beauty";
        categories[7] = "Movie & Music";
        categories[8] = "Furnitures";
        categories[9] = "Toys";
        categories[10] = "Accessories";

        ArrayAdapter<String> spn_adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, categories);
        spn_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn.setAdapter(spn_adapter); 

        if(PageLogin.equals("login")){
            CatID="0";
            new GetAllItemsAS().execute();
        }

        spn.setOnItemSelectedListener(new OnItemSelectedListener(){

            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                selectedCat = spn.getSelectedItem().toString().trim();  
                if(selectedCat.equals("All")){
                    CatID="0";
                }
                else if(selectedCat.equals("Computers")){
                    CatID="1";
                }
                else if(selectedCat.equals("Mobile")){
                    CatID="2";
                }
                else if(selectedCat.equals("Home Electronics")){
                    CatID="3";
                }
                else if(selectedCat.equals("Fashion")){
                    CatID="4";
                }
                else if(selectedCat.equals("Magazines")){
                    CatID="5";
                }
                else if(selectedCat.equals("Health & Beauty")){
                    CatID="6";
                }
                else if(selectedCat.equals("Movie & Music")){
                    CatID="7";
                }
                else if(selectedCat.equals("Furnitures")){
                    CatID="8";
                }
                else if(selectedCat.equals("Toys")){
                    CatID="9";
                }
                else if(selectedCat.equals("Accessories")){
                    CatID="10";
                }
                new GetAllItemsAS().execute();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                CatID="0";
                new GetAllItemsAS().execute();
            }                   
        }); 
    }

Solution

  • on the onCreate method, you shouldn't create a new intent bu just get the intent that started the activity. Remove this lines :

    intent = new Intent(MainActivity.this,ItemActivity.class);
    bundle = new Bundle();
    

    and just get the variable as you did :

    veriler = getIntent().getExtras();       
    String PageLogin = "";
    if(veriler != null)
       PageLogin = veriler.getString("login");
    

    Also please respect java coding conventions.