Example usage for java.lang NullPointerException printStackTrace

List of usage examples for java.lang NullPointerException printStackTrace

Introduction

In this page you can find the example usage for java.lang NullPointerException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:rta.ae.sharekni.RegisterNewTest.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {//from www.j a  va2  s . c o m
        if (TakeATour.getInstance() != null) {
            TakeATour.getInstance().finish();
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    registerNewTestActivity = this;
    mContext = this;
    //        cal.add(Calendar.YEAR, -18);

    year_x = cal.get(Calendar.YEAR);
    month_x = cal.get(Calendar.MONTH);
    day_x = cal.get(Calendar.DAY_OF_MONTH);

    setContentView(R.layout.activity_register_new_test);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    //        txt_year = (TextView) findViewById(R.id.txt_year);
    //        txt_year.setText("0");
    txt_beforeCal = (TextView) findViewById(R.id.txt_beforeCal);
    txt_dayOfWeek = (TextView) findViewById(R.id.txt_dayOfWeek);
    showDialogOnButtonClick();

    driver_toggle = (ImageView) findViewById(R.id.driver_toggle);
    passenger_toogle = (ImageView) findViewById(R.id.passenger_toggle);
    both_toggle = (ImageView) findViewById(R.id.both_toggle);
    both_toggle_active = (ImageView) findViewById(R.id.both_toggle_active);
    driver_toggle_active = (ImageView) findViewById(R.id.driver_toggle_active);
    passenger_toggle_active = (ImageView) findViewById(R.id.passenger_toggle_active);

    btn_save = (Button) findViewById(R.id.btn_register_id);
    btn_upload_image = (Button) findViewById(R.id.btnUploadPhotoReg);
    edit_fname = (EditText) findViewById(R.id.edit_reg_fname);
    edit_lname = (EditText) findViewById(R.id.edit_reg_lname);
    edit_phone = (EditText) findViewById(R.id.edit_reg_phone);
    edit_pass = (EditText) findViewById(R.id.edit_reg_pass);
    edit_user = (EditText) findViewById(R.id.edit_reg_username);
    txt_comma = (TextView) findViewById(R.id.Register_comma_cal);
    malefemale_txt = (TextView) findViewById(R.id.malefemale_txt);
    femalemale_txt = (TextView) findViewById(R.id.femalemale_txt);

    malefemale = (ImageView) findViewById(R.id.malefemale);
    femalemale = (ImageView) findViewById(R.id.femalemale);

    //Terms_And_Cond_txt = (TextView) findViewById(R.id.Terms_And_Cond_txt);

    txt_lang = (TextView) findViewById(R.id.autocomplete_lang_id);
    txt_country = (AutoCompleteTextView) findViewById(R.id.autocompletecountry_id);

    Terms_And_Cond_txt_2 = (TextView) findViewById(R.id.Terms_And_Cond_txt_2);
    Terms_And_Cond_txt_2
            .setText(Html.fromHtml("<u><font color=#e72433>" + getString(R.string.reg_terms) + "</font></u>"));
    txt_terms = (RelativeLayout) findViewById(R.id.terms_relative);
    Privacy_and_poolicy = (TextView) findViewById(R.id.Privacy_and_poolicy);
    Privacy_and_poolicy
            .setText(Html.fromHtml("<u><font color=#e72433>" + getString(R.string.reg_policy) + "</font></u>"));

    FirstName_Linear = (LinearLayout) findViewById(R.id.FirstName_Linear);
    LastName_Linear = (LinearLayout) findViewById(R.id.LastName_Linear);
    MobileNumber_Linear = (LinearLayout) findViewById(R.id.MobileNumber_Linear);
    UserName_Linear = (LinearLayout) findViewById(R.id.UserName_Linear);
    Password_Linear = (LinearLayout) findViewById(R.id.Password_Linear);
    //   Nat_Linear = (LinearLayout) findViewById(R.id.Nat_Linear);
    Language_Linear = (LinearLayout) findViewById(R.id.Language_Linear);
    Date_Relative = (RelativeLayout) findViewById(R.id.datepicker_id);

    AgeCheckBox = (CheckBox) findViewById(R.id.AgeCheckBox);

    initToolbar();

    txt_terms.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getBaseContext(), TermsAndCond.class);
            startActivity(intent);

        }
    });

    Privacy_and_poolicy.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getBaseContext(), Privacy_Policy.class);
            startActivity(intent);
        }
    });

    btn_upload_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final CharSequence[] items = { getString(R.string.take_photo),
                    getString(R.string.choose_from_library), getString(R.string.cancel) };
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                    RegisterNewTest.this);
            builder.setTitle(getString(R.string.add_photo));
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (items[item].equals(getString(R.string.take_photo))) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, 0);
                    } else if (items[item].equals(getString(R.string.choose_from_library))) {
                        Intent intent = new Intent(Intent.ACTION_PICK,
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        intent.setType("image/*");
                        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_file)),
                                1337);
                    } else if (items[item].equals(getString(R.string.cancel))) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    });

    edit_fname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                edit_fname.setHint(getString(R.string.Reg_FirstN));
                if (edit_fname.getText().length() == 0) {
                    FirstName_Linear.setBackgroundResource(R.drawable.user_register_border_error);
                } else {
                    FirstName_Linear.setBackgroundResource(R.drawable.user_register_border);
                }
            }
        }
    });

    edit_lname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                edit_lname.setHint(getString(R.string.Reg_LastN));
                if (edit_lname.getText().length() == 0) {
                    LastName_Linear.setBackgroundResource(R.drawable.user_register_border_error);
                } else {
                    LastName_Linear.setBackgroundResource(R.drawable.user_register_border);
                }
            }
        }
    });

    edit_phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                edit_phone.setHint(getString(R.string.REg_Mobile));
                if (edit_phone != null) {
                    if (edit_phone.length() < 9) {
                        Toast.makeText(RegisterNewTest.this, getString(R.string.short_mobile),
                                Toast.LENGTH_SHORT).show();
                        MobileNumber_Linear.setBackgroundResource(R.drawable.user_register_border_error);
                    } else {
                        MobileNumber_Linear.setBackgroundResource(R.drawable.user_register_border);
                    }
                } else {
                    MobileNumber_Linear.setBackgroundResource(R.drawable.user_register_border);
                }
            }
            if (hasFocus) {
                edit_phone.setHint("");
            }
        }
    });

    edit_user.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                edit_user.setHint(getString(R.string.Reg_Email));
                if (!isEmailValid(edit_user.getText().toString())) {
                    vailedEmail = false;
                    UserName_Linear.setBackgroundResource(R.drawable.user_register_border_error);
                    Toast.makeText(RegisterNewTest.this, getString(R.string.email_valid_form),
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                vailedEmail = true;
                UserName_Linear.setBackgroundResource(R.drawable.user_register_border);
            }
            if (hasFocus) {
                edit_user.setHint("");
            }
        }
    });

    edit_pass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                edit_pass.setHint(R.string.password);
                if (edit_pass != null) {
                    if (edit_pass.length() <= 4) {
                        Password_Linear.setBackgroundResource(R.drawable.user_register_border_error);
                        Toast.makeText(RegisterNewTest.this, getString(R.string.short_pass), Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            } else {
                Password_Linear.setBackgroundResource(R.drawable.user_register_border);
            }
            if (hasFocus) {
                edit_pass.setHint("");
            }
        }
    });

    //        txt_country.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    //            public void onFocusChange(View v, boolean hasFocus) {
    //                Boolean result = false;
    //                if (!hasFocus) {
    //                    txt_country.setHint(getString(R.string.nationality));
    //                    if (Country_List.size() != 0 && txt_country.getText() != null && !txt_country.getText().toString().equals(getString(R.string.nationality))) {
    //                        for (int i = 0; i <= 193; i++) {
    //                            String a = Country_List.get(i).get("NationalityEnName");
    //                            String b = txt_country.getText().toString();
    //                            if (a.equals(b)) {
    //                                result = true;
    //                            }
    //                        }
    //                    }
    //                    if (!result) {
    //                        txt_country.setBackgroundResource(R.drawable.user_register_border_error);
    //                        Toast.makeText(RegisterNewTest.this, R.string.unknown_country, Toast.LENGTH_SHORT).show();
    //                    } else {
    //                        txt_country.setBackgroundResource(R.drawable.user_register_border);
    //                    }
    //                }
    //                if (hasFocus) {
    //                    txt_country.setHint("");
    //                }
    //            }
    //        });

    txt_lang.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            Boolean result = false;
            if (!hasFocus) {
                txt_lang.setHint(getString(R.string.language));
                if (Lang_List.size() != 0 && txt_lang.getText() != null
                        && !txt_lang.getText().toString().equals(getString(R.string.Reg_PrefLang))) {
                    for (int i = 0; i <= Lang_List.size(); i++) {
                        String a = Lang_List.get(i).get("NationalityEnName");
                        String b = txt_lang.getText().toString();
                        if (a.equals(b)) {
                            result = true;
                        }
                    }
                } else {
                    Nat_Linear.setBackgroundResource(R.drawable.user_register_border);
                }
                if (!result) {
                    Nat_Linear.setBackgroundResource(R.drawable.user_register_border_error);
                    //                            Toast.makeText(RegisterNewTest.this, R.string.unknown_language, Toast.LENGTH_SHORT).show();
                }
            }
            if (hasFocus) {
                txt_lang.setHint("");
            }
        }
    });

    both_toggle.setOnClickListener(this);
    driver_toggle.setOnClickListener(this);
    passenger_toogle.setOnClickListener(this);
    both_toggle_active.setOnClickListener(this);
    passenger_toggle_active.setOnClickListener(this);
    driver_toggle_active.setOnClickListener(this);

    // get Languages
    new lang().execute();

    // get nationals
    //        new nat().execute();

    btn_save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!vailedEmail) {
                UserName_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            } else {
                UserName_Linear.setBackgroundResource(R.drawable.user_register_border);
            }

            if (edit_fname.getText().length() == 0) {
                FirstName_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            } else {
                FirstName_Linear.setBackgroundResource(R.drawable.user_register_border);
            }
            if (edit_lname.getText().length() != 0) {
                LastName_Linear.setBackgroundResource(R.drawable.user_register_border);
            } else {
                LastName_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            }
            if (edit_phone.getText().length() != 0) {
                MobileNumber_Linear.setBackgroundResource(R.drawable.user_register_border);
            } else {
                MobileNumber_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            }
            if (edit_pass.getText().length() != 0) {
                Password_Linear.setBackgroundResource(R.drawable.user_register_border);
            } else {
                Password_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            }

            //                if (txt_country.getText().length() != 0) {
            //                    Nat_Linear.setBackgroundResource(R.drawable.user_register_border);
            //                } else {
            //                    Nat_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            //                }
            if (txt_lang.getText().length() != 0) {
                Language_Linear.setBackgroundResource(R.drawable.user_register_border);
            } else {
                Language_Linear.setBackgroundResource(R.drawable.user_register_border_error);
            }
            if (AgeCheckBox.isChecked()) {
                Date_Relative.setBackgroundResource(R.drawable.user_register_border);
            }
            if (!AgeCheckBox.isChecked()) {
                Toast.makeText(RegisterNewTest.this, R.string.fill_all_error, Toast.LENGTH_SHORT).show();
                Date_Relative.setBackgroundResource(R.drawable.user_register_border_error);
            } else {
                if (edit_fname.getText() != null
                        && !edit_fname.getText().toString().equals(getString(R.string.Reg_FirstN))
                        && edit_lname.getText() != null
                        && !edit_lname.getText().toString().equals(getString(R.string.Reg_LastN))
                        && edit_phone.getText() != null
                        && !edit_phone.getText().toString().equals(getString(R.string.REg_Mobile))
                        && edit_pass.getText() != null
                        && !edit_pass.getText().toString().equals(getString(R.string.Reg_pass))
                        && edit_user.getText() != null
                        && !edit_user.getText().toString().equals(getString(R.string.Reg_Email))
                        && !edit_lname.getText().toString().equals(getString(R.string.Reg_Nat))
                        && Language_ID != -1 && vailedEmail == true) {
                    ArrayList codes = new ArrayList();
                    codes.add("50");
                    codes.add("52");
                    codes.add("55");
                    codes.add("56");
                    String code = edit_phone.getText().toString().substring(0, 2);

                    if (edit_pass.getText().length() < 5) {
                        Toast.makeText(RegisterNewTest.this, R.string.Password_sould_be_more_than_five_chars,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        if (!codes.contains(code)) {
                            Toast.makeText(RegisterNewTest.this, getString(R.string.short_mobile),
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            String Fname = edit_fname.getText().toString();
                            String Lname = edit_lname.getText().toString();
                            String phone = edit_phone.getText().toString();
                            String pass = edit_pass.getText().toString();
                            String user = edit_user.getText().toString();
                            // String country = txt_country.getText().toString();
                            String country = "0";
                            //                        String lang = txt_lang.getText().toString();
                            char gender = i;
                            //    String birthdate = full_date;
                            int x = Language_ID;
                            //                            int y = Nationality_ID;
                            RegisterJsonParse registerJsonParse = new RegisterJsonParse();

                            switch (usertype) {
                            case "Passenger":
                                registerJsonParse.stringRequest(GetData.DOMAIN + "RegisterPassenger?firstName="
                                        + URLEncoder.encode(Fname) + "&lastName=" + URLEncoder.encode(Lname)
                                        + "&mobile=" + phone + "&username=" + URLEncoder.encode(user)
                                        + "&password=" + URLEncoder.encode(pass) + "&gender=" + gender
                                        + "&BirthDate=" + "&NationalityId=0" + "&PreferredLanguageId=" + x
                                        + "&photoName=" + uploadedImage, RegisterNewTest.this, country, "P");
                                Log.d("Registration :", GetData.DOMAIN + "RegisterPassenger?firstName="
                                        + URLEncoder.encode(Fname) + "&lastName=" + URLEncoder.encode(Lname)
                                        + "&mobile=" + phone + "&username=" + URLEncoder.encode(user)
                                        + "&password=" + URLEncoder.encode(pass) + "&gender=" + gender
                                        + "&BirthDate=" + "&NationalityId=0" + "&PreferredLanguageId=" + x
                                        + "&photoName=" + uploadedImage);
                                break;
                            case "1":
                                Toast.makeText(RegisterNewTest.this, R.string.select_type_first_error,
                                        Toast.LENGTH_SHORT).show();

                                break;
                            case "Driver":

                                registerJsonParse.stringRequest(
                                        GetData.DOMAIN + "RegisterDriver?firstName=" + URLEncoder.encode(Fname)
                                                + "&lastName=" + URLEncoder.encode(Lname) + "&mobile=" + phone
                                                + "&username=" + URLEncoder.encode(user) + "&password="
                                                + URLEncoder.encode(pass) + "&gender=" + gender + "&BirthDate="
                                                + "&licenseScannedFileName=nofile.jpg"
                                                + "&TrafficFileNo=nofile.jpg" + "&photoName=" + uploadedImage
                                                + "&NationalityId=0" + "&PreferredLanguageId=" + x,
                                        RegisterNewTest.this, country, "D");
                                Log.d("Reg Driver",
                                        GetData.DOMAIN + "RegisterDriver?firstName=" + URLEncoder.encode(Fname)
                                                + "&lastName=" + URLEncoder.encode(Lname) + "&mobile=" + phone
                                                + "&username=" + URLEncoder.encode(user) + "&password="
                                                + URLEncoder.encode(pass) + "&gender=" + gender + "&BirthDate="
                                                + "&licenseScannedFileName=nofile.jpg"
                                                + "&TrafficFileNo=nofile.jpg" + "&photoName=" + uploadedImage
                                                + "&NationalityId=0" + "&PreferredLanguageId=" + x);
                                break;
                            case "Both":
                                registerJsonParse.stringRequest(
                                        GetData.DOMAIN + "RegisterDriver?firstName=" + URLEncoder.encode(Fname)
                                                + "&lastName=" + URLEncoder.encode(Lname) + "&mobile=" + phone
                                                + "&username=" + URLEncoder.encode(user) + "&password="
                                                + URLEncoder.encode(pass) + "&gender=" + gender + "&BirthDate="
                                                + "&licenseScannedFileName=nofile.jpg"
                                                + "&TrafficFileNo=nofile.jpg" + "&photoName=" + uploadedImage
                                                + "&NationalityId=0" + "&PreferredLanguageId=" + x,
                                        RegisterNewTest.this, country, "D");
                                break;
                            }
                        }

                    }
                } else {
                    Toast.makeText(RegisterNewTest.this, R.string.fill_all_error, Toast.LENGTH_SHORT).show();
                }
            }

        }

        //            else {
        //                    Toast.makeText(RegisterNewTest.this, R.string.fill_all_error, Toast.LENGTH_SHORT).show();
        //                }
        //
    });

    malefemale.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            malefemale.setVisibility(View.INVISIBLE);
            femalemale.setVisibility(View.VISIBLE);
            malefemale_txt.setTextColor(Color.GRAY);
            femalemale_txt.setTextColor(Color.RED);
            i = 'F';

        }
    });

    femalemale.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            femalemale.setVisibility(View.INVISIBLE);
            malefemale.setVisibility(View.VISIBLE);
            malefemale_txt.setTextColor(Color.RED);
            femalemale_txt.setTextColor(Color.GRAY);
            i = 'M';
        }
    });

    femalemale_txt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            malefemale_txt.setTextColor(Color.GRAY);
            femalemale_txt.setTextColor(Color.RED);

            malefemale.setVisibility(View.INVISIBLE);
            femalemale.setVisibility(View.VISIBLE);
            i = 'M';

        }
    });

    malefemale_txt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            i = 'F';
            malefemale_txt.setTextColor(Color.RED);
            femalemale_txt.setTextColor(Color.GRAY);

            malefemale.setVisibility(View.VISIBLE);
            femalemale.setVisibility(View.INVISIBLE);
        }
    });

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:org.csp.everyaware.offline.Map.java

/****************** DISEGNA PATH ****************************************************/

//draw path from a list of points
public void drawPath() {
    ExtendedLatLng newLatLng = null;/*  www  .  j a  v  a  2  s .co m*/
    ExtendedLatLng precLatLng = null;
    int color = Color.DKGRAY;

    try {
        Log.d("Map", "polyline count: " + mLatLngPoints.size());

        for (int i = 0; i < mLatLngPoints.size(); i++) {
            newLatLng = mLatLngPoints.get(i);
            color = Color.DKGRAY; //color for a segment without bc value

            //10 is upper limit in scale, so a black carbon of 10 (multiplied by 10) must be drawn in dark red
            if ((newLatLng.mBc > 0) && (newLatLng.mBc <= 10))
                color = ColorHelper.numberToColor(newLatLng.mBc * BC_MULTIPLIER);
            else
                color = ColorHelper.numberToColor(100);

            //draw segment with appropriate color (dark grey if no bc value is present) 
            if (precLatLng != null)
                mGoogleMap.addPolyline(new PolylineOptions().add(newLatLng.mLatLng).add(precLatLng.mLatLng)
                        .width(5).color(color));

            String annotation = newLatLng.mUserAnn;

            if (!annotation.equals("")) {
                BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.annotation_marker);
                mGoogleMap.addMarker(
                        new MarkerOptions().position(newLatLng.mLatLng).title("AQI: " + newLatLng.mBc)
                                .snippet("Annotation: " + annotation).icon(icon).anchor(0.25f, 1f)); //Map Markers are 'anchored' by default to the middle of the bottom of layout (i.e., anchor(0.5,1)).
            }

            precLatLng = newLatLng;
        }

        //center camera on last trackn position
        //if((mTrackMode)&&(mCameraTrackOn))
        try {
            mGoogleMap.animateCamera(CameraUpdateFactory
                    .newLatLngZoom(mLatLngPoints.get(mLatLngPoints.size() - 1).mLatLng, mZoom));
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {

    }
}

From source file:org.csp.everyaware.offline.Map.java

/***************************** INIT GOOGLE MAP **********************************************/

private void setUpMap() {
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mGoogleMap.getUiSettings().setCompassEnabled(false);
    mGoogleMap.getUiSettings().setZoomControlsEnabled(false);

    //assign istance of MyLocationSource to google maps and activate it
    //mGoogleMap.setLocationSource(mLocationSource); 
    //mGoogleMap.setMyLocationEnabled(true);

    //mGoogleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());

    //animate camera to an initial zoom level 
    try {//from  w w w . j  a v  a 2 s.  com
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(mZoom), 1500, null);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

    mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(LatLng arg0) {
            if (mZoomControls != null) {
                mOnMapClickTs = new Date().getTime();

                mZoomControls.setVisibility(View.VISIBLE);

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if ((new Date().getTime() - mOnMapClickTs) >= 2500)
                            mZoomControls.setVisibility(View.GONE);
                    }

                }, 3000);
            }
        }
    });

    mGoogleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng latLng) {
            double minDistance = 0;
            int index = -1;

            Log.d("Map", "onMapLongClick()--> lat lng: " + latLng.latitude + ", " + latLng.longitude);

            //calculate bounding box around tapped point (tapped point is the center of BB)
            LatLng topLeft = new LatLng(latLng.latitude + 0.01, latLng.longitude - 0.01);
            LatLng bottomRight = new LatLng(latLng.latitude - 0.01, latLng.longitude + 0.01);

            //calculate intersection between BB and path and the point of path inside the intersection that
            //is nearer to tapped point
            //output of the cycle is the index of path point nearest to tapped point
            for (int i = 0; i < mLatLngPoints.size(); i++) {
                ExtendedLatLng extLatLng = mLatLngPoints.get(i);

                //if actual path point is inside BB, calculate distance between tapped point and path point and save it 
                if ((extLatLng.mLatLng.latitude <= topLeft.latitude)
                        && (extLatLng.mLatLng.latitude >= bottomRight.latitude)) {
                    if ((extLatLng.mLatLng.longitude >= topLeft.longitude)
                            && (extLatLng.mLatLng.longitude <= bottomRight.longitude)) {
                        double latDiff = Math.abs(extLatLng.mLatLng.latitude - latLng.latitude);
                        double lonDiff = Math.abs(extLatLng.mLatLng.longitude - latLng.longitude);
                        double distance = Math.sqrt(latDiff * latDiff + lonDiff * lonDiff);

                        if (i == 0) {
                            minDistance = distance;
                            index = 0;
                        } else if (distance < minDistance) {
                            minDistance = distance;
                            index = i;
                        }
                    }
                }
            }

            //if an index is present, it is the index of the path point inside BB nearest to tapped point
            if (index > -1) {
                ExtendedLatLng nearestPathLatLng = mLatLngPoints.get(index);
                insertAnnDialog(nearestPathLatLng);
            } else
                Toast.makeText(getApplicationContext(), "Path not found", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:org.csp.everyaware.offline.Map.java

@Override
public void onResume() {
    Utils.paused = false;/*  ww  w  . j av  a2 s  .c  om*/
    super.onResume();
    mMapView.onResume();

    //acquire partial wake lock
    if (!mWakeLock.isHeld())
        mWakeLock.acquire();

    mLocationSource.registerLocUpdates();

    if (Utils.uploadOn == Constants.INTERNET_ON_INT)
        mInterUplStatus.setBackgroundResource(R.drawable.internet_on);
    else if (Utils.uploadOn == Constants.INTERNET_OFF_INT)
        mInterUplStatus.setBackgroundResource(R.drawable.internet_off);
    else if (Utils.uploadOn == Constants.UPLOAD_ON_INT)
        mInterUplStatus.setBackgroundResource(R.drawable.upload);

    if (mCameraTrackOn)
        mFollowCamBtn.setBackgroundResource(R.drawable.follow_camera_pressed);
    else
        mFollowCamBtn.setBackgroundResource(R.drawable.follow_camera_not_pressed);

    //register receiver for messages from store'n'forward service
    IntentFilter internetOnFilter = new IntentFilter(Constants.INTERNET_ON);
    registerReceiver(mServiceReceiver, internetOnFilter);
    IntentFilter internetOffFilter = new IntentFilter(Constants.INTERNET_OFF);
    registerReceiver(mServiceReceiver, internetOffFilter);
    IntentFilter uploadOnFilter = new IntentFilter(Constants.UPLOAD_ON);
    registerReceiver(mServiceReceiver, uploadOnFilter);
    IntentFilter uploadOffFilter = new IntentFilter(Constants.UPLOAD_OFF);
    registerReceiver(mServiceReceiver, uploadOffFilter);

    //register receiver for messages from gps tracking service
    IntentFilter phoneGpsOnFilter = new IntentFilter(Constants.PHONE_GPS_ON);
    registerReceiver(mGpsServiceReceiver, phoneGpsOnFilter);
    IntentFilter networkGpsOnFilter = new IntentFilter(Constants.NETWORK_GPS_ON);
    registerReceiver(mGpsServiceReceiver, networkGpsOnFilter);
    IntentFilter phoneGpsOffFilter = new IntentFilter(Constants.PHONE_GPS_OFF);
    registerReceiver(mGpsServiceReceiver, phoneGpsOffFilter);

    //get selected track and draw it on map
    mTrack = Utils.track;

    if (mTrack != null) {
        Log.d("Map", "onCreate()--> shown session id: " + mTrack.mSessionId);

        if (mGoogleMap != null)
            mGoogleMap.clear();

        int divider = 1;

        long trackLength = mTrack.mNumOfRecords;

        Log.d("Map", "onResume()--> track length: " + trackLength);

        if (trackLength > 1800)
            divider = 2;
        if (trackLength > 3600)
            divider = 4;
        if (trackLength > 7200)
            divider = 8;
        if (trackLength > 14400)
            divider = 16;

        mLatLngPoints = mDbManager.loadLatLngPointsBySessionId(mTrack.mSessionId, divider);
        if (mLatLngPoints != null) {
            int size = mLatLngPoints.size();

            if (size > 0) {
                calcMinAvgPollValue();
                drawPath();
                mCameraTrackOn = false;
                if (mGoogleMap != null)
                    try {
                        mGoogleMap.animateCamera(
                                CameraUpdateFactory.newLatLng(mLatLngPoints.get(size - 1).mLatLng));
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
            }
        }
    }

    if (mMapPolygons == null)
        mMapPolygons = new ArrayList<Polygon>();

    int color;

    //draw map cluster on the map
    if ((mMapClusters != null) && (mMapClusters.size() > 0)) {
        for (int i = 0; i < mMapClusters.size(); i++) {
            MapCluster mapCluster = mMapClusters.get(i);

            if (mapCluster.mBcLevel != 0) {
                if ((mapCluster.mBcLevel > 0) && (mapCluster.mBcLevel <= 10))
                    color = ColorHelper.numberToColor(mapCluster.mBcLevel * BC_MULTIPLIER);
                else
                    color = ColorHelper.numberToColor(100);

                mMapPolygons.add(mGoogleMap.addPolygon(new PolygonOptions()
                        .add(new LatLng(mapCluster.mMinLat, mapCluster.mMinLon),
                                new LatLng(mapCluster.mMinLat, mapCluster.mMaxLon),
                                new LatLng(mapCluster.mMaxLat, mapCluster.mMaxLon),
                                new LatLng(mapCluster.mMaxLat, mapCluster.mMinLon))
                        .strokeColor(Color.TRANSPARENT)
                        .fillColor(Color.parseColor("#66" + String.format("%06X", 0xFFFFFF & color)))));
            }
        }
    }
}

From source file:de.geeksfactory.opacclient.frontend.AccountFragment.java

@Override
public void accountSelected(Account account) {

    svAccount.setVisibility(View.GONE);
    unsupportedErrorView.setVisibility(View.GONE);
    answerErrorView.setVisibility(View.GONE);
    errorView.removeAllViews();/*from  w w  w  .  ja v a  2 s.  com*/
    llLoading.setVisibility(View.VISIBLE);

    setRefreshing(false);
    supported = true;

    this.account = app.getAccount();
    OpacApi api;
    try {
        api = app.getApi();
    } catch (NullPointerException e) {
        e.printStackTrace();
        return;
    }
    if (api != null && !app.getLibrary().isAccountSupported()) {
        supported = false;
        // Not supported with this api at all
        llLoading.setVisibility(View.GONE);
        unsupportedErrorView.setVisibility(View.VISIBLE);
        tvErrBodyU.setText(R.string.account_unsupported_api);
        btSend.setText(R.string.write_mail);
        btSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "info@opacapp.de" });
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "Bibliothek " + app.getLibrary().getIdent());
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        getResources().getString(R.string.interested_to_help));
                emailIntent.setType("text/plain");
                startActivity(Intent.createChooser(emailIntent, getString(R.string.write_mail)));
            }
        });

    } else if (account.getPassword() == null || account.getPassword().equals("null")
            || account.getPassword().equals("") || account.getName() == null || account.getName().equals("null")
            || account.getName().equals("")) {
        // No credentials entered
        llLoading.setVisibility(View.GONE);
        answerErrorView.setVisibility(View.VISIBLE);
        btPrefs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AccountEditActivity.class);
                intent.putExtra(AccountEditActivity.EXTRA_ACCOUNT_ID, app.getAccount().getId());
                startActivity(intent);
            }
        });
        tvErrHeadA.setText("");
        tvErrBodyA.setText(R.string.status_nouser);

    } else {
        // Supported
        Context ctx = getActivity() != null ? getActivity() : OpacClient.getEmergencyContext();
        AccountDataSource adatasource = new AccountDataSource(ctx);
        adatasource.open();
        refreshtime = adatasource.getCachedAccountDataTime(account);
        if (refreshtime > 0) {
            displaydata(adatasource.getCachedAccountData(account), true);
            if (System.currentTimeMillis() - refreshtime > MAX_CACHE_AGE) {
                refresh();
            }
        } else {
            refresh();
        }
        adatasource.close();
    }
}

From source file:org.opendatakit.aggregate.odktables.DataManager.java

/**
 * Retrieve a row from the table./*from   w ww .  ja  va  2s  . c  o m*/
 *
 * @param rowId
 *          the id of the row
 * @return the row
 * @throws ODKEntityNotFoundException
 *           if the row with the given id does not exist
 * @throws ODKDatastoreException
 * @throws PermissionDeniedException
 * @throws InconsistentStateException
 * @throws ODKTaskLockException
 * @throws BadColumnNameException
 */
public Row getRow(String rowId) throws ODKEntityNotFoundException, ODKDatastoreException,
        PermissionDeniedException, InconsistentStateException, ODKTaskLockException, BadColumnNameException {
    try {
        Validate.notEmpty(rowId);

        userPermissions.checkPermission(appId, tableId, TablePermission.READ_ROW);

        List<DbColumnDefinitionsEntity> columns = null;
        Entity entity = null;
        LockTemplate propsLock = new LockTemplate(tableId, ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES,
                cc);
        try {
            propsLock.acquire();

            DbTableEntryEntity entry = DbTableEntry.getTableIdEntry(tableId, cc);
            String schemaETag = entry.getSchemaETag();

            if (schemaETag == null) {
                throw new InconsistentStateException("Schema for table " + tableId + " is not yet defined.");
            }

            DbTableDefinitionsEntity tableDefn = DbTableDefinitions.getDefinition(tableId, schemaETag, cc);
            columns = DbColumnDefinitions.query(tableId, schemaETag, cc);

            DbTable table = DbTable.getRelation(tableDefn, columns, cc);
            DbLogTable logTable = DbLogTable.getRelation(tableDefn, columns, cc);

            revertPendingChanges(entry, columns, table, logTable);

            entity = table.getEntity(rowId, cc);

        } finally {
            propsLock.release();
        }

        if (columns == null) {
            throw new InconsistentStateException("Unable to retrieve rows for table " + tableId + ".");
        }

        Row row = converter.toRow(entity, columns);
        if (userPermissions.hasPermission(appId, tableId, TablePermission.UNFILTERED_READ)) {
            return row;
        } else if (userPermissions.hasFilterScope(appId, tableId, TablePermission.READ_ROW, row.getRowId(),
                row.getFilterScope())) {
            return row;
        }
        throw new PermissionDeniedException(String.format("Denied table %s row %s access to user %s", tableId,
                rowId, userPermissions.getOdkTablesUserId()));

    } catch (NullPointerException e) {
        e.printStackTrace();
        throw e;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw e;
    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKEntityPersistException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKEntityNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKTaskLockException e) {
        e.printStackTrace();
        throw e;
    } catch (BadColumnNameException e) {
        e.printStackTrace();
        throw e;
    } catch (PermissionDeniedException e) {
        e.printStackTrace();
        throw e;
    } catch (InconsistentStateException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.csp.everyaware.offline.Map.java

/****************** OTTIENE RIFERIMENTO AI BOTTONI *********************************/

public void getButtonRefs() {
    mZoomControls = (LinearLayout) findViewById(R.id.zoomLinearLayout);
    mZoomControls.setVisibility(View.GONE);

    mTrackLengthBtn = (Button) findViewById(R.id.trackLengthBtn);
    mFollowCamBtn = (Button) findViewById(R.id.followCameraBtn);
    mZoomOutBtn = (Button) findViewById(R.id.zoomOutBtn);
    mZoomInBtn = (Button) findViewById(R.id.zoomInBtn);
    mInsertAnnBtn = (Button) findViewById(R.id.insertAnnBtn);
    mShareBtn = (Button) findViewById(R.id.shareBtn);

    mTrackLengthBtn.setVisibility(View.GONE);
    mInsertAnnBtn.setVisibility(View.GONE);

    mZoomOutBtn.setOnClickListener(new OnClickListener() {
        @Override//ww w .  j a  v  a  2  s .  c om
        public void onClick(View arg0) {
            // Zoom out
            try {
                mGoogleMap.moveCamera(CameraUpdateFactory.zoomBy(-1f));
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            //read and save actual zoom level
            mZoom = mGoogleMap.getCameraPosition().zoom;
        }
    });

    mZoomInBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // Zoom in
            try {
                mGoogleMap.moveCamera(CameraUpdateFactory.zoomBy(1f));
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            //read and save actual zoom level
            mZoom = mGoogleMap.getCameraPosition().zoom;
        }
    });

    mShareBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            mFacebookManager = FacebookManager.getInstance(Map.this, mFacebookHandler);
            mTwitterManager = TwitterManager.getInstance(Map.this);

            final Dialog dialog = new Dialog(Map.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.share_dialog);
            //dialog.setTitle("Activate login on...");

            getShareButtonsRef(dialog);

            dialog.show();
        }
    });

    mFollowCamBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            //mCameraTrackOn = !mCameraTrackOn;
            setCameraTracking();

            if (mCameraTrackOn) {
                try {
                    if (Utils.lastPhoneLocation != null)
                        mGoogleMap.animateCamera(
                                CameraUpdateFactory.newLatLng(new LatLng(Utils.lastPhoneLocation.getLatitude(),
                                        Utils.lastPhoneLocation.getLongitude())));
                    else if (Utils.lastNetworkLocation != null)
                        mGoogleMap.animateCamera(CameraUpdateFactory
                                .newLatLng(new LatLng(Utils.lastNetworkLocation.getLatitude(),
                                        Utils.lastNetworkLocation.getLongitude())));
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    mShareBtn.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View arg0) {
            Toast toast = Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.share_btn_text), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 250); //250 from top on a 480x800 screen
            toast.show();
            return false;
        }
    });

    //status icons references
    mGpsStatus = (ImageView) findViewById(R.id.gpsStatusIv);
    mInterUplStatus = (ImageView) findViewById(R.id.interUplStatusIv);

    //gps status icon initialization
    mGpsStatus.setBackgroundResource(R.drawable.gps_off);

    //read network type index on which upload data is allowed: 0 - only wifi; 1 - both wifi and mobile
    int networkTypeIndex = Utils.getUploadNetworkTypeIndex(getApplicationContext());

    //1 - is internet connection available? 
    boolean[] connectivity = Utils.haveNetworkConnection(getApplicationContext());

    //if user wants to upload only on wifi networks, connectivity[0] (network connectivity) must be true
    if (networkTypeIndex == 0) {
        if (connectivity[0])
            mConnectivityOn = true;
        else
            mConnectivityOn = false;
    } else //if user wants to upload both on wifi/mobile networks
        mConnectivityOn = connectivity[0] || connectivity[1];

    //network status icon initialization
    if (mConnectivityOn) {
        mInterUplStatus.setBackgroundResource(R.drawable.internet_on);
        Utils.uploadOn = Constants.INTERNET_ON_INT;
    } else {
        mInterUplStatus.setBackgroundResource(R.drawable.internet_off);
        Utils.uploadOn = Constants.INTERNET_OFF_INT;
    }

    //button to get from server black carbon levels around user
    mGetBcLevelsBtn = (Button) findViewById(R.id.getBcLevelsBtn);
    mGetBcLevelsBtn.setVisibility(View.VISIBLE);
    mGetBcLevelsBtn.setOnClickListener(mGetBcLevelsOnClickListener);

    //bcLayout.addView(mGetBcLevelsBtn);
    mSpectrum = (LinearLayout) findViewById(R.id.spectrumLinearLayout);
    mSpectrum.setVisibility(View.VISIBLE);
}

From source file:ai.api.sample.AIDialogSampleActivity.java

private void searchMobileAmazon(String mobile_brand, String mobile_browsenode, String mobile_maxprice,
        String mobile_minprice, String mobile_os) {

    // Get shared client
    AWSECommerceServicePortType_SOAPClient client = AWSECommerceClient.getSharedClient();
    client.setDebug(true);// ww w.  j  ava2 s .co  m

    // Build request
    ItemSearch request = new ItemSearch();
    request.associateTag = "teg"; // seems any tag is ok
    request.shared = new ItemSearchRequest();
    request.shared.searchIndex = "Electronics";

    request.shared.responseGroup = new ArrayList<String>();
    request.shared.responseGroup.add("Images");
    request.shared.responseGroup.add("Small");

    ItemSearchRequest itemSearchRequest = new ItemSearchRequest();

    itemSearchRequest.keywords = mobile_os;

    itemSearchRequest.browseNode = mobile_browsenode; //unlcoked or carrier

    //        if(!mobile_carrier.equalsIgnoreCase("none"))
    //        {
    //            itemSearchRequest.keywords = mobile_os + " " + mobile_carrier;
    //        }
    //        else{
    //            itemSearchRequest.keywords = mobile_os + " unlocked";
    //        }

    itemSearchRequest.sort = "salesrank";

    itemSearchRequest.brand = mobile_brand;
    if (mobile_maxprice.contains("above"))
        mobile_maxprice = "100000";
    if (mobile_minprice.contains("below"))
        mobile_minprice = "0";

    if (Integer.parseInt(mobile_maxprice) < Integer.parseInt(mobile_minprice)) {
        mobile_maxprice = "1000000";
    }
    BigInteger min = new BigInteger(mobile_minprice + "00");
    BigInteger max = new BigInteger(mobile_maxprice + "00");
    itemSearchRequest.minimumPrice = min;

    itemSearchRequest.maximumPrice = max;

    request.request = new ArrayList<ItemSearchRequest>();
    request.request.add(itemSearchRequest);

    // authenticate the request
    // http://docs.aws.amazon.com/AWSECommerceService/latest/DG/NotUsingWSSecurity.html
    AWSECommerceClient.authenticateRequest("ItemSearch");
    // Make API call and register callbacks
    client.itemSearch(request, new SOAPServiceCallback<ItemSearchResponse>() {

        @Override
        public void onSuccess(ItemSearchResponse responseObject) {
            // success handling logic
            if (responseObject.items != null && responseObject.items.size() > 0) {

                Items items = responseObject.items.get(0);

                /*for(Items i : responseObject.items)
                {
                if(i!=null) {
                    for (Item ii : i.item) {
                        Log.i("Checking Items", ii.detailPageURL);
                    }
                }
                }*/

                if (items.item != null && items.item.size() > 0) {
                    Item item = items.item.get(0);
                    Toast.makeText(AIDialogSampleActivity.this, item.itemAttributes.title, Toast.LENGTH_LONG)
                            .show();

                    /*
                    Log.i("Searchresult",items.item.get(1).itemAttributes.title);
                    Log.i("Searchresult",items.item.get(2).itemAttributes.title);
                    */
                    Log.i("SearchresultExtended", items.item.get(0).itemAttributes.title);

                    if (items.item.get(0).itemAttributes.audienceRating != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.audienceRating);
                    else
                        Log.i("SearchresultExtended", "rating is null");

                    if (items.item.get(0).itemAttributes.manufacturer != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.manufacturer);
                    else
                        Log.i("SearchresultExtended", "manufacturer is null");

                    if (items.item.get(0).itemAttributes.listPrice != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.listPrice.toString());

                    TTS.speakadd("I think the best product is ");
                    TTS.speakadd(item.itemAttributes.title);
                    TTS.speakadd("Dont worry! I have added links for top 3 product to your Speakbuy app");
                    TTS.speakadd("Do you want to continue using speakbuy?");
                    //code to save links
                    int x = 0;

                    try {

                        for (Items i : responseObject.items) {
                            for (Item ii : i.item) {

                                Log.i("Checking Items", ii.detailPageURL);
                                if (x < 3) {
                                    //ReminderActivity.itemsAdapter.add(ii.detailPageURL);
                                    itemsToAdd.add(ii.detailPageURL);
                                }
                                x++;
                            }
                        }
                    } catch (NullPointerException e) {

                        Toast.makeText(AIDialogSampleActivity.this, "Some error Occured", Toast.LENGTH_LONG)
                                .show();
                    }

                    File filesDir = getFilesDir();
                    File todoFile = new File(filesDir, "todo.txt");
                    try {

                        FileUtils.writeLines(todoFile, itemsToAdd, true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //TTS.speakadd(items.item.get(1).itemAttributes.title);
                    //TTS.speakadd("Next item is :");
                    //TTS.speakadd(items.item.get(2).itemAttributes.title);

                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    TTS.speakadd("Sorry, I found no phones in that price range");
                    TTS.speakadd("Do you want to continue using speakbuy?");
                }

            } else {
                if (responseObject.operationRequest != null && responseObject.operationRequest.errors != null) {
                    Errors errors = responseObject.operationRequest.errors;
                    if (errors.error != null && errors.error.size() > 0) {
                        com.amazon.webservices.awsecommerceservice._2011_08_01.errors.Error error = errors.error
                                .get(0);
                        Toast.makeText(AIDialogSampleActivity.this, error.message, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                }
            }

        }

        @Override
        public void onFailure(Throwable error, String errorMessage) { // http or parsing error
            Toast.makeText(AIDialogSampleActivity.this, errorMessage, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSOAPFault(Object soapFault) { // soap fault
            com.leansoft.nano.soap11.Fault fault = (com.leansoft.nano.soap11.Fault) soapFault;
            Toast.makeText(AIDialogSampleActivity.this, fault.faultstring, Toast.LENGTH_LONG).show();
        }

    });

}

From source file:ai.api.sample.AIDialogSampleActivity.java

private void serachLaptopAmazon(String keyword, String manufacturer, String mini, String maxi) {

    // Get shared client
    AWSECommerceServicePortType_SOAPClient client = AWSECommerceClient.getSharedClient();
    client.setDebug(true);//from  ww  w . j  av a  2s. c  o m

    // Build request
    ItemSearch request = new ItemSearch();
    request.associateTag = "teg"; // seems any tag is ok
    request.shared = new ItemSearchRequest();
    request.shared.searchIndex = "Electronics";

    request.shared.responseGroup = new ArrayList<String>();
    request.shared.responseGroup.add("Images");
    request.shared.responseGroup.add("Small");

    ItemSearchRequest itemSearchRequest = new ItemSearchRequest();

    if (keyword.charAt(0) == 'g' || keyword.charAt(0) == 'G' || keyword.equalsIgnoreCase("gaining")
            || keyword.equalsIgnoreCase("giving") || keyword.equalsIgnoreCase("gimme")
            || keyword.equalsIgnoreCase("jimme") || keyword.equalsIgnoreCase("MN")) {
        keyword = "gaming";
    }

    itemSearchRequest.keywords = keyword;

    itemSearchRequest.browseNode = "13896615011";
    itemSearchRequest.browseNode = "565108";

    itemSearchRequest.sort = "salesrank";

    if (manufacturer.equalsIgnoreCase("HBO") || manufacturer.equalsIgnoreCase("FB")
            || manufacturer.equalsIgnoreCase("HD") || manufacturer.equalsIgnoreCase("XP")
            || manufacturer.length() == 2 || manufacturer.equalsIgnoreCase("xb")) {
        Log.i("changing ", manufacturer);
        manufacturer = "HP";
    }

    if (manufacturer.equalsIgnoreCase("adelle") || manufacturer.equalsIgnoreCase("adele")
            || manufacturer.equalsIgnoreCase("Bell") || manufacturer.equalsIgnoreCase("Den")) {
        manufacturer = "Dell";
    }

    itemSearchRequest.manufacturer = manufacturer;
    BigInteger min = new BigInteger(mini + "00");
    BigInteger max = new BigInteger(maxi + "00");

    itemSearchRequest.minimumPrice = min;

    itemSearchRequest.maximumPrice = max;

    request.request = new ArrayList<ItemSearchRequest>();
    request.request.add(itemSearchRequest);

    // authenticate the request
    // http://docs.aws.amazon.com/AWSECommerceService/latest/DG/NotUsingWSSecurity.html
    AWSECommerceClient.authenticateRequest("ItemSearch");
    // Make API call and register callbacks
    client.itemSearch(request, new SOAPServiceCallback<ItemSearchResponse>() {

        @Override
        public void onSuccess(ItemSearchResponse responseObject) {
            // success handling logic
            if (responseObject.items != null && responseObject.items.size() > 0) {

                Items items = responseObject.items.get(0);

                /*for(Items i : responseObject.items)
                {
                if(i!=null) {
                    for (Item ii : i.item) {
                        Log.i("Checking Items", ii.detailPageURL);
                    }
                }
                }*/

                if (items.item != null && items.item.size() > 0) {
                    Item item = items.item.get(0);
                    Toast.makeText(AIDialogSampleActivity.this, item.itemAttributes.title, Toast.LENGTH_LONG)
                            .show();

                    Log.i("Searchresult", items.item.get(1).itemAttributes.title);
                    Log.i("Searchresult", items.item.get(2).itemAttributes.title);

                    Log.i("SearchresultExtended", items.item.get(0).itemAttributes.title);

                    if (items.item.get(0).itemAttributes.audienceRating != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.audienceRating);
                    else
                        Log.i("SearchresultExtended", "rating is null");

                    if (items.item.get(0).itemAttributes.manufacturer != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.manufacturer);
                    else
                        Log.i("SearchresultExtended", "manufacturer is null");

                    if (items.item.get(0).itemAttributes.listPrice != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.listPrice.toString());

                    TTS.speakadd("I think the best product is ");
                    TTS.speakadd(item.itemAttributes.title);
                    TTS.speakadd("Dont worry! I have added links for top 3 product to your Speakbuy app");
                    TTS.speakadd("Do you want to continue using speakbuy?");

                    //code to save links
                    int x = 0;

                    try {

                        for (Items i : responseObject.items) {
                            for (Item ii : i.item) {

                                Log.i("Checking Items", ii.detailPageURL);
                                if (x < 3) {
                                    //ReminderActivity.itemsAdapter.add(ii.detailPageURL);
                                    itemsToAdd.add(ii.detailPageURL);
                                }
                                x++;
                            }
                        }
                    } catch (NullPointerException e) {

                        Toast.makeText(AIDialogSampleActivity.this, "Some error Occured", Toast.LENGTH_LONG)
                                .show();
                    }

                    File filesDir = getFilesDir();
                    File todoFile = new File(filesDir, "todo.txt");
                    try {

                        FileUtils.writeLines(todoFile, itemsToAdd, true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //TTS.speakadd(items.item.get(1).itemAttributes.title);
                    //TTS.speakadd("Next item is :");
                    //TTS.speakadd(items.item.get(2).itemAttributes.title);

                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    TTS.speakadd("Sorry, I found no products in that price range");
                    TTS.speakadd("Do you want to continue using speakbuy?");
                }

            } else {
                if (responseObject.operationRequest != null && responseObject.operationRequest.errors != null) {
                    Errors errors = responseObject.operationRequest.errors;
                    if (errors.error != null && errors.error.size() > 0) {
                        com.amazon.webservices.awsecommerceservice._2011_08_01.errors.Error error = errors.error
                                .get(0);
                        Toast.makeText(AIDialogSampleActivity.this, error.message, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                }
            }

        }

        @Override
        public void onFailure(Throwable error, String errorMessage) { // http or parsing error
            //Toast.makeText(AmazonSearchActivity.this, errorMessage, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSOAPFault(Object soapFault) { // soap fault
            com.leansoft.nano.soap11.Fault fault = (com.leansoft.nano.soap11.Fault) soapFault;
            //Toast.makeText(AmazonSearchActivity.this, fault.faultstring, Toast.LENGTH_LONG).show();
        }

    });

}

From source file:ai.api.sample.AIDialogSampleActivity.java

private void searchTabletAmazon(String tablet_brand, String tablet_browsenode, String tablet_maxprice,
        String tablet_minprice, String tablet_os, String tablet_model) {

    // Get shared client
    AWSECommerceServicePortType_SOAPClient client = AWSECommerceClient.getSharedClient();
    client.setDebug(true);// w  ww . j  a va 2 s.  c  o  m

    // Build request
    ItemSearch request = new ItemSearch();
    request.associateTag = "teg"; // seems any tag is ok
    request.shared = new ItemSearchRequest();
    request.shared.searchIndex = "Electronics";

    request.shared.responseGroup = new ArrayList<String>();
    request.shared.responseGroup.add("Images");
    request.shared.responseGroup.add("Small");

    ItemSearchRequest itemSearchRequest = new ItemSearchRequest();

    if (tablet_model.equals("null") == false) {
        itemSearchRequest.keywords = tablet_model;
        itemSearchRequest.brand = "apple";
    } else {
        itemSearchRequest.keywords = tablet_os;
        itemSearchRequest.brand = tablet_brand;
    }

    itemSearchRequest.browseNode = tablet_browsenode; //unlcoked or carrier

    //        if(!mobile_carrier.equalsIgnoreCase("none"))
    //        {
    //            itemSearchRequest.keywords = mobile_os + " " + mobile_carrier;
    //        }
    //        else{
    //            itemSearchRequest.keywords = mobile_os + " unlocked";
    //        }

    itemSearchRequest.sort = "salesrank";

    if (tablet_maxprice.contains("above"))
        tablet_maxprice = "100000";
    if (tablet_minprice.contains("below"))
        tablet_minprice = "0";

    if (Integer.parseInt(tablet_maxprice) < Integer.parseInt(tablet_minprice)) {
        tablet_maxprice = "1000000";
    }

    BigInteger min = new BigInteger(tablet_minprice + "00");
    BigInteger max = new BigInteger(tablet_maxprice + "00");
    itemSearchRequest.minimumPrice = min;

    itemSearchRequest.maximumPrice = max;

    request.request = new ArrayList<ItemSearchRequest>();
    request.request.add(itemSearchRequest);

    // authenticate the request
    // http://docs.aws.amazon.com/AWSECommerceService/latest/DG/NotUsingWSSecurity.html
    AWSECommerceClient.authenticateRequest("ItemSearch");
    // Make API call and register callbacks
    client.itemSearch(request, new SOAPServiceCallback<ItemSearchResponse>() {

        @Override
        public void onSuccess(ItemSearchResponse responseObject) {
            // success handling logic
            if (responseObject.items != null && responseObject.items.size() > 0) {

                Items items = responseObject.items.get(0);

                /*for(Items i : responseObject.items)
                {
                if(i!=null) {
                    for (Item ii : i.item) {
                        Log.i("Checking Items", ii.detailPageURL);
                    }
                }
                }*/

                if (items.item != null && items.item.size() > 0) {
                    Item item = items.item.get(0);
                    Toast.makeText(AIDialogSampleActivity.this, item.itemAttributes.title, Toast.LENGTH_LONG)
                            .show();

                    Log.i("Searchresult", items.item.get(1).itemAttributes.title);
                    Log.i("Searchresult", items.item.get(2).itemAttributes.title);

                    Log.i("SearchresultExtended", items.item.get(0).itemAttributes.title);

                    if (items.item.get(0).itemAttributes.audienceRating != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.audienceRating);
                    else
                        Log.i("SearchresultExtended", "rating is null");

                    if (items.item.get(0).itemAttributes.manufacturer != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.manufacturer);
                    else
                        Log.i("SearchresultExtended", "manufacturer is null");

                    if (items.item.get(0).itemAttributes.listPrice != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.listPrice.toString());

                    TTS.speakadd("I think the best product is " + item.itemAttributes.title
                            + ". Dont worry! I have added links for top 3 product to your Speakbuy app Do you want to do another search?, say Yes or No");
                    /*TTS.speakadd(item.itemAttributes.title);
                    TTS.speakadd("Dont worry! I have added links for top 3 product to your Speakbuy app");
                    TTS.speakadd("");*/
                    //code to save links
                    int x = 0;

                    try {

                        for (Items i : responseObject.items) {
                            for (Item ii : i.item) {

                                Log.i("Checking Items", ii.detailPageURL);
                                if (x < 3) {
                                    //ReminderActivity.itemsAdapter.add(ii.detailPageURL);
                                    itemsToAdd.add(ii.detailPageURL);
                                }
                                x++;
                            }
                        }
                    } catch (NullPointerException e) {

                        Toast.makeText(AIDialogSampleActivity.this, "Some error Occured", Toast.LENGTH_LONG)
                                .show();
                    }

                    File filesDir = getFilesDir();
                    File todoFile = new File(filesDir, "todo.txt");
                    try {

                        FileUtils.writeLines(todoFile, itemsToAdd, true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //TTS.speakadd(items.item.get(1).itemAttributes.title);
                    //TTS.speakadd("Next item is :");
                    //TTS.speakadd(items.item.get(2).itemAttributes.title);

                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    TTS.speakadd("Sorry, I found no phones in that price range");
                    TTS.speakadd("Do you wanna use SpeakBuy again?");
                }

            } else {
                if (responseObject.operationRequest != null && responseObject.operationRequest.errors != null) {
                    Errors errors = responseObject.operationRequest.errors;
                    if (errors.error != null && errors.error.size() > 0) {
                        com.amazon.webservices.awsecommerceservice._2011_08_01.errors.Error error = errors.error
                                .get(0);
                        Toast.makeText(AIDialogSampleActivity.this, error.message, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                }
            }

        }

        @Override
        public void onFailure(Throwable error, String errorMessage) { // http or parsing error
            Toast.makeText(AIDialogSampleActivity.this, errorMessage, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSOAPFault(Object soapFault) { // soap fault
            com.leansoft.nano.soap11.Fault fault = (com.leansoft.nano.soap11.Fault) soapFault;
            Toast.makeText(AIDialogSampleActivity.this, fault.faultstring, Toast.LENGTH_LONG).show();
        }

    });

}