Showing posts with label android studio. Show all posts
Showing posts with label android studio. Show all posts

Last Updated: October 30, 2019

Things every android developer should know - part 5

Description: Hello coders! In this post I'm gonna show some interesting tips and tricks you can start using in your android project.

Also check out Part 1,Part 2Part 3 and Part 4

So let's get started.

1. How to remove boiler plate code of  Parcelable interface?

Let's consider this class with Parcelable Interface implementation. This class contains overriden methods which are boiler plate at larger extends

class User(val id: String, val name: String, val age: Long, val address: String, val isPrime: Boolean, val contact: String) : Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString(),
            parcel.readLong(),
            parcel.readString(),
            parcel.readByte() != 0.toByte(),
            parcel.readString())

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(id)
        parcel.writeString(name)
        parcel.writeLong(age)
        parcel.writeString(address)
        parcel.writeByte(if (isPrime) 1 else 0)
        parcel.writeString(contact)
    }

    override fun describeContents(): Int = 0

    companion object CREATOR : Parcelable.Creator {
        override fun createFromParcel(parcel: Parcel): User {
            return User(parcel)
        }

        override fun newArray(size: Int): Array {
            return arrayOfNulls(size)
        }
    }

}

So here comes @Parcelize annotation into picture. Lets modify our User class using @Parcelize
@Parcelize
class User(val id: String, val name: String, val age: Long, val address: String, 
           val isPrime: Boolean, val contact: String) : Parcelable

@Parcelize is the part of androidExtensions we have to enable it by adding below snippets within module's build.gradle section.
android {
    ...
    androidExtensions {
        experimental true
    }
    ...
}

2. Using Plurals

Although plurals where introduced long time back, but have seen developers adding logics for plural strings. Let's take an example of adding plural, when any post is liked.
    <plurals> name="like_count">
        <item quantity="one">%d second ago</item>
        <item quantity="other">%d seconds ago</item>
    </plurals>


Access within the code
mContext.resources.getQuantityString(R.plurals.like_count, 1, 2)

#Output:
2 second ago

#Note: First argument matches the plural and second is the argument for %d 

3. How to Change Default layout of activity?


Its interesting because it will help to add some constant template(toolbar in all the activity etc ) which we normally add after the activity is created, henceforth saving time. Simply Go to File -> New -> Edit File Templates


Edit Templates
Edit Templates

Change Default Tag of any layout.xml
Changing Root Tag for layouts

In the above example we can simply replace  ROOT_TAG with <LinearLayout> and next time when we create new layout it will start with <LinearLayout>


Bingo we're done.

For more updates follow us on -  Twitter

#codingIsAnArt
#coderconsole

Last Updated: December 27, 2017

Things every android developer should know - part 4

Description: In this post, I will show you some interesting tools from Android Studio that developers use.

Also check out Part 1,Part 2  and  Part 3.


So let's get started.


1. Layout Inspector: Layout Inspector is an interesting tool to help track view and their respective properties. It contains-

    •    View Tree - contains the hierarchy of the Android widgets displaying the full nesting of views.
    •    Properties Table - contains the properties attached to the respective view. e.g.: layouts/methods/padding and many more.
 a) How to enable it?
        Goto Tools -> Android -> Layout Inspector fig.1 
     
fig.1 Layout Inspector
 Note: Make sure you have an Android process running for your app and you have an active window present to take the screenshot.

 b) How to understand it?(fig.2)

    Left
       - 'View Tree' showing the full hierarchy of the screen.
   Center
     - Screenshot of the active window       
   Right
      - 'Properties Table' for each view.
  View Click
    - Properties of the widgets get updated on the right pane i.e. 'Properties Table.' and get highlighted on the screenshot screen.


fig.2 Layout Inspector

fig.3 Layout Inspector with Properties

RecyclerView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/percentList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
RecyclerView Item:

<android.support.percent.PercentRelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fifty_huntv"
        android:background="#ff7acfff"
        android:text="20% - 50%"
        android:textColor="@android:color/white"
        style="@style/STYLE_PERCENT_TV"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="50%" />
    <TextView
        android:layout_toRightOf="@id/fifty_huntv"
        android:background="#ffff5566"
        android:text="80%-50%"
        style="@style/STYLE_PERCENT_TV"
        app:layout_heightPercent="80%"
        app:layout_widthPercent="50%" />


</android.support.percent.PercentRelativeLayout>


Its an amazing tool to analyse the screen UI for the developers with all the information available on single click. Simply great.



2. How to change the DPI of the Phone using ADB?

Many times in our development phase we want to check the look of Android UI on low/high-end devices. Changing the DPI could come in handy in such cases.

So let get started.

Step 1: Find out your phone's dpi using the below command of adb shell. Search for 'mBaseDisplayInfo='. And then search for density within it. Save it for the future to revert our DPI
adb shell dumpsys display

Step 2: Search for 'mBaseDisplayInfo' and 'density' as shown in fig.4


fig.4 Display Density
Step 3: Finally enter below adb command to change the dpi. (fig.5) with 200dpi,420dpi and 600dpi respectively

adb shell wm density 150



 


Note: If the changes do not reflect you can also try:
adb shell wm density 150 && adb reboot

That it, the screen will be reloaded and icon sizes will change to withstand the density specified in the command.


For more updates follow us on -  
Twitter

Last Updated: October 20, 2016

Things every android developer should know - part 3

Description: In this post I'm gonna demonstrate some useful tips which we could come handy in our app development life cycle

Also check out Part 1 and Part 2.

So let 's get started.


1. Grant all permissions at once in Marshmallow and above.  

As we know marshmallow compatible apps require permissions. So we normally show permission dialog to the user asking to grant us. That's fine. But every time clicking that 'allow' feels annoying for developers.

So the idea is to allow all the permissions at once without every time clicking the allow button.

Below  shell script will help to make it happen flawlessly.
#!/bin/sh

#add your package_name
PACKAGE=com.app.code2concept

#create array with all the permission you need to enabled    
PKG_ARRAY='android.permission.CALL_PHONE
        android.permission.GET_ACCOUNTS
        android.permission.READ_SMS
        android.permission.READ_CONTACTS
        android.permission.ACCESS_FINE_LOCATION
        android.permission.CAMERA
        android.permission.WRITE_EXTERNAL_STORAGE'

#lets exceute our command
for permissions in $PKG_ARRAY; 
do
 echo $permissions + ' granted'
 adb shell pm grant $PACKAGE $permissions
done

echo 'Bingo its done'
OUTPUT:
$ sh grant_all_permissions.sh
android.permission.CALL_PHONE +  granted
android.permission.GET_ACCOUNTS +  granted
android.permission.READ_SMS +  granted
android.permission.READ_CONTACTS +  granted
android.permission.ACCESS_FINE_LOCATION +  granted
android.permission.CAMERA +  granted
android.permission.WRITE_EXTERNAL_STORAGE +  granted
Bingo its done'

Before


After





2. Battery Historian

Battery historian translate the battery stats into visualization form thereby helping us to figure out whats the cause and how we can optimized our battery usage.

Pre-requisite:
1. 'adb' is configured
2. Devices is detectable using 'adb devices' command
3. Python(2.7)  is install and path is set.

Step 1: Reset the battery stats to fetch fresh info using below
adb shell dumpsys batterystats --reset

Note: Disconnect phone and explore the app for few minutes and connect again

Step 2: Capture 'batterystats' using below command
adb shell dumpsys batterystats > batterystats.txt

Note: The command creates a file name 'batterystats.txt' into the current directory

Step 3: Clone or download the Github repo of 'Battery Historian' from Here. You will find a python script at path '../battery-historian/scripts/historian.py'

Note: You can keep both 'historian.py' and 'batterystats.txt' in the same folder for ease

Step 4: Finally let execute the python script against our 'batterstats.txt' as input as show below
python historian.py batterystats.txt > batterystats.html
This will create 'battertstats.html' fig.1 which we can use to analyse the battery usage as shown HERE.

Historian
fig.1

Last Updated: April 17, 2016

Things every android developer should know - part 2

Description: In the post, we'll continue the legacy of  Part 1 :-). Below are some tools provided by Google Android which is helpful for Android developers during the development and debugging session of the Production app issues

So let's get started :-)





Note: If you have missed part 1. Please refer here

1. Capture or record screen without any external app.

Often we are required to take snapshots of the app's screen or even record a video to show some features to colleagues QA or Clients. It comes in handy very often.

Step 1: Simply connect your device. Open the Android Monitor from Android Studio you'll see as fig.1.
http://code2concept.blogspot.in/
fig.1
Step 2: Now, you can open your app and click on the camera icon from the Android monitor located in the extreme top-left corner to capture any screen you want. Bingo !!!

For video: Click the video icon below the camera icon. Enter the resolution with multiples of 16x. fig.2. That's it. It'll start recording your actions on the app.

http://code2concept.blogspot.in/
fig.2



2. How to find layout boundaries?

Layout boundaries are very useful when we develop our UI components. It gives a real sense of layout, thereby letting us study the arrangement of different widgets in the layout.

Step 1: Open Settings - Developer Options - Show layout boundaries. From drawing section

https://www.linkedin.com/in/nitesh-tiwari-b5032a74
fig.3.LinkedIn app

fig.3. A Simple analysis of pencil icon. (without opening our layout)

1. The Edit pencil icon has some padding to it. 
2. It's aligned to the top-right corner of its parent layout.

Really awesome.





3. How to debug obfuscated code using proguard tool?

Note: This tool is inbuild provided by Google Android Sdk for developers and is helpful during debugging for live issues 

As we know, code is obfuscated when we build our app with Proguard enabled. We often come in contact with obfuscated code in our app while debugging the stack trace of the crashes.

So decoding is very much needed to study the stack trace. Android builds a file called "mapping.txt" which serves as the key ingredient to decode, in a combination with "retrace".

In Windows

Step 1: Go to  (android-studio-install-dir-path)\tools\proguard\bin  open "proguardgui.bat"  fig.4

fig.4
Step 2: Click on "ReTrace" fig.5. and upload your "mapping.txt" file from app/build/outputs/mapping/.../mapping.txt   and the obfuscated code file (e.g: crash.txt). You can also simply paste the stack trace in the box provided.

http://code2concept.blogspot.in/
fig.5
You can also use command line code to do that.

\tool\proguard\bin> retrace.bat -verbose   (path_to_mapping.txt)\mapping.txt  (path_to_stacktrace)\crash.txt


For more updates follow us on -  Twitter

#codingIsAnArt
#coderconsole

Last Updated: February 09, 2016

Things every android developer should know - part 1



Description: In this post, I'm gonna demonstrate tools that help solve some common problems while app development & help increase the speed as well.

So let's get started :-)


1. How to run app on phone without USB cord.(need USB initially to make connection

Note: Android Studio has provided a more sophisticated option to connect without USP using wireless debugging. Do check out the blog


Step 1: Connect the device with the cord to your system. Ensure that USB debugging is enabled from Developer options. Open cmd(windows) or Terminal(Linux) run the command. You'll find the connected device.
adb kill-server && adb devices
Step 2: Run the next command to restart in tcp mode on port 5555
adb tcpip 5555
Step 3: Now disconnect your device from the system and note down your ip address of the phone from Setting > About Phone > Status

E.g It could be something like 192.168.0.3(IP address) Now run the final command by replacing it with your IP address
adb connect 192.168.0.3:5555
Bingo we're done now your device is connected and you can run it wirelessly :-)

2. How to find SHA1 key from android studio?

SHA1 key is needed in many different apps containing maps or social sites authentication or using any Google apps and services. It's super useful. So the simplest way to get that is using Android Studio.

Step 1: Select the Gradle projects from the right pane and expand Tasks > Android> signingReport. (fig.1).

Note: If you do not find your project in Gradle Projects sync the project from Android Studio.

Gradle Project
fig.1


3. Best way to create icons for android app using vector asset.

Many times in our development we need icons for small things with varied colors or shape. Using Vector Asset in Android Studio we can create our icons with super ease.

Step 1: Right-click on app > New > Vector Asset you'll see Fig. 3. You can choose Material Icons which contains a whole lot of icons in different categories. This will create <vector> for the icon you have selected. (fig.4) in drawable folder

Vector Asset
fig.3
Vector Asset for the icon
Vector xml

fig.4
Step 2: Awesome now just we can simply set it to background or src of ImageView and other widgets.


For more updates follow us on -  Twitter

#codingIsAnArt
#coderconsole

Last Updated: December 19, 2015

Android Studio Flavors Demo

Description: In this post I'm gonna explain and show you guys how to use flavors in android studio.

Android Studio's flavors help as totally avoid chaos in code by separating our release code setup and staging code setup or by creating free/premium version for the same code base.

Really awesome :-)

Lets get started by creating two flavors for our project i.e prod and stag and find how it actually works!!!

Here we goo.



Step 1: Add productFlavors in your  app's build.gradle  within android section.

productFlavors{
    prodFlavors{

    }

    stageFlavors{

    }
}

*Just sync the gradle or rebuild the project you will find variants for two flavors in "Build Variants"(fig.1)















                                      (fig.1)


Step 2: Now let's create the folder structure for flavors to use prod and stage flavors similar to the structure of the main.


(Here we have created the folder structure same as the main i.e containing java and res folders respectively)
(fig.2)




Step 3: Lets add a constant file containing our dummy values.Thus we can easily switch the build variant & our constants values get changed as per the build variant selected.

Note: Always change the "Build Variant" when ever you want to change any thing within the flavors code base. (as shown in fig.1)













                                   (fig.3)

Step 4: Bingo !!!Final code and output.

In production flavor:

public class Constant {
    public static final String FLAVOUR_ID = "Woot !!! This is production setup";
}


In staging flavor
public class Constant {
    public static final String FLAVOUR_ID = "Woot !!! This is staging setup";
}



MainActivity:

public class MainActivity extends AppCompatActivity {

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

        //This is where by just changing by build variant we can change our setup easily
        TextView flavourType = (TextView)findViewById(R.id.flavourType);
        flavourType.setText(Constant.FLAVOUR_ID);

    }
}

How to change configuration of the build as per the variant? - (listed below)

productFlavors{

    prodFlavors{
        applicationId "com.buildvariant.prod"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 2
        versionName "1.1"
 
}

    stageFlavors{
        applicationId "com.buildvariant.stage"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 2
        versionName "1.1"
    }
}

Thus we can change our project setup thereby avoiding unnecessary chaos by separating our production setup code against staging.

Awesome!!!Android.

Output:


 


Last Updated: October 21, 2015

Android support v7 palette demo

Description: In this post I'm gonna show you how to use android's support library v7 palette for extracting color from bitmap. Its can have variety of use-cases like making the background of the profile image somewhat similar to profile image or changing the whole UI as per the bitmap into the screen. Really Awesome !!!

Github project here

Lets get started.



Step 1: Add this into build.gradle.

compile 'com.android.support:palette-v7:+'


Step 2: Pass the bitmap into palette to get List<Palette.Swatch> as shown below.

Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
    @Override    public void onGenerated(Palette palette) {
        swatchesList = palette.getSwatches();

        }
    }
});




Step 3: Here we have used CountDownTimer to display the RGB of the bitmap into the background of parent layout after the interval of 1sec. As shown below

mainContainer.setBackground(AppUtils.createGradient(swatch.getRgb()));




Steps 4: Lets combine everything :-)


public class MainActivity extends AppCompatActivity implements INotifyTimer {

    private static final String TAG = MainActivity.class.getName();

    private List<Palette.Swatch> swatchesList;
    private CountDownTimerPalette countDownTimer;

    private int size ;

    private RelativeLayout mainContainer;
    private ImageView circularImageView;

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

        init();

        extractColorFromBitmap();
    }

    private void init() {
        mainContainer = (RelativeLayout)findViewById(R.id.mainContainer);
        circularImageView = (ImageView)findViewById(R.id.circularImageView);
    }

    private void extractColorFromBitmap() {

        Bitmap bitmap = AppUtils.getCircleBitmap(BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.capture_palette));
        circularImageView.setImageBitmap(bitmap);

        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override            public void onGenerated(Palette palette) {
                swatchesList = palette.getSwatches();

                if (swatchesList != null && swatchesList.size() > 0) {
                    countDownTimer = new CountDownTimerPalette(1000 * swatchesList.size(), 1000, MainActivity.this);
                    countDownTimer.start();
                }
            }
        });
    }

    @Override    public void onTick(int tick) {

        Palette.Swatch swatch = swatchesList.get(tick - 1);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mainContainer.setBackground(AppUtils.createGradient(swatch.getRgb()));
        }else {
            mainContainer.setBackgroundDrawable(AppUtils.createGradient(swatch.getRgb()));
        }

    }

    @Override    public void onFinish() {
        countDownTimer.start();
    }


    @Override    protected void onDestroy() {
        super.onDestroy();

        if (countDownTimer != null){
            countDownTimer.cancel();
        }
    }

}


Output:


 

Last Updated: October 14, 2015

Android Multiple row layout using RecyclerView

Description: In this post I'm gonna show you how we can have multiple row layout in Android's Material Design  RecyclerView  using   getItemViewType.

compile 'com.android.support:cardview-v7:23.0.0'
compile 'com.android.support:recyclerview-v7:23.0.0'

GitHub Project HERE

So lets get started :-)



Step 1:
Create Recycler Adapter by overriding getItemViewType method and giving the type for different layout as shown below.


@Override

public int getItemViewType(int position) {

    MultipleRowModel multipleRowModel = multipleRowModelList.get(position);

    if (multipleRowModel != null)
        return multipleRowMod.type;

    return super.getItemViewType(position);
}
Step 2: Create a viewHolder as per viewType .  We can create different row layout using viewType .

Note: viewType in onCreateviewholder is retured from getItemViewType in Step 1.
@Override
public MultipleRowViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = null;

    if (viewType == AppConstant.FIRST_ROW)
        view = inflater.inflate(R.layout.view_row_first, parent, false);
    else if (viewType == AppConstant.OTHER_ROW)
        view = inflater.inflate(R.layout.view_row_other, parent, false);

    return new MultipleRowViewHolder(view, viewType);
}

Step 3: Lets integrated all this in one RecyclerView adapter.

public class MultipleRowAdapter extends RecyclerView.Adapter<MultipleRowViewHolder> {

    private LayoutInflater inflater = null;
    private List<MultipleRowModel> multipleRowModelList;

    public MultipleRowAdapter(Context context, List<MultipleRowModel> multipleRowModelList){
        this.multipleRowModelList = multipleRowModelList;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public MultipleRowViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = null;

        if (viewType == AppConstant.FIRST_ROW)
            view = inflater.inflate(R.layout.view_row_first, parent, false);
        else if (viewType == AppConstant.OTHER_ROW)
            view = inflater.inflate(R.layout.view_row_other, parent, false);

        return new MultipleRowViewHolder(view, viewType);
    }

    @Override
    public void onBindViewHolder(MultipleRowViewHolder holder, int position) {
        holder.multipleContent.setText(multipleRowModelList.get(position).modelContent);
    }

    @Override
    public int getItemCount() {
        return (multipleRowModelList!= null && multipleRowModelList.size() > 0 ) ? multipleRowModelList.size() : 0;
    }

    @Override
    public int getItemViewType(int position) {

        MultipleRowModel multipleRowModel = multipleRowModelList.get(position);

        if (multipleRowModel != null)
            return multipleRowModel.type;

        return super.getItemViewType(position);
    }

}





Step 4: Finally our MainActivity looks something like this.

public class MainActivity extends AppCompatActivity {

    private RecyclerView multipleRowRecyclerView;
    private MultipleRowAdapter multipleRowAdapter;

    private List<MultipleRowModel> multipleRowModelList = new ArrayList<>();

    @Override

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

        multipleRowRecyclerView = (RecyclerView)findViewById(R.id.multipleRowRecyclerView);
        multipleRowRecyclerView.setHasFixedSize(true);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        multipleRowRecyclerView.setLayoutManager(linearLayoutManager);
        multipleRowRecyclerView.setItemAnimator(new DefaultItemAnimator());

        fillAdapter();

        multipleRowAdapter = new MultipleRowAdapter(MainActivity.this, multipleRowModelList);

        multipleRowRecyclerView.setAdapter(multipleRowAdapter);
    }

    private void fillAdapter() {

        int type;

        String content;

        for (int i = 0; i < 10; i++) {

            if (i == 0 || i == 5 || i == 9) {
                type = AppConstant.FIRST_ROW;
                content = "Type 1: This is Multiple row layout";
            } else {
                type = AppConstant.OTHER_ROW;
                content = "Type 2";
            }

            multipleRowModelList.add(new MultipleRowModel(type , content));
        }
    }
}


GitHub Project HERE

Sample Output :


Last Updated: July 28, 2015

Android InstrumentationTestCase for Network call Demo.

Description: In this post I'm gonna show you how we can create a testcase for our network calls using android InstrumentationTestCase I'm gonna use CoutDownLatch simply becausein most of our app we make network call on background thread. CountDownLatch gives as option to run call single threaded.

So lets get started. :-)



Step 1: Create a class NetworkCallTest extends InstrumentationTestCase within your 'app/src/androidTest/java/<package_name>


Step2: Create any method within the class prefixed as test e.g: testNetworkCall. For serial exceution you can have name as test1,test2,test3 and so on.

Note: test case are event driven if methods are not prefixed with test its not gonna execute.
public void testNetworkCall(){}


Step3: Lets create  a dummy network call for demo using aquery and countdown latch.
public class NetworkCallTest extends InstrumentationTestCase {

    @Override
    public void setUp() throws Exception {
        super.setUp();
    }

    public void testNetworkCall(){
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(new NetworkRunnable(countDownLatch)).start();
    }

    private class NetworkRunnable implements Runnable {

        private CountDownLatch countDownLatch;

        public NetworkRunnable(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {

            AQuery aQuery = new AQuery(getInstrumentation().getContext());
            aQuery.ajax( "http://jsonplaceholder.typicode.com/posts" , JSONArray.class , new AjaxCallback<JSONArray>(){
                @Override
                public void callback(String url, JSONArray jsonArray, AjaxStatus status) {

                    assertNotNull("response array  is null", jsonArray);

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

                        JSONObject object = jsonArray.optJSONObject(i);

                        assertNotNull("jsonObject is null", object);

                        String userId = object.optString("userId");
                        assertTrue("User Id is empty" , !TextUtils.isEmpty(userId));

                        String id = object.optString("id");
                        assertTrue("Id is empty" , !TextUtils.isEmpty(id));

                        String title = object.optString("title");
                        assertTrue("title is empty" , !TextUtils.isEmpty(title));

                        String body = object.optString("body");
                        assertTrue("body is empty" , !TextUtils.isEmpty(body));
                    }

                    countDownLatch.countDown();


                }
            });
        }
    }
}




Step4:Run the test case . Click to know HOW TO RUN TESTCASES ?.









Android How to run Instrumentation testCases ?

Description: In this post I'm gonna show you how we can run the test case in android.I have posted snapshot of each step and how we can filter the testcase based on class -methods respectively.

So lets get started.




Step 1: Open Edit Configuration from Run menu of android studio.












Step 2: Create new Configuration by clicking icon + and select new Android Tests.



Step 3: Select module.You can also select different testType like class,package,method or module.






Step 4: Apply n save.Now you have saved the configuration.You testcase configuration is ready!!!

Note: You can now also right the particular testcase and run it direclty after configuration.