Learnings Posts

post

Software testing is a process of checking and validating the functionality of an application to determine if it meets specified requirements. It is about finding application faults and verifying where the application is operating according to the end-user needs.

Important Software Testing Techniques:-

  • Boundary Value Analysis (BVA)
  • Equivalence Class Partitioning
  • Decision Table based testing.
  • State Transition
  • Error Guessing
  • Boundary Value Analysis (BVA)
  1. The marginal cost assessment is based entirely on trying the boundaries between partitions. It includes maximum, minimum, internal, or external barriers, typical values, and error values. It is generally seen that numerous errors occur at the obstacles of the defined input values as opposed to the center.

  2. It is also known as BVA and offers a selection of test entities that train limit values. This black container test method improves equivalence partitioning. This software program trying one approach is based on the principle that if a machine works well for these exact values, it will paint error-free for all values that are between the two limits.

Let's see one example:

Input condition is valid between 1 and 10 Boundary values 0,1,2 and 9,10,11

Equivalence Class Partitioning

The equal class phase lets you divide a hard and fast check state into separate sections which are taken into consideration identical. The equal class division software program test technique breaks the input area of a program into a class of information, so a test case has to be designed.

Let’s see one example:

Input conditions are valid between

1 to 10 and 20 to 30

Hence, there are five equivalence classes

--- to 0 (invalid)

1 to 10 (valid)

11 to 19 (invalid)

20 to 30 (valid)

31 to --- (invalid)

You select values from each class, i.e.,

-2, 3, 15, 25, 45

Decision Table Based Testing

The decision table is known as the cause and effect table. This testing technique is suitable for input features that have a logical relationship between inputs. In this technique, combinations of inputs are processed. In order to identify the test case with the decision table, it is necessary to consider the terms, actions, and procedures. Conditions are taken as input and actions as output.

Testing Using The Decision Table In The Login Form

software-testing-technology/1

CONDITIONS - CASE 1, CASE 2, CASE 3, CASE 4

| EMAIL | F | T | F | T | PASSWORD | F | F | T | T | OUTPUT | ERROR | ERROR | ERROR | HOME SCREEN

CASE 1: Email And Password Wrong: Error Message Displayed.

CASE 2: Email True And Password Wrong, Error Message Displayed.

CASE 3: Email Wrong And Password True, Error Message Displayed.

CASE 4: Email And Password True, Redirect to Home screen

State Transition Testing Technique

In-State Transition technique changes in input conditions change the state of the Application Under Test (AUT). This testing technique allows the tester to test the behavior of an AUT. The tester can perform this action by entering various input conditions in a sequence. In-State transition technique, the testing team provides positive as well as negative input test values for evaluating the system behavior.

Presently We Make A Diagram For Forgot Password/OTP Proces

software-testing-technology/2

software-testing-technology/3

  1. First Enter the Right Number In This Text Box and Click RESET PASSWORD Button. One OTP Comes On Mobile Number.
  2. To reset the secret word you should experience the "OTP'' framework. The first run-through the client enters is "OTP '', they will be permitted to go to the secret phrase change page.
  3. In the event that the client enters mistaken "OTP '' unexpectedly and second, the framework will request the third time "OTP'' is entered.
  4. In the event that "OTP'' is valid, it will be permitted to go to the secret phrase change page, in any case, if the OTP is off base the third time, an Error Message Displayed Like "Your OTP has expired!!".

State Transition Table

ATTEMPT CORRECT PIN INCORRECT PIN

| [B1] Start | B5 | B2

| [B2] First attempt | B5 | B3

| [B3] Second attempt | B5 | B4

| [B4] third attempt | B5 | B4

| [B5] Access granted | - | -

| [B6] Account blocked | - | -

Error Guessing Technique

Error guessing is a software testing technique based on guessing the error that can appear in the code. The technique relies heavily on experience, with the test analysts using their experience to guess the problematic part of the test application. Therefore, test analysts need to be competent and experienced in order to better guess errors. The technique counts a list of possible errors or error-prone situations. Then the tester writes a test case to uncover these errors. To design test cases based on this software testing technique, the analyst can use the experience to identify the conditions.

This technique can be used at any level of testing and for testing the common mistakes like:

  • Divide by zero
  • Inserting blanks in text fields
  • Pressing the enter button without entering values
  • Uploading files that exceed the maximum limits
  • Exception null pointer.
  • Invalid parameters

Let’s see one example:

Suppose there is a requirement that the phone number be numeric and not less than 10 characters. And the software application has a phone number.

The following are the error estimation techniques:

  1. What will be the result if the cellphone number is left blank?
  2. What is the result if a character other than a digit is entered?
  3. What is the result if fewer than 10 digits are entered?
August 22, 20204 minutesauthorBhumi Khimani
post

We work on projects with the admin panel every day. In which we mostly use data tables and we need to delete the record from the data table without page refresh.

So, today I will show you how to extract a record using Ajax. It's very easy to integrate.

Let's take one example. I have a Category data table and I want to delete one category from the table without refreshing the page. Now, what am I doing for that? First of all, I add a class for the listen to a click event into the delete button and it says delete-btn.

See the following image for where I added a class.

delete-record-using-ajax-in-laravel/1

I used SweetAlert for the confirmation popup. let add sweet alert's CSN into the index.blade.php.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css"> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

Let's declare routes of the delete record.

<script>let categoryUrl = '{{route('categories.index')}}'; </script>

Next steps, I'm going to listen to the click event of the delete button. one more thing does not forget to add the record id into the data attribute to the delete button. see the above image for it. I highlighted it with a yellow line.

So the general practices we use in Laravel is to write the following code to listen to a click event and delete a record,

$(document).on('click', '.delete-btn', function (event) {             
           const id = $(event.currentTarget).data('id');

  swal({ 
      title: 'Delete !',                     
      text: 'Are you sure you want to delete this Category" ?',                     
      type: 'warning',                    
      showCancelButton: true,                     
      closeOnConfirm: false,                     
      showLoaderOnConfirm: true,                     
      confirmButtonColor: '#5cb85c',                     
      cancelButtonColor: '#d33',                     
      cancelButtonText: 'No',                     
      confirmButtonText: 'Yes',                 },                 
          function () {                    
                   $.ajax({                 
                       url: categoryUrl + '/' + id,                 
                       type: 'DELETE',                 
                       DataType: 'json',                 
                       data:{"_token": "{{ csrf_token() }}"},                 
                       success: function(response){                     

                              swal({                                 
                                  title: 'Deleted!',                                 
                                  text: 'Category has been deleted.',                                 
                                  type: 'success',                                 
                                  timer: 2000,                             
                              });                     
 $('#categoryTbl').DataTable().ajax.reload(null, false);                 
              },                 
               error: function(error){                     
               swal({                                 
                   title: 'Error!',                                 
                   text: error.responseJSON.message,                                 
                   type: 'error',                                 
                   timer: 5000,                             
              })                     
            }             
        });                 
    });         
});

Now we are done with the front-end side and need to look into it backend side.

Let's declare the destroy method into the category Controller. I hope are you generate crud with InfyOm Laravel Generator. so, the Destroy method and routes are there. If not please create a route. if the destroy method is there then need to change the response of that method.

The destroy method code looks like,

public function destroy($id) { $category = $this->categoryRepository->find($id); if (empty($category)) { Flash::error('Category not found');

        return $this->sendError('Category not found.');
    }

    $this->categoryRepository->delete($id);

    return $this->sendSuccess('Category deleted successfully.');
}

Now we are done. the video tutorial also available here

August 19, 20202 minutesauthorShailesh Ladumor
post

Here is part one of How to Keep Your Customers Happy & Increase Repeat Project

9. Know your products and services

Customers want to work with knowledgeable employees. Learn all you can about your products so you can be better equipped to answer customer questions. If you are unsure about something, ask for help.

10. Treat your customers individually

Not all customers are the same. Every customer has individual needs and concerns and they want to be treated with a personal touch that doesn’t make them feel like a number. Communicate the way your customers want to communicate.

11. Make it easy for your customers to complain

Your customers seem to have heard, especially when they are frustrated with the service they have received. Customers know what they like and at least about your service. Ongoing surveys are a reliable and consistent approach to getting feedback but don’t miss the opportunity when you’re with a customer. Just asking you sends a beautiful message about how you value your customers and their feedback.

12. Thank your customers for every opportunity you get

Thank you very much for your customers. Thank you for calling, bringing payment, meeting you at their home, calling for help, and yes, calling for a complaint! For many, there are options available and they chose your company over the competition.

13. Never accept your customers

Your customers are your business!

14. To be active

Don't wait for your client to reach you. Reach out to them in more than one way. Improving the first call resolution cases of the customer problem will improve the overall customer experience. Create a complete self-help interface, in which customers can solve their problems manually.

15. I will take responsibility

Tell your customer that you understand that you have a responsibility to ensure a satisfactory outcome of the transaction. Assure the customer that you know what she expects and will deliver the product or service at the agreed price. There will be no unexpected charges or costs to solve the problem.

August 03, 20202 minutesauthorAnkit Kalathiya
post
Organisational Culture is an aspect that impacts every organization’s functioning. Keeping in view the vital role that plays in the success of any Organisation. I would like to mention the desired culture is the “OCTAPACE” Culture. “OCTAPACE” culture is the best initiative for any Organisation, whether it’s an IT or Non-IT organization. Let’s look at- What is “OCTAPACE” culture? How will it be helpful to Organisational Growth? OCTAPACE Meaning Outcome O - Openness
  • Freedom to communicate.
  • It signifies the transparency of the environment in the organization.
  • It helps to improve the implementation of any system & bring innovation by free interaction among team members, clarity in setting objects, and common Goals.
C - Confrontation
  • Facing problems and challenges.
  • The person is facing it boldly and not shying.
  • Improve Problem Solving.
  • Clarity in work.
  • Group discussion to resolve particular problems.
T - Trust
  • Maintaining confidentiality.
  • Building trust in each other.
  • Do not share anything to others or outside of the organization.
  • Higher Empathy.
  • Timely Support.
  • Reduce Stress.
A - Authenticity
  • No or narrowest gap between said value & Actual behaviour.
  • Person’s commitment to work/Assigned tasks & Actual performance should be the same.
  • Everyone has attitude “Jo me bolta hu wo me karta hu”
  • Develop mutuality culture.
  • Sharing of feeling freely.
  • Improve interpersonal communication.
  • Reduce the distortion in Communication.
P- Pro-Active
  • Taking Initiative.
  • Pre- Planning.
  • It prepared everyone for upcoming challenges.
  • Reduce uncertainty.
  • One step ahead (advance team)
  • Prepare everyone to accept changes with time.
A- Autonomy
  • Freedom to plan & act at one’s own level.
  • Organisation must avoid an Autocratic type of environment and give chance to all members to use their power in a positive way.
  • Develop mutual relationship.
  • Feeling of Pride.
  • Self Motivation
  • work satisfaction.
C- Collaboration
  • Involves working together for common cause.
  • individuales share their concerns and prepare strategies for working out plans, actions & implementing them together.
  • Timely work.
  • Resource sharing.
  • Improve Communication.
E-Experimentation
  • Trying out new ways to deal with problems/Tasks.
  • Organisation should allow all to experiment new ways and encourage them to find the best ways.
  • Accurate problem solutions.
  • Development of new products.
  • Development of New methods.

To recapitulate, Organisational culture represents Values, Beliefs, behaviors & Capabilities acquired by the members of the firm. We can truly say if the Organisation has all Dimensions of __“OCTAPACE”,__ it is on the way to __SUCCESS__……….
July 31, 20202 MinutesauthorMariyam Bemat
post

1.Add this library build.gradle(:app)

  • This library user for firebase integration dependencies
  • { 
       implementation 'com.google.firebase:firebase-auth:19.4.0'
    }

2.Add this permission in AndroidManifest.xml

  • This permission use internet connection checking
{
<com.facebook.login.widget.LoginButton          
android:id="@+id/login_button"          
android:layout_width="match_parent"          
android:layout_height="match_parent"          
android:layout_gravity="center"
android:visibility="gone"/>
}

3.Activity in add this permission

  • This permission is for user data. Without this permission user data not meet

  • loginButtonThis button is Facebook button

  • LoginManager.getInstance().logInWithReadPermissions(FacebookLoginActivity.this, Arrays.asList("email", "public_profile"));
  • loginButton.setReadPermissions("email", "public_profile");

4.Initialize Authentication:

void initializeAuthentication(){
   FirebaseAuth  mAuth = FirebaseAuth.getInstance();
   GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
   .requestIdToken(getString(R.string.default_web_client_id))
   .requestEmail()
   .build();
   mGoogleSignInClient = GoogleSignIn.getClient(this, so); 
}

7.Add This Function:

  • This function user login result return
void faceBookLogin(LoginResult loginResult){
   setFacebookData(loginResult);
   Profile profile = Profile.getCurrentProfile();      
   if (profile != null) {        
      String avatar = ImageRequest.getProfilePictureUri(profile.getId(), 200, 200)
     .toString();    
   }    handleFacebookAccessToken(loginResult.getAccessToken());
}

7.Handle Token :

  • This token return firebase login fails or not an event
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)           
.addOnCompleteListener(this, new OnCompleteListener() {                
      @Override                
      public void onComplete(@NonNull Task task) {
      if (task.isSuccessful()) {
      FirebaseUser user = mAuth.getCurrentUser();
      user.getIdToken(true).addOnCompleteListener(new OnCompleteListener() {
      @Override
      public void onComplete(@NonNull Task task) {
            String token = task.getResult().getToken();
       }
    });
 } else {
      String errorCode = String.valueOf(task.getException());
      Toast.makeText(FacebookLoginActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
                    } 
            }
    });
}

Notes:

  • “Default_web_client_id” this keyword, not changes because creating google-services.json file time automatically this keyword in add values so this key work put at its
How to creating google JSON file : JSON File

Add google JSON file this location in android studio:

July 28, 20201 minuteauthorPankaj Valani
post

The Stripe Customer Portal is very useful for managing customer subscriptions like Upgrade, Downgrade, and Renew.

Customers can review their invoices directly and also check their history.

Portal billing setting

Do login into your stripe account

Navigate to the portal settings to configure the portal, and do below billing settings

setting

Create Product

First of all, we need to create products. Follow the below process for creating products.

Click on the “Products” menu from the sidebar and click on the “Add Product” button on the top right corner of the products page and create a product.

Here is an example of how to create a product.

Create two or three products as shown below.

product

Select product In portal settings

If you want to allow your customer to change their subscription by an upgrade, downgrade, cancel or renew you need to set products in your portal setting.

Now navigate to customer portal settings again, in the Products section, you will find a dropdown “Find or add a product..”, click on it you will find the plan you have added, select the price of this product.

portal settings

Don’t forget to save all these settings.

Then do the setup of your business information, also do branding settings in the “Appearance” section, and save it.

Once you are done with settings, you can preview the customer portal by clicking the Preview button beside the save button.

This will launch a preview of the portal so you can see how customers will use it for managing their subscriptions and billing details.

Integrate into Laravel

  • Get you API keys
    • Go to “Developers > API keys” here you will find your “Publishable key” and “Secret key

api keys

  • Create customer using stripe dashboard or by API
    • Create customer by Stripe API.
    • First of all, you’ll need to set your stripe secret key. For development mode, you can use test mode keys, but for production, you need to use your live mode keys
\Stripe\Stripe::setApiKey('sk_test_YOUR_KEY');
$customer = \Stripe\Customer::create([undefined]);
  • Once you create a customer using stripe API, now you can create a billing session for that customer using stripe API.
    • Create a billing session of the customer by API
\Stripe\Stripe::setApiKey('sk_test_YOUR_KEY'); 
\Stripe\BillingPortal\Session::create([    
      'customer'   => 'cus_HnKDAQNjBniyFh',    
      'return_url' => 'https://example.com/subscription'
]);

You’ll get a response, like the below object:

{
  "id": "pts_c5cfgf8gjfgf73m5748g6",
  "object"    : "billing_portal.session",
  "created"   : 453543534,   
  "customer"  : "cus_bGFsnjJDcSiJu",   
  "livemode"  : false,   
  "return_url": "https://example.com/subscription" 
}

In the response body, there is a URL attribute:

Now redirect your customer to this URL immediately. For security purposes, this URL will expire in a few minutes.

After redirecting the customer to this URL, the portal will open and customers can manage their subscriptions and billing details in the portal. customers can return to the app by clicking the Return link on your company’s name or logo within the portal on the left side. They’ll redirect to the return_url you have provided at the time of creating the session or redirect URL set in your portal settings.

Listen to Webhooks

You must have a question, what is this Webhook!!!

It’s just an event, which will fire when a customer does any changes in his/her subscription in the portal, we can listen to this event in our app and make appropriate changes.

For example,

If a customer cancels his/her subscription in the portal, then how we will know about it!!

For it, when customers do any changes in his/her subscription

“customer.subscription.updated” event will be fired and we can listen for this event and, get to know the customer has changed subscription so we need to do appropriate changes in our app also.

Set webhook in your app

In the webhooks.php (in routes folder) file set up a route to handle webhook.

You can use the Laravel Cashier Package (https://laravel.com/docs/8.x/billing)to handle webhooks.

To set up a webhook for your portal navigate to the “Developers > Webhooks” menu you will find the below screen, here I have added a webhook to handle subscription cancel and update events, it will fire when customers update subscription, and you will receive it.

webhook

Click on the “Add endpoint” button and the below pop up will open. In Endpoint URL set the route you have created in the webhooks.php file. Select subscription updated and deleted events.

webhook endpoint

All done.

For more details, you can use stripe customer portal integration

July 25, 20203 MinutesauthorMonika Vaghasiya
post

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you deliver messages for free.

It allows you to send push notifications from the Firebase console or from the application server or some trusted server where logic runs.

Step 1:- Create a new Android Studio Project

First, create a new Android Studio project and add the dependencies. First set up Firebase in your project. You can find a good tutorial.

Add Firebase messaging dependency to your app-level.

build.Gradle
dependencies {
  implementation 'com.google.firebase:firebase-messaging:19.0.1'
}

Step 2: Create a Firebase Service

The next step is to create Firebase Services:- MyFirebaseInstanceIDService and MyFirebaseMessagingService. first MyFirebaseInstanceIDService service will handle the device registration process and the second MyFirebaseInstanceIDService will handle the reception and display of notifications. The services have no visual interface and are used for operations that run in the background. To create a service, right-click and select the Applications folder New -> Service -> Service.

push-notification-using-firebase-cloud-messaging/1

Type in your service name, and click the Finish button. Repeat the same steps for the second service.

push-notification-using-firebase-cloud-messaging/2

AndroidManifest.xml file and update your service declarations under the application tag. Also, add INTERNET and CLOUD TO DEVICE MESSAGING permissions so your app can interact with the FCM server.

<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.exmple.notify">

  <uses-permission android:name="android.permission.INTERNET">
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE">

<application android:allowbackup="true" 
android:icon="@mipmap/ic_launcher" 
android:label="@string/app_name" 
android:roundicon="@mipmap/ic_launcher_round" 
android:supportsrtl="true" 
android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN">
        <category android:name="android.intent.category.LAUNCHER">
      </category></action></intent-filter>
    </activity>

    <service android:name=".MyFirebaseInstanceIDService">
      <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT">
      </action></intent-filter>
    </service>

    <service android:name=".MyFirebaseMessagingService"

android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT">
        <action android:name="com.google.android.c2dm.intent.RECEIVE">
      </action></action></intent-filter>
    </service>
  </application>
</uses-permission>
</uses-permission>
</manifest>

To handle the device registration process, MyFirebaseInstanceIDService must increase the FireBaseInstenside service class. Under this service, override the tokenrefresh() method so that whenever the system decides to refresh the tokens, it will be requested. This usually happens when the user installs/reinstalls the application or when the user clears the application data.

Since you are sending notifications between devices, each user must subscribe to an issue with a different user_id. This ensures that users receive notifications sent to topics that match their user_id. Here is the implementation of MyFirebaseInstanceIDSericiclass.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

  private final String ADMIN_CHANNEL_ID = "admin_channel";

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    final Intent intent = new Intent(this, MainActivity.class);
    NotificationManager notificationManager = (NotificationManager) 
getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationID = new Random().nextInt(3000);
   /*
    Apps targeting SDK 26 or above (Android O) must implement notification channels and add their notifications to at least one of them. 
Therefore, confirm if the version is Oreo or higher, then setup notification channel
   */
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
      setupChannels(notificationManager);
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.notify_icon);
    Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIF CATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
        .setSmallIcon(R.drawable.notify_icon)
        .setLargeIcon(largeIcon)
        .setContentTitle(remoteMessage.getData().get("title"))
        .setContentText(remoteMessage.getData().get("message"))
        .setAutoCancel(true)
        .setSound(notificationSoundUri)
        .setContentIntent(pendingIntent);

    // Set notification color to match your app color template
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      notificationBuilder.setColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    notificationManager.notify(notificationID, notificationBuilder.build());
  }

  @RequiresApi(api = Build.VERSION_CODES.O)
  private void setupChannels(NotificationManager notificationManager) {
    CharSequence adminChannelName = "New notification";
    String adminChannelDescription = "Device to device notification ";

    NotificationChannel adminChannel;
    adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, 
    adminChannelName, 
    NotificationManager.IMPORTANCE_HIGH);

    adminChannel.setDescription(adminChannelDescription);
    adminChannel.enableLights(true);
    adminChannel.setLightColor(Color.RED);
    adminChannel.enableVibration(true);

    if (notificationManager != null) {
      notificationManager.createNotificationChannel(adminChannel);
    }
  }
}

Step 3: Implement the notification sending logic

This is the most important part of the whole article. This is where you define the content of the instruction and how it will be modeled. However, before you dive into coding, follow these steps to get your server key from the Firebase console.

push-notification-using-firebase-cloud-messaging/3

Navigate to the Cloud Messaging tab, and copy your Server key

push-notification-using-firebase-cloud-messaging/4

Implement the Sending Logic: An FCM server with the following request properties only needs an HTTP post request to send a push notification:

Method Type: POST

URL: https://fcm.googleapis.com/fcm/send

Headers:

Authorization: key="Firebase server key" Content-Type: application/json

Body:

{
 "to": "/topics/notification_userId",
 "data": {
  "title": "Notification title",
  "message": "Notification message",
  "key1" : "value1",
  "key2" : "value2" //additional data you want to pass
 }
}

With these concepts in mind, you will first create a JsonObject of Notification body within your activity class. This object budget will contain the subject of the receiver, the title of the notification, the notification message, and the other key/value pair you want to add.

public class MainActivity extends AppCompatActivity {
  EditText edtTitle;
  EditText edtMessage;
  final private String FCM_API = "https://fcm.googleapis.com/fcm/send";
  final private String serverKey = "key=" + "Your Firebase server key";
  final private String contentType = "application/json";
  final String TAG = "NOTIFICATION TAG";

  String NOTIFICATION_TITLE;
  String NOTIFICATION_MESSAGE;
  String TOPIC;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edtTitle = findViewById(R.id.edtTitle);
    edtMessage = findViewById(R.id.edtMessage);
    Button btnSend = findViewById(R.id.btnSend);

    btnSend.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        TOPIC = "/topics/userABC"; //topic must match with what the receiver subscribed to
        NOTIFICATION_TITLE = edtTitle.getText().toString();
        NOTIFICATION_MESSAGE = edtMessage.getText().toString();

        JSONObject notification = new JSONObject();
        JSONObject notifcationBody = new JSONObject();
        try {
          notifcationBody.put("title", NOTIFICATION_TITLE);
          notifcationBody.put("message", NOTIFICATION_MESSAGE);
          notification.put("to", TOPIC);
          notification.put("data", notifcationBody);
        } catch (JSONException e) {
          Log.e(TAG, "onCreate: " + e.getMessage() );
        }
        sendNotification(notification);
      }
    });
  }
  private void sendNotification(JSONObject notification) {
 ...
  }
}

The next step is to request the network server using the library volley, then use the parameters to the root server will request notification on the target device.

public class MainActivity extends AppCompatActivity {

  ....

  private void sendNotification(JSONObject notification) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
            new Response.Listener() {
              @Override
              public void onResponse(JSONObject response)
              {
                Log.i(TAG, "onResponse: " + response.toString());
                edtTitle.setText("");
                edtMessage.setText("");
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Request error", Toast.LENGTH_LONG).show();
                Log.i(TAG, "onErrorResponse: Didn't work");
              }
            }){
          @Override
          public Map getHeaders() throws AuthFailureError {
            Map params = new HashMap<>();
            params.put("Authorization", serverKey);
            params.put("Content-Type", contentType);
            return params;
          }
        };
    MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
  }
}

Finally, add a MySingleton class that will serve as a request queue for instruction requests.

public class MySingleton {
  private static MySingleton instance;
  private RequestQueue requestQueue;
  private Context ctx;

  private MySingleton(Context context) {
    ctx = context;
    requestQueue = getRequestQueue();
  }
  public static synchronized MySingleton getInstance(Context context) {
    if (instance == null) {
      instance = new MySingleton(context);
    }
    return instance;
  }
  public RequestQueue getRequestQueue() {
    if (requestQueue == null) {
      // getApplicationContext() is key, it keeps you from leaking the
      // Activity or BroadcastReceiver if someone passes one in.
      requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
    }
    return requestQueue;
  }
  public  void addToRequestQueue(Request req) {
    getRequestQueue().add(req);
  }
}

With it, you're done creating your app. You can start sending push notifications between devices without typing any server-side code. Always make sure that the notification will not be delivered to you if the subject of the recipient is correct. If you do everything right, you will get the same result.

push-notification-using-firebase-cloud-messaging/5

July 21, 20206 minutesauthorVivek Beladiya
post

Livewire is a very awesome thing that I have ever seen, the old school developers are still using the jquery and ajax concept to not refresh the page. But forget the jquery and ajax stuff. If you are good at PHP then you can do the same with Laravel Livewire.

Wait what?

Load dynamic data on the page without using ajax? Yes, it is possible with Laravel Livewire. So that is all about laravel livewire, and in this tutorial, we will see how to build laravel pagination with laravel livewire.

Let's start and I hope you have already set up the livewire. Let's say you already have created a component named UsersListing Now in the users listing, we want to paginate all users and we will list 10 records per page.

How to use pagination with Laravel Livewire

Livewire provides a trait called WithPagination and you have to add it into your component UsersListing. Check out the following code:

use Livewire\WithPagination; 
use Livewire\Component; 
class UsersListing extends Component 
{ 
   use WithPagination;

   public function render() 
     { 
       return view('livewire.users.index', [ 'users' => User::paginate(10), ]); 
     } 
} 

And to load pagination you have to add the following code:

@foreach ($users as $user) ... 

@endforeach {{ $users->links() }} 

That's it, and your laravel pagination now works like charm without page refresh. There is much more about pagination like how to use it with a custom view, how to use it with a custom theme. We will see it in our next tutorial, until then enjoy the code

July 11, 20201 minuteauthorVishal Ribdiya