Step 1: Sign up for a Paytm merchant account To integrate the PayTM payment gateway, you need to sign up for a PayTM merchant account. Visit the PayTM Developer Portal (https://developer.paytm.com/) and follow the registration process to create your merchant account.
Add the following dependency to your app-level build. gradle file:
implementation 'com.paytm:pgplussdk:1.4.3'
Sync your project to download the PayTM SDK.
Step 3: Obtain merchant credentials After signing up for a merchant account, you will receive the necessary credentials from PayTM. These include the merchant ID and merchant key, which you’ll need for integration.
Step 4: Create a PayTM activity Create a new activity in your Android project to handle the PayTM payment process. For example, create a PaytmActivity.java file.
Step 5: Implement the PayTM payment process In the PaytmActivity.java file, implement the following steps:
Initialize the PayTM service in the onCreate() method:
PaytmPGService service = PaytmPGService.getStagingService(); // or PaytmPGService.getProductionService() for production environment
Set up the payment parameters and listener:
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("MID", "YOUR_MERCHANT_ID");
paramMap.put("ORDER_ID", "UNIQUE_ORDER_ID");
paramMap.put("CUST_ID", "CUSTOMER_ID");
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("TXN_AMOUNT", "AMOUNT");
paramMap.put("WEBSITE", "WEBSTAGING"); // for staging environment, use "DEFAULT" for production
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
paramMap.put("CALLBACK_URL", "CALLBACK_URL"); // the URL to which PayTM will send the payment response
PaytmOrder order = new PaytmOrder(paramMap);
service.initialize(order, null);
Replace the placeholders with the appropriate values from your merchant account.
Start the payment transaction:
service.startPaymentTransaction(this, true, true, new PaytmPaymentTransactionCallback() {
@Override
public void onTransactionResponse(Bundle inResponse) {
// Handle the payment response
}
@Override
public void networkNotAvailable() {
// Handle network error
}
@Override
public void clientAuthenticationFailed(String inErrorMessage) {
// Handle authentication error
}
@Override
public void someUIErrorOccurred(String inErrorMessage) {
// Handle UI error
}
@Override
public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {
// Handle web page loading error
}
@Override
public void onBackPressedCancelTransaction() {
// Handle transaction cancellation
}
@Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
// Handle transaction cancellation
}
});
Handle the payment response in the onTransactionResponse() method:
@Override
public void onTransactionResponse(Bundle inResponse) {
String status = inResponse.getString("STATUS");
String message = inResponse.getString("RESPMSG");
if (status != null && status.equals("TXN_SUCCESS")) {
// Payment was successful
} else {
// Payment failed
}
}
Step 6: Connect the PayTM activity to your app Finally, you need to connect the PayTM activity to your e-commerce app. For example, you can add a button to the shopping cart screen and launch the PayTM activity when the user selects the payment option.
That’s it! You have now integrated the PayTM payment gateway into your Android e-commerce app. Remember to replace the placeholder values with your actual merchant credentials and customize the code according to your app’s requirements.
Please note that this guide provides a basic integration example. For a complete and detailed implementation, including error handling and additional features, you may need to refer to the official PayTM documentation or consult their support resources.
Slide transition between screens is common in Android applications. We can use the navigation components or a swipe-able view to create this transition. A common swipe-able view is ViewPager2. The ViewPager library has been around for quite a while.
Introduction
This view allows the developer to display views or fragments to the user in a swipe-able format. This feature is common in content display applications and in app setups.
ViewPager2 is often integrated with TabLayout. A TabLayout indicates the current page and allows a user to switch through pages.
Prerequisites
To follow through with this tutorial, you will need to:
Create a new layout file for each of your blog fragments (fragment_blog.xml). Customize it to your needs:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Add your blog content views here -->
</LinearLayout>
Create a new class for your ViewPager adapter (BlogPagerAdapter.java):
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.List;
public class BlogPagerAdapter extends FragmentStateAdapter {
private List<Fragment> fragments;
public BlogPagerAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragments) {
super(fragmentActivity);
this.fragments = fragments;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragments.get(position);
}
@Override
public int getItemCount() {
return fragments.size();
}
}
Finally, in your MainActivity, set up the TabLayout and ViewPager2:
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager2 viewPager;
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
List<Fragment> fragments = new ArrayList<>();
fragments.add(new BlogFragment1());
fragments.add(new BlogFragment2());
fragments.add(new BlogFragment3());
BlogPagerAdapter adapter = new BlogPagerAdapter(this, fragments);
viewPager.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
// Customize the tab names as per your requirement
switch (position) {
case 0:
tab.setText("Blog 1");
break;
case 1:
tab.setText("Blog 2");
break;
case 2:
tab.setText("Blog 3");
break;
}
}).attach();
}
}
That’s it! You can now create separate fragments (BlogFragment1, BlogFragment2, etc.) and customize them for each blog page.
Note: Make sure to replace the colors and other resources with your own preferences in the XML files. Also, remember to register the MainActivity in your AndroidManifest.xml file.
This is a basic example to get you started. You can further enhance it with additional features and customization based on your requirements.
Android Bottom Navigation stays at the bottom of the screen providing navigation between top-level views in the app. This is introduced in design support library with backward compatibility. Bottom Navigation should be used when the app has three to five top-level navigations.
This article explains the basics of Bottom Navigation, combining it with Fragments. We also going to learn how to load the first fragment with grid data (using RecyclerView) by fetching JSON through HTTP call.
1. Bottom Navigation
The Bottom Navigation can be easily added using BottomNavigationView component. You have to use gravitation or relative attributes to make it appear at the bottom of the screen.
app:menu — The menu resource file to display the navigation items along with icon and text. app:itemBackground — Applies background color to bottom navigation. app:itemTextColor — The text color of bottom navigation item. app:itemIconTint — The icon color of bottom navigation item.
When to use Bottom Navigation? As per the design specs, the below navigations should be used depending on the criteria.
>Navigation Drawer – Use when top-level navigation has more than six destinations.
>Tabs – Use when there are two navigational destinations.
>Bottom Navigation – Use when there are three to five top-level destinations.
Before going further, have a quick look at the design specifications of Bottom Navigation.
Now let’s try it by creating a new project in Android Studio.
2. Creating New Project
1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.
2. Download this res folder and add the drawables to your project’s res. This folder contains necessary drawables required for bottom navigation items.
3. Make sure you have design support library in your build.gradle.
6. Open the layout file of main activity i.e activity_main.xml and add BottomNavigationView widget. Here we are also adding a FrameLayout to load the Fragments when the navigation item is selected.
7. Now open MainActivity.java and modify it as below.
> Here, OnNavigationItemSelectedListener will be called when the bottom navigation item is selected. For now we are just changing the toolbar title upon selecting the navigation item.
If you run the app, you can see the bottom navigation displayed as shown below.
3. Adding Fragments
As we have the Bottom Navigation ready, let’s see how to switch views when the navigation menu item is selected. This can be done easily by using the Fragments.
Note: ViewPager shouldn’t be used when using Bottom Navigation as per design specs (Avoid using lateral motion to transition between views)
I am creating four fragments named StoreFragment, GiftsFragment, CartFragment and ProfileFragment.
8. Create new Fragment by going to File ⇒ New ⇒ Fragment ⇒ Fragment (Blank) and name it as StoreFragment.java. Likewise create other three fragments too.
9. Open MainActivity.java and modify bottom navigation listener as below to load the fragments in FrameLayout.
>loadFragment() – loads the Fragment into FrameLayout. The same method is called in OnNavigationItemSelectedListener callback by passing appropriate fragment instance. > The logic needed for specific module goes into appropriate Fragment keeping the MainActivity clean.
MainActivity.java
package info.androidhive.bottomnavigation;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import info.androidhive.bottomnavigation.fragment.CartFragment;
import info.androidhive.bottomnavigation.fragment.GiftsFragment;
import info.androidhive.bottomnavigation.fragment.ProfileFragment;
import info.androidhive.bottomnavigation.fragment.StoreFragment;
import info.androidhive.bottomnavigation.helper.BottomNavigationBehavior;
public class MainActivity extends AppCompatActivity {
private ActionBar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
// load the store fragment by default
toolbar.setTitle("Shop");
loadFragment(new StoreFragment());
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_shop:
toolbar.setTitle("Shop");
fragment = new StoreFragment();
loadFragment(fragment);
return true;
case R.id.navigation_gifts:
toolbar.setTitle("My Gifts");
fragment = new GiftsFragment();
loadFragment(fragment);
return true;
case R.id.navigation_cart:
toolbar.setTitle("Cart");
fragment = new CartFragment();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
toolbar.setTitle("Profile");
fragment = new ProfileFragment();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
Now if you run the project you can see the fragments loaded when navigation is selected.
4. Implementing ShopFragment – Displaying Items in Grid
Now we’ll see how to implement the first fragment i.e ShopFragment which displays the shop items in a Grid fashion. For demonstration, I have created a sample json which contains few movies for sale. To implement this, all we have to do is, fetch json and display the data in RecyclerView in a grid format. To make the task simpler, follow my other article which explains the same.
14. Create an xml layout named store_item_row.xml under res ⇒ layout. This layout file will be used in RecyclerView adapter class to render single item.
15. Create a class named Movie.java. This POJO class will be useful while parsing the json.
Movie.java
package info.androidhive.bottomnavigation;
public class Movie {
String title;
String image;
String price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
16. Now open StoreFragment.java and add below code. For simplicity the RecyclerView adapter class StoreAdapter included in the same fragment.
>fetchStoreItems() Method fetches the movies json using Volley and serializes it using Gson.
>StoreAdapter class renders the movies in RecyclerView.
StoreFragment.java
package info.androidhive.bottomnavigation.fragment;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.bottomnavigation.Movie;
import info.androidhive.bottomnavigation.app.MyApplication;
import info.androidhive.bottomnavigation.R;
public class StoreFragment extends Fragment {
private static final String TAG = StoreFragment.class.getSimpleName();
private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
private RecyclerView recyclerView;
private List<Movie> movieList;
private StoreAdapter mAdapter;
public StoreFragment() {
// Required empty public constructor
}
public static StoreFragment newInstance(String param1, String param2) {
StoreFragment fragment = new StoreFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_store, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
mAdapter = new StoreAdapter(getActivity(), movieList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(8), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
fetchStoreItems();
return view;
}
private void fetchStoreItems() {
JsonArrayRequest request = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
return;
}
List<Movie> items = new Gson().fromJson(response.toString(), new TypeToken<List<Movie>>() {
}.getType());
movieList.clear();
movieList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MyApplication.getInstance().addToRequestQueue(request);
}
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
class StoreAdapter extends RecyclerView.Adapter<StoreAdapter.MyViewHolder> {
private Context context;
private List<Movie> movieList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, price;
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.title);
price = view.findViewById(R.id.price);
thumbnail = view.findViewById(R.id.thumbnail);
}
}
public StoreAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.store_item_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final Movie movie = movieList.get(position);
holder.name.setText(movie.getTitle());
holder.price.setText(movie.getPrice());
Glide.with(context)
.load(movie.getImage())
.into(holder.thumbnail);
}
@Override
public int getItemCount() {
return movieList.size();
}
}
}
Now if you run the app, you can see the ShopFragment displaying the movies in grid manner. Likewise you can implement other fragments too.
5. Hiding Bottom Navigation on Scroll
As per design specs, the Bottom Navigation has to be hidden when the content is scrolled giving more room to content on the screen. To achieve this, we need to attach the BottomNavigationBehavior to Bottom Navigation.
17. Create a class named BottomNavigationBehavior.java with the below code.
I am Vishal Swami, mobile and web application developer. Having worked with various technologies ranging from PHP to ASP.NET to iPhone and Android of course, I in the process noticed that there are not many good blogs targeted towards beginners when it comes to mobile(android) development, hence I decided to start this blog where I can share my experience with Android development and hopefully help you guys find quick tips and good resources.
My first post is a quickie on how to get yourself started with Android development and the tools you will need to get going. So lets get started with your first basic setup for Android development.
1. Download & Install the Android SDK
a. Download the Android SDK b. Install/Extract the downloaded SDK c. Go to the directory where you installed the SDK and open SDK Manager to open Android SDK and AVD Manager. d. In AVD manager under Avaliable Packages you can see different versions of SDK’s
e. Select SDK Platform tools and one of the version of SDK and click on install
2. Downloading Eclipse Software
Although there are lot of IDE out there Eclipse is recommended IDE which will give you best support for Android app development.
3. Installing Android Development Toolkit (ADT) plug-in
a. Open Eclipse s/w and under Help -> Install New Software… b. Now you will see a window which allows you to install new plug-in c. Click on Add button and in Name and in Location give the link https://dl-ssl.google.com/android/eclipse/ and proceed with further steps.
4. Creating Sample Project
Creating a sample android project involves very few steps
a. In your Eclipse IDE go to File -> Android Project b. Give Project Name, Select Build Target, Application Name, Package Name, Activity Name, Min SDK version and click Finish
c. Now you can see bunch of files created in the project explorer.
5. Creating New Android Virtual Device (AVD)
The AVD is an emulator which provides you android hardware and software environment to test application on computer.
a. In Eclipse open SDK Manager under Windows -> Android SDK and AVD Manager
b. Click on New on the right side.
c. Give Name, Select Target give SD Card size and click on Create AVD.
d. Now a new AVD is created with the specification you provided and Close the Android SDK and AVD Manager
6. Running the Project
Once you successfully created AVD you are ready to test your application.
a. Right Click on the project in Package Explore and click on Run As -> Android Application.
b. Now you can see an AVD is opened and booting up.( It will take much time to launch AVD for the first time) c. Once the AVD started you can see the output on the AVD screen.