Showing posts with label gradle. Show all posts
Showing posts with label gradle. Show all posts

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 ?.









Last Updated: May 26, 2015

Lollipop SwipeRefreshLayout with loader


Description: In this post I'm gonna show you how to use Lollipop's SwipeRefreshLayout using loader in android.It demostrate use of swipe refresh with loader's restartloader() method.

Github project for the same here


Step 1: Add the dependency in build.gradle
dependencies {
    compile 'com.android.support:appcompat-v7:21.0.2' // or your updated version
}
Step 2: Create Layout to use swipeRefreshLayout.It can be wrap over Scrollview or ListView.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/video_listView"
        android:layout_width="match_parent"
        android:smoothScrollbar="true"
        android:layout_height="match_parent" />

</android.support.v4.widget.SwipeRefreshLayout>


Step 3:Finally lets wrap everthing in code.

Note: Here loader is used  to fetch the videos names from phone and a swipeRefreshLayout functionality is added to update the content.

public class MainActivity extends FragmentActivity implements  LoaderManager.LoaderCallbacks<Cursor>  ,SwipeRefreshLayout.OnRefreshListener {

    private static final int LOADER_ID = 100;
    private ListView videoList;
    private SwipeRefreshLayout swipeContainer;
    private Context context;
    private SwipeAdapter swipeListAdapter;
    private String TAG = MainActivity.class.getName();

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

        context         = MainActivity.this;
        videoList       = (ListView) findViewById(R.id.video_listView);
        swipeContainer  = (SwipeRefreshLayout) findViewById(R.id.swipe_container);


        swipeContainer.setColorSchemeResources(
                R.color.swiperedcolor,
                R.color.swipegreencolor,
                R.color.swipeyellowcolor,
                R.color.swipebluecolor);


        swipeListAdapter = new SwipeAdapter(context , null  , 0);
        videoList.setAdapter(swipeListAdapter);


        swipeContainer.setOnRefreshListener(this);

        getSupportLoaderManager().initLoader(LOADER_ID, null, this);

    }


    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        Log.d(TAG , "||onCreateLoader called||");
        return new CursorLoader(context ,MediaStore.Video.Media.EXTERNAL_CONTENT_URI ,null , null , null , MediaStore.Video.Media.TITLE + " collate nocase ");
    }


    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        if (swipeListAdapter != null && cursorLoader != null){

            Log.d(TAG , "||onLoadFinished called||");

            swipeListAdapter.swapCursor(cursor);

            swipeContainer.post(new Runnable() {
                @Override
                public void run() {
                    swipeContainer.setRefreshing(false);
                }
            });
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        if (swipeListAdapter != null) {
            Log.d(TAG , "||onLoaderReset called||");
            swipeListAdapter.swapCursor(null);
        }
    }


    /**
     * Whenever swipe refresh starts we get callback here.Here we can place our logic.
     */
    @Override
    public void onRefresh() {
        Log.d(TAG , "||onRefresh called||");
        getSupportLoaderManager().restartLoader(LOADER_ID , null ,this);
    }



    private class SwipeAdapter extends CursorAdapter{


        private VideoViewHolder videoViewHolder;

        public SwipeAdapter(Context context, Cursor c, int flags) {
            super(context, c, flags);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            videoViewHolder = new VideoViewHolder();
            View convertView = LayoutInflater.from(context).inflate(R.layout.row_swipe_refresh , parent , false);
            videoViewHolder.videoTitleTextView = (TextView) convertView.findViewById(R.id.titleTv);

            convertView.setTag(videoViewHolder);

            return convertView;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            videoViewHolder = (VideoViewHolder) view.getTag();
            videoViewHolder.videoTitleTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE)));

        }
    }


    private class VideoViewHolder {
        private TextView videoTitleTextView;
    }
}


Result:(Displays the names of videos in phone using loader)