Thursday 29 November 2018

Android Important Topic List

Convert the video URL to image.
String[] split = mThumImage.split("=");
String breakString = split[1];
String mURl="http://img.youtube.com/vi/"+breakString+"/0.jpg";
Picasso.with(context).load(mURl).into(holder.imageViewIcon);
------------------End------------------

Half Circle Create.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item
    android:left="-150dp"
    android:right="-150dp"
    android:top="-200dp">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">
        <solid android:color="#C72C2F" />
    </shape>
</item>
</layer-list>

---------------------------------
Define AdView adview; 
/****
create code
/*****
AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                adView.setVisibility(View.VISIBLE);
            }
        });

Library:- compile 'com.google.android.gms:play-services-auth:11.0.0'



/******/
xml layout
/******/
 
 <com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ads:adSize="SMART_BANNER"
            android:layout_centerHorizontal="true"
            android:layout_above="@id/bottom_bar"
            android:layout_gravity="center"
            android:visibility="gone"
            ads:adUnitId="your ca-app-pub">
        </com.google.android.gms.ads.AdView>

----------------------------------------------------

//ToolBar back press

@Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
            Intent cartIntent = new Intent(ReferralListingActivity.this, DashBoardActivity.class);
            startActivity(cartIntent);
            finish();
        }
        return super.onOptionsItemSelected(menuItem);
    }
//End

//ToolBar Setting
 setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        Drawable upArrow = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_back);
        upArrow.setColorFilter(ContextCompat.getColor(ReferralListingActivity.this, R.color.black), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(upArrow);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolTitle.setText("Referral History");
//End

----------------------------------

Run Time Permission

AppPermissions mRuntimePermission;
    private static final String[] ALL_PERMISSIONS = {
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_SMS
    };


  mRuntimePermission = new AppPermissions(SplashActivity.this);
        mRuntimePermission = new AppPermissions(SplashActivity.this);
        if (Build.VERSION.SDK_INT >= 23) {
            if (mRuntimePermission.hasPermission(ALL_PERMISSIONS)) {
                //exitSplash();
                updateAppCode();
            } else {
                mRuntimePermission.requestPermission(SplashActivity.this, ALL_PERMISSIONS, ALL_REQUEST_CODE);
            }
        } else {
            //exitSplash();
            updateAppCode();
        }



 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case ALL_REQUEST_CODE:
                List<Integer> permissionResults = new ArrayList<>();
                for (int grantResult : grantResults) {
                    permissionResults.add(grantResult);
                }
                if (permissionResults.contains(PackageManager.PERMISSION_DENIED)) {
                    mRuntimePermission.requestPermission(SplashActivity.this, ALL_PERMISSIONS, ALL_REQUEST_CODE);
                    Toast.makeText(SplashActivity.this, "All permissions are necessary, please select allow button from permission dialog.", Toast.LENGTH_SHORT).show();
                } else {
                    exitSplash();
                }
                break;
        }
    }

Library:- compile 'com.mukesh:permissions:1.0.4'
---------------------------------------------
Retrofit

public interface Api {

static final String URL = "https://pixelsoftwares.com/";
//Post the user information on server
    @Multipart
    @POST("/connectadlinks/api/user/updateprofile")
    Call<ProfileInformation> profileInformation(@Part("userId") RequestBody userId, @Part("name") RequestBody mName, @Part("username") RequestBody mUserName, @Part("email") RequestBody mEmail, @Part("mobile") RequestBody mMobile, @Part("countrycode") RequestBody mCountryCode, @Part("nationid") RequestBody mNationalID, @Part MultipartBody.Part profileImage);

}

public class ProfileInformation {

    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("image")
    @Expose
    private String image;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

}



 //Post the user Information
    public void postImage(String path) {
        //progressBar.setVisibility(View.VISIBLE);
        showDialog(true);
        //profileImageView.setVisibility(View.GONE);
        final String mUserName = userNameEditText.getText().toString();
        final String mName = nameEditText.getText().toString();
        final String mEmail = emailEditText.getText().toString();
        final String mMobile = phoneEditText.getText().toString();
        final String mNationalID = proofEditText.getText().toString();
        int compressionRatio = 2; //1 == originalImage, 2 = 50% compression, 4=25% compress
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream(imageFile));
        } catch (Throwable t) {
            Log.e("ERROR", "Error compressing file." + t.toString());
            t.printStackTrace();
        }
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), imageFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("identificationimage", imageFile.getName(), reqFile);
        RequestBody usertid = RequestBody.create(MediaType.parse("text/html"), Credentials.getLoginUserID(getActivity()));
        RequestBody name = RequestBody.create(MediaType.parse("text/html"), mName);
        RequestBody username = RequestBody.create(MediaType.parse("text/html"), mUserName);
        RequestBody email = RequestBody.create(MediaType.parse("text/html"), mEmail);
        RequestBody phone = RequestBody.create(MediaType.parse("text/html"), mMobile);
        RequestBody countryCode = RequestBody.create(MediaType.parse("text/html"), "91");
        RequestBody nationalId = RequestBody.create(MediaType.parse("text/html"), mNationalID);

        Api service = Retrofit().create(Api.class);
        Call<ProfileInformation> call = service.profileInformation(usertid, name, username, email, phone, countryCode, nationalId, body);
        call.enqueue(new Callback<ProfileInformation>() {
            @Override
            public void onResponse(Call<ProfileInformation> call, retrofit2.Response<ProfileInformation> response) {
                //progressBar.setVisibility(View.GONE);
                showDialog(false);
                // profileImageView.setVisibility(View.VISIBLE);
                Log.d(">>onsuccess", ">>onsuccess" + response.body().getMessage());
                Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_LONG).show();
                //fetchUserInfo();
            }

            @Override
            public void onFailure(Call<ProfileInformation> call, Throwable t) {
                // progressBar.setVisibility(View.VISIBLE);
                showDialog(false);
                Log.d(">>onFailure", ">>onFailure" + t.getMessage());
            }
        });
    }


public Retrofit Retrofit() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(60 * 2000, TimeUnit.MILLISECONDS).addInterceptor(logging)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.URL)
                .addConverterFactory(GsonConverterFactory.create()).client(okHttpClient)
                .build();
        return retrofit;
    }

Library:-
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
----------------------------------------------------------------------------
Profile Image Upload

public class ProfileFragment extends Fragment {
    View convertView;
    //EditText
    EditText nameEditText, userNameEditText, phoneEditText, emailEditText, proofEditText;
    //TextView
    TextView confirmTextView;
    LinearLayout uploadTextView;
    //ImageView
    ImageView statusImageView, pendingImageView;
    ProgressDialog dialog;
    Button submitButton;
    ImageView profileImageView;
    int CAPTURE_IMAGE = 1, CHOOSE_GALLERY = 2;
    ProgressBar progressBar;
    private static final String[] ALL_PERMISSIONS = {
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private static final int ALL_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST = 108;
    private String mCurrentPhotoPath = "";
    AppPermissions mRuntimePermission;
    File imageFile;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        convertView = inflater.inflate(R.layout.fragment_edit_profile, container, false);

        //Getting the widget id here
        init(convertView);
        //Using the clikc listenr here
        listener();

        fetchUserInfo();
        //Credentials.getLoginUserID(getActivity());
        //End
        return convertView;
    }

    private void init(View view) {
        //EditText
        nameEditText = (EditText) view.findViewById(R.id.etName);
        userNameEditText = (EditText) view.findViewById(R.id.etUser);
        emailEditText = (EditText) view.findViewById(R.id.etEmail);
        phoneEditText = (EditText) view.findViewById(R.id.etPhone);
        proofEditText = (EditText) view.findViewById(R.id.etNationalId);
        //TextView
        confirmTextView = (TextView) view.findViewById(R.id.txtStatus);
        uploadTextView = (LinearLayout) view.findViewById(R.id.txtUpload);
        //ImageView
        statusImageView = (ImageView) view.findViewById(R.id.imgStatus);
        pendingImageView = (ImageView) view.findViewById(R.id.imgPending);
        //Button
        submitButton = (Button) view.findViewById(R.id.btnSubmit);
        //ImageView
        profileImageView = (ImageView) view.findViewById(R.id.imgUserProfile);

        //Disable Here
        nameEditText.setEnabled(false);
        userNameEditText.setEnabled(false);
        emailEditText.setEnabled(false);
        phoneEditText.setEnabled(false);
    }

    private void listener() {
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (nameEditText.length() == 0) {
                    Toast.makeText(getActivity(), "Please fill all field!.", Toast.LENGTH_SHORT).show();
                } else if (userNameEditText.length() == 0) {
                    Toast.makeText(getActivity(), "Please fill all field!.", Toast.LENGTH_SHORT).show();
                } else if (emailEditText.length() == 0) {
                    Toast.makeText(getActivity(), "Please fill all field!.", Toast.LENGTH_SHORT).show();
                } else if (phoneEditText.length() == 0) {
                    Toast.makeText(getActivity(), "Please fill all field!.", Toast.LENGTH_SHORT).show();
                } else if (proofEditText.length() == 0) {
                    Toast.makeText(getActivity(), "Please fill all field!.", Toast.LENGTH_SHORT).show();
                } else {
                    //postData();
                    if (imageFile == null) {
                        Toast.makeText(getActivity(), "Please provide Passport/National ID upload image", Toast.LENGTH_SHORT).show();

                    } else {
                        postImage(imageFile.getPath());
                    }

                }
            }
        });

        mRuntimePermission = new AppPermissions(getActivity());
        profileImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRuntimePermission = new AppPermissions(getActivity());
                if (Build.VERSION.SDK_INT >= 23) {
                    if (mRuntimePermission.hasPermission(ALL_PERMISSIONS)) {
                        clickImage();
                    } else {
                        mRuntimePermission.requestPermission(getActivity(), ALL_PERMISSIONS, ALL_REQUEST_CODE);
                    }
                } else {
                    clickImage();
                }
            }
        });
    }

    private void clickImage() {
        final CharSequence[] items = {"Take Photo Camera", "Take Photo Gallery"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo Camera")) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                        File photoFile;
                        photoFile = createImageFile();
                        if (photoFile != null) {
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            getActivity().startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        } else {
                            mCurrentPhotoPath = "";
                            getActivity().startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        }
                    }
                } else if (items[item].equals("Take Photo Gallery")) {
                    chooseGallery();
                }
            }
        });
        builder.show();
    }

    public void chooseGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        getActivity().startActivityForResult(galleryIntent, CHOOSE_GALLERY);
    }

    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        imageFile = null;
        try {
            imageFile = File.createTempFile(
                    imageFileName,  // prefix
                    ".jpg",         // suffix
                    storageDir      // directory

            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (imageFile != null) {
            mCurrentPhotoPath = "file:" + imageFile.getAbsolutePath();
            Log.d("Ihdh", "Image" + mCurrentPhotoPath);
        }
        return imageFile;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case ALL_REQUEST_CODE:
                List<Integer> permissionResults = new ArrayList<>();
                for (int grantResult : grantResults) {
                    permissionResults.add(grantResult);
                }
                if (permissionResults.contains(PackageManager.PERMISSION_DENIED)) {
                    mRuntimePermission.requestPermission(getActivity(), ALL_PERMISSIONS, ALL_REQUEST_CODE);
                    Toast.makeText(getActivity(), "All permissions are necessary, please select allow button from permission dialog.", Toast.LENGTH_SHORT).show();
                } else {
                    clickImage();
                }
                break;
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        return dir != null && dir.delete();
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            try {
                profileImageView.setImageDrawable(null);
                uploadTextView.setVisibility(View.GONE);
                //postImage(mCurrentPhotoPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Log.i("CROP", "handleCrop: " + Crop.getOutput(result));
                profileImageView.setImageURI(Crop.getOutput(result));
                uploadTextView.setVisibility(View.GONE);
                //postImage(mCurrentPhotoPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            try {
                Toast.makeText(getActivity(), Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void beginCrop(Uri source) {
        try {
            File file = getActivity().getCacheDir();
            deleteDir(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
        Crop.of(source, destination).asSquare().start(getActivity(), Crop.REQUEST_CROP);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_CANCELED) {
            if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
                beginCrop(data.getData());
            } else if (requestCode == Crop.REQUEST_CROP) {
                handleCrop(resultCode, data);
            } else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
                if (mCurrentPhotoPath == null || mCurrentPhotoPath.isEmpty()) {
                    beginCrop(data.getData());
                } else {
                    beginCrop(Uri.parse(mCurrentPhotoPath));
                }
            }
        }

        if (requestCode == CHOOSE_GALLERY && resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String imgDecodableString = cursor.getString(columnIndex);
            cursor.close();
            File imageFile = new File("" + imgDecodableString);
            this.imageFile = imageFile;
            Uri uri = Uri.fromFile(imageFile);
            Log.i("TAG", "path: " + imageFile.getAbsolutePath());
            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                profileImageView.setImageBitmap(bitmap);
                uploadTextView.setVisibility(View.GONE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            CropImage.activity(uri).setGuidelines(com.theartofdev.edmodo.cropper.CropImageView.Guidelines.ON).setAspectRatio(1, 1).start(getActivity());
        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                CropImage.ActivityResult result = CropImage.getActivityResult(data);
                if (resultCode == RESULT_OK) {
                    Uri resultUri = result.getUri();
                    imageFile = new File(resultUri.getPath());
                    //postImage(imageFile.getPath());
                } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    Exception error = result.getError();
                }
            }
        }
    }

    //Post the user Information
    public void postImage(String path) {
        //progressBar.setVisibility(View.VISIBLE);
        showDialog(true);
        //profileImageView.setVisibility(View.GONE);
        final String mUserName = userNameEditText.getText().toString();
        final String mName = nameEditText.getText().toString();
        final String mEmail = emailEditText.getText().toString();
        final String mMobile = phoneEditText.getText().toString();
        final String mNationalID = proofEditText.getText().toString();
        int compressionRatio = 2; //1 == originalImage, 2 = 50% compression, 4=25% compress
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream(imageFile));
        } catch (Throwable t) {
            Log.e("ERROR", "Error compressing file." + t.toString());
            t.printStackTrace();
        }
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), imageFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("identificationimage", imageFile.getName(), reqFile);
        RequestBody usertid = RequestBody.create(MediaType.parse("text/html"), Credentials.getLoginUserID(getActivity()));
        RequestBody name = RequestBody.create(MediaType.parse("text/html"), mName);
        RequestBody username = RequestBody.create(MediaType.parse("text/html"), mUserName);
        RequestBody email = RequestBody.create(MediaType.parse("text/html"), mEmail);
        RequestBody phone = RequestBody.create(MediaType.parse("text/html"), mMobile);
        RequestBody countryCode = RequestBody.create(MediaType.parse("text/html"), "91");
        RequestBody nationalId = RequestBody.create(MediaType.parse("text/html"), mNationalID);

        Api service = Retrofit().create(Api.class);
        Call<ProfileInformation> call = service.profileInformation(usertid, name, username, email, phone, countryCode, nationalId, body);
        call.enqueue(new Callback<ProfileInformation>() {
            @Override
            public void onResponse(Call<ProfileInformation> call, retrofit2.Response<ProfileInformation> response) {
                //progressBar.setVisibility(View.GONE);
                showDialog(false);
                // profileImageView.setVisibility(View.VISIBLE);
                Log.d(">>onsuccess", ">>onsuccess" + response.body().getMessage());
                Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_LONG).show();
                //fetchUserInfo();
            }

            @Override
            public void onFailure(Call<ProfileInformation> call, Throwable t) {
                // progressBar.setVisibility(View.VISIBLE);
                showDialog(false);
                Log.d(">>onFailure", ">>onFailure" + t.getMessage());
            }
        });
    }

   
public Retrofit Retrofit() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(60 * 2000, TimeUnit.MILLISECONDS).addInterceptor(logging)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.URL)
                .addConverterFactory(GsonConverterFactory.create()).client(okHttpClient)
                .build();
        return retrofit;
    }
} 
Menifest:-  <activity
            android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
            android:screenOrientation="portrait" />
        <activity android:name="com.soundcloud.android.crop.CropImageActivity" />
--------------------------------------------------------------------------------------------------
Get the Url in text

setLinks(messageTextView(TextView), mMessage(get message));

private void setLinks(TextView messageTextView, String mMessage) {
        String[] linkPatterns = {
                "([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])",
                "#[\\w]+", "@[\\w]+"};
        for (String str : linkPatterns) {
            Pattern pattern = Pattern.compile(str);
            Matcher matcher = pattern.matcher(messageTextView.getText());
            while (matcher.find()) {
                int x = matcher.start();
                int y = matcher.end();
                final android.text.SpannableString f = new android.text.SpannableString(messageTextView.getText());
                InternalURLSpan span = new InternalURLSpan();
                span.text = mMessage.substring(x, y);
                f.setSpan(span, x, y, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageTextView.setText(f);
                Log.i("TEXT::", "TEXT:>>>" + f);

            }
        }
        //messageTextView.setLinkTextColor(Color.BLUE);
        messageTextView.setLinksClickable(true);
        messageTextView.setMovementMethod(LinkMovementMethod.getInstance());
        //messageTextView.setFocusable(false);

    }

 class InternalURLSpan extends android.text.style.ClickableSpan {
        public String text;

        @Override
        public void onClick(View widget) {
            Log.i("FINAL TEXT::", "FINAL TEXT:>>>" + text);
            String mFinalValue = text.replace("\r\n", "");
            if (mFinalValue.equals("https://pixelsoftwares.com/connectadlinks/user-status/check")) {
                sendDataNotification();
            } else {
                Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mFinalValue));
                startActivity(myIntent);
            }
        }
--------------------------------------------------------------
EditText Field Enter Only one text

 otpOne.addTextChangedListener(new GenericTextWatcher(otpOne));
        otpTwo.addTextChangedListener(new GenericTextWatcher(otpTwo));
        otpThree.addTextChangedListener(new GenericTextWatcher(otpThree));
        otpFour.addTextChangedListener(new GenericTextWatcher(otpFour));

public class GenericTextWatcher implements TextWatcher {
        private View view;

        private GenericTextWatcher(View view) {
            this.view = view;
        }

        @Override
        public void afterTextChanged(Editable editable) {
            // TODO Auto-generated method stub
            String text = editable.toString();
            switch (view.getId()) {

                case R.id.otp_1:
                    if (text.length() == 1)
                        otpTwo.requestFocus();
                    break;
                case R.id.otp_2:
                    if (text.length() == 1)
                        otpThree.requestFocus();
                    break;
                case R.id.otp_3:
                    if (text.length() == 1)
                        otpFour.requestFocus();
                    break;
                case R.id.otp_4:
                    break;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub
        }
    }


///
-----------------------------------------------------------
Tab Select

Example select Left and Right

boolean isLeftSelect=false;
boolean isRightSelected=false;

if(isLeftSelect==false && isRightSelected==false){
                    Toast.makeText(RegisterActivity.this, "Please selected Left or Right", Toast.LENGTH_LONG).show();
                }

leftText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isLeftSelect=!isLeftSelect;
                leftText.setBackgroundResource(R.drawable.edtnewbg);
                leftText.setTextColor(Color.parseColor("#000000"));
                rightText.setTextColor(Color.parseColor("#ffffff"));
                rightText.setBackgroundColor(Color.parseColor("#5C5B6D"));
                rightText.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_box));
                vaLues = "2";

            }
        });
---------------------------------------------
Broadcast Receiver OTP

//ManiFest file 

<receiver android:name="com.blush.app.IncomingSms">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>



//Main Activity

public class IncomingSms extends BroadcastReceiver {

    // Get the object of SmsManager
    final SmsManager sms = SmsManager.getDefault();


    public void onReceive(Context context, Intent intent) {

        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody().split(":")[1];

                   /// message = message.substring(0, message.length()-1);
                     message = message.substring(0, message.length());
                    Log.d(">>SmsReceiver", "senderNum: " + senderNum + "; message: " + message);

                    Intent myIntent = new Intent("otp");
                    myIntent.putExtra("message",message);
                    LocalBroadcastManager.getInstance(context).sendBroadcast(myIntent);
                    // Show Alert

                } // end for loop
            } // bundle is null

        } catch (Exception e) {
            Log.d(">>SmsReceiver", "Exception smsReceiver" +e.getMessage());

        }
    }
}


//Use in OTP Activity

private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase("otp")) {
                final String message = intent.getStringExtra("message");
                Log.d(">>SmsReceiver", "otp is " + message);
                otpEditText.setText(message);
                if(otpEditText.getText().toString().length()>6) {
                    requestOTP();
                }
                //Do whatever you want with the code here
            }
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        Log.d(">>on resume unregister", "on resume unregister");
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    @Override
    public void onResume() {

        Log.d(">>on resume register", "on resume register");
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
        super.onResume();
    }
----------------------------------------------------

Refferal and auto fill

//Receiver....

public class InstallReferrerReceiver extends BroadcastReceiver {

    Prefs prefs;

    @Override
    public void onReceive(Context context, Intent intent) {
        K.Log.i("TAG", "registered ref");
        if (intent.getAction().equals("com.android.vending.INSTALL_REFERRER")) {

            prefs = new Prefs(context);

            String referrer = intent.getStringExtra("referrer");

            K.Log.i("TAG", "referrer: " + referrer);
            if (!referrer.contains("=") && !referrer.contains("&")) {
                prefs.setString(Prefs.REFERRAL_ID, referrer.replace("\"", ""));
            } else {
                prefs.setString(Prefs.REFERRAL_ID, "");
            }
            //Use the referrer
        }
    }
}

//END

//Get Data
 etReferralId.setText(prefs.getString(Prefs.REFERRAL_ID, ""));


//Share links
  Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                intent.setType("text/plain");
                String shareBodyText = "Take a look at this amazing app: https://play.google.com/store/apps/details?id=com.connectadlinks"+"&"+"referrer="+username;
                intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject/Title");
                intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
                startActivity(Intent.createChooser(intent, "Share with"));

-----------------------------------------------------------------------------

EditText Message Field
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="18dp"
    android:orientation="vertical"
  >

    <EditText
        android:id="@+id/contactmsgbox"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:gravity="left"
        android:hint="Enter Message"
        android:background="@drawable/et_square"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:textColor="#000000"
        android:textColorHint="#000000" />

</LinearLayout>
-----------------------------------------------
Minus and Plus Logic on cart

private static int _counter = 0

plusLinearLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                if (_counter >= 0 && _counter < 10) {
                    _counter = _counter + 1;
                    countTextView.setText("" + _counter);
                    String mQty = "" + _counter;
                    BasketAddAdapter.this.notifyDataSetChanged();
                    displayAlertDialog(mQty);
                }

            }


  minusLinearLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (_counter > 1 && _counter <= 10) {
                    _counter = _counter - 1;
                    countTextView.setText("" + _counter);
                    String mQty = "" + _counter;
                    //addItem(mQty,mID,mOrderId);
                    BasketAddAdapter.this.notifyDataSetChanged();
                    display(mQty);


                }
            }
--------------------------------------------
RawData

 private void postExamData(JSONObject finalObj) {
        showDialog(true);
        String URL = "";
        RequestQueue queue = Volley.newRequestQueue(this);

        Log.i(">", "studentsObj>>>: " + finalObj);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, finalObj, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject object) {
                Log.d("RESPONSE", object.toString());
                showDialog(false);
                submitPopMessage(object.toString());
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("RESPONSE", "That didn't work!");
                showDialog(false);
            }

        });
        queue.add(request);
        request.setRetryPolicy(new DefaultRetryPolicy(500000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    }

---------------------------------

Retrofit

public interface Api {

    public static final String URL = " http://www.bloodstock.co.in/";

    @POST("/api/UserRegistration")
    @FormUrlEncoded
    Call<UploadResponse> requestRegister(@Field("Name") String name,
                                         @Field("Email") String email,
                                         @Field("PhoneNumber") String phoneNumber,
                                         @Field("BloodGroup") String bloodGroup,
                                         @Field("DistrictId") String district,
                                         @Field("StateId") String state,
                                         @Field("CityId") String city,
                                         @Field("Occupation") String occuption,
                                         @Field("Address") String address);}

Create response call:::

public void registerBloodUserData() {
    final String mUserName = userNameEditText.getText().toString();
    final String mUserEmail = emailEditText.getText().toString();
    final String mPhone = phoneEditText.getText().toString();
    final String mAddress = addressEditText.getText().toString();
    final String mOccuption = occuptionEditText.getText().toString();
    showDialog(true);

    Api service = Retrofit().create(Api.class);
    Call<UploadResponse> call = service.requestRegister(mUserName, mUserEmail,mPhone,"B+ve","4","3","11",mAddress,mOccuption);
    call.enqueue(new Callback<UploadResponse>() {
        @Override
        public void onResponse(Call<UploadResponse> call, retrofit2.Response<UploadResponse> response) {

            Log.d("++response registerotp", "response" + response);

            String status = response.body().getStatus();
            Log.d("++status", "status" + status);

            if (status.equalsIgnoreCase("true")) {
                showDialog(false);

                Toast.makeText(RegisterActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();


            } else {
                showDialog(false);
                Toast.makeText(RegisterActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();

            }

        }

        @Override
        public void onFailure(Call<UploadResponse> call, Throwable t) {
            showDialog(false);
            Toast.makeText(RegisterActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();

            Log.d("++", "exception" + t.getMessage());


        }
    });

}
-------------------------------------------------------------------------------
Date Change
SimpleDateFormat form = new SimpleDateFormat("yyyy-mm-dd");
java.util.Date toDate= null;
java.util.Date taskDate= null;
java.util.Date confirmDate= null;
try
{
    toDate = form.parse(mBonusDate);
    taskDate = form.parse(mTaskDate);
    confirmDate = form.parse(mConfirmDate);
}
catch (ParseException e)
{
    e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd-mm-yyyy");
//Set the to and from date in list
String newDateTo = postFormater.format(toDate);
String newtaskDate = postFormater.format(taskDate);
String newconfirmDate = postFormater.format(confirmDate);

----------------------------------

//***********Expanse or Income login on radio button****************//

rExpense = (RadioButton) view.findViewById(R.id.rExpense);
        rExpense.setChecked(true);
        rIncome = (RadioButton) view.findViewById(R.id.rIncome);
        rExpense.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rIncome.setChecked(false);
                } else {
                    rIncome.setChecked(true);
                }
            }
        });
        rIncome.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rExpense.setChecked(false);
                } else {
                    rExpense.setChecked(true);
                }
            }
        });
//************************END******************************************//

//***********Pass Value*************//
  String type = rExpense.isChecked() ? "E" : "I";
-----------------------------------------------------------------------

 


No comments:

Post a Comment