Importance of Communication Skills in Software Engineering

Today I am in different mood. I am going to share something different today. Yes, somewhat on a non-technical point but that is more important in day to day life of any software engineer or developer, QA or any other IT guy.

Before moving further on same topic, I just want to remind you that i hope you gone thorough my last technical blog about MVVM Architecture. If not yet I request you to go and check out that will definitely help you to clear your doubts. Let’ continue on this 🙂

You must think that what I am talking about. Right, I am not going to waste my time in storytelling and come to the main topic is communication. You heard right, soft skill is most of the important part in every day that we all know.

Great communication is the most important characteristic for success as a software engineer. For most people, this may sound counterintuitive. Don’t engineers spend all day coding? A big part of the day-to-day job of software engineering is not spent knee-deep in code but rather working with a variety of folks across the company. Can you spend your day without communicating with your colleague?  Not at all.  Today we are going to understand the communication part. I am more excited about this today Let’s go started.

Today’s learning:

  • What is communication?
  • Importance in software industry
  • Types of communication
  • Tips to become effective communicator

What is communication?

The imparting or exchanging of information by speaking, writing, or using some other medium. Or we can say, sending or receiving information, such as phone lines or computers.

Importance in software industry

However technically sharp a person is, he will be neither recognized nor appreciated for his/her efforts unless s/he masters communication and interpersonal skills.


Well, one may have a strong argument that what role these soft skills play in professional development. As long as s/he is thorough with the knowledge to deliver the tasks, what is the need to ensure having proper communication and interpersonal skills? Do they have any major role to play in the IT field, especially for developers? Yes, they do – let’s dive into the details.

Research shows that poor interpersonal skills are the number one reason why people don’t get along, don’t get promoted, or, even worse, lose their jobs.
To become a successful professional developer, a person needs to master these communication and interpersonal skills.

Any guy should be able to share his knowledge, message any information effectively with their colleague. Other people can understand the requirement, issue or challenges what you are facing or what you are trying to share it. If other people can’t understand your input then it will create a negative impact. You and your team will not get the desired output as per the expectation.

This includes all sorts of communications e.g.

  • Online chat
  • Audio/video call
  • Email /message communications
  • Social media interactions
  • Others

Types of communication

In preparing for my blog, I’ve been thinking more and more about the different types of communication. Before my exploration on this in death I have outlined four (4) types of communication, but now but I believe there are five types of communication: verbal, non-verbal, written, listening, and visual. Let’s see in details

Verbal communication:

Verbal communication occurs when we engage in speaking with others. It can be face-to-face, over the telephone, via Skype or Zoom, etc. Some verbal engagements are informal, such as chatting with a friend over coffee or in the office kitchen, while others are more formal, such as a scheduled meeting. Regardless of the type, it is not just about the words, it is also about the caliber and complexity of those words, how we string those words together to create an overarching message, as well as the intonation (pitch, tone, cadence, etc.) used while speaking. And when occurring face-to-face, while the words are important, they cannot be separated from non-verbal communication.

Non-verbal communication:

What we do while we speak often says more than the actual words. Non-verbal communication includes facial expressions, posture, eye contact, hand movements, and touch. For example, if you’re engaged in a conversation with your boss about your cost-saving idea, it is important to pay attention to both the their words and their non-verbal communication. Your boss might be in agreement with your idea verbally, but their nonverbal cues: avoiding eye contact, sighing, scrunched up face, etc. indicate something different.

Written communication:

Whether it is an email, a paper post , a report, a Facebook post, a Tweet, a contract, etc. all forms of written communication have the same goal to disseminate information in a clear and concise manner – though that objective is often not achieved. In fact, poor writing skills often lead to confusion and embarrassment, and even potential legal jeopardy. One important thing to remember about written communication, especially in the digital age, is the message lives on, perhaps in perpetuity. Thus, there are two things to remember: first, write well – poorly constructed sentences and careless errors make you look bad; and second, ensure the content of the message is something you want to promote or be associated with for the long haul.

Listening:

The act of listening does not often make its way onto the list of types of communication. Active listening, however, is perhaps one of the most important types of communication because if we cannot listen to the person sitting across from us, we cannot effectively engage with them. Think about a negotiation – part of the process is to assess what the opposition wants and needs. Without listening, it is impossible to assess that, which makes it difficult to achieve a win/win outcome.

Visual communication:

We are a visual society. Think about it, televisions are running 24/7, Facebook is visual with memes, videos, images, etc., Instagram is an image-only platform, and advertisers use imagery to sell products and ideas. Think about from a personal perspective – the images we post on social media are meant to convey meaning – to communicate a message. In some cases that message might be, look at me, I’m in Italy or I just won an award. Others are carefully curated to tug on our heartstrings – injured animals, crying children, etc.

Tips to become effective communicator

A person should be effective communicator, and create his/her positive impression and for that they should below notes,

  • Approachable and helpful
  • Problem-solving attitude and skills
  • Effective time management
  • Softness in writing tone
  • Critical and analytical  thinking
  • Improve vocabulary

Understanding how you communicate is the first step to communicating more effectively. You can easily look online for communication courses. There are a variety of credit and non-credit course available to help you improve your communication skills.

Hope this helps you!

Feel free to reach me at any time on
LinkedIn
Github
ChintanKhetiya -Blog
Instagram AASE-ChintanKhetiya

Thank you!
Happy Coding 🙂

MVVM-Architecture-All-In-One

I have been searching for the best practices of Kotlin in MVVM architecture. I’ve decided to write this post. If you don’t know about the LiveData please check my last blog on Live Data and Lifecycle.

 I chintan khetiya, writing this blog to share my knowledge on MVVM architecture.

This is a very simple All in One using MVVM Architecture, DataBinding, Room Database, API Call and LiveData and other important elements in Android. It loads the data from the web service or local Database (Room) using DataBinding “@=”, stores it in LiveData, and displays back on the UI.

This example is for those who want to learn the easiest way to fetch the data from online or offline and display the data. This is useful in many ways such as Saving Development Time, Code Reusability, Validations etc.

So let’s get started on using these technologies together in a single application:

1. What is MVVM Architecture?
2. What is DataBinding?
3. What is LiveData, LifeCycle and that Advantages ?
4. What is Room Database and Coroutines?
5. Advantages of Room over SQLite
6. Important Annotations in Room
7. How to call the web-service
8. Implementation Step-by-Step
9. All in one – Full example
10. Conclusion

1. What is MVVM Architecture?

MVVM is a design pattern for organizing GUI applications that has become popular on Android. MVVM architecture is a Model-View-ViewModel architecture that removes the tight coupling between each component. Most importantly, in this architecture, the children don’t have the direct reference to the parent, they only have the reference by observables.

This concept will introduce you to the main 3 components of MVVM, the View, Model, and ViewModel.

Model:

  • It represents the data and the business logic of the Android Application. It consists of the business logic – local and remote data source, model classes, and repository.
  • What should go in your model layer and what should not.
  • Benefits of model isolation and how it affects testing.

View:

  • It consists of the UI Code(Activity, Fragment), XML. It sends the user action to the ViewModel but does not get the response back directly. To get the response, it has to subscribe to the observables which ViewModel exposes to it.
  • How it interacts with the ViewModel.

ViewModel

  • It is a bridge between the View and Model(business logic). It does not have any clue which View has to use it as it does not have a direct reference to the View. So basically, the ViewModel should not be aware of the view who is interacting with. It interacts with the Model and exposes the observable that can be observed by the View.
  • How it supports the View, by providing actions and observable state.
  • Interactions with the Model.
  • Isolation from the View.

2. What is DataBinding?

The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically and many more.

3. What is LiveData, LifeCycle and Advantages?

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

Below are the advantages: You can check my previous blog Live Data here.

Ensures your UI matches your data state:

LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there’s a change.

No memory leaks:

Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.

No crashes due to stopped activities:

If the observer’s lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.

No more manual lifecycle handling:

UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.

Always up to date data:

If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.

Proper configuration changes:

If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.

Sharing resources:

You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object. For more information, see Extend LiveData.

4. What is Room Database and Coroutines?

Room Database:

Database layer on top of SQLite database that takes care of mundane tasks that you used to handle with an SQLiteOpenHelper. Database holder that serves as an access point to the underlying SQLite database. The Room database uses the DAO to issue queries to the SQLite database.

Entity:

When working with Architecture Components, this is an annotated class that describes a database table.

SQLite database:

On the device, data is stored in an SQLite database. For simplicity, additional storage options, such as a web server, are omitted. The Room persistence library creates and maintains this database for you.

DAO:

Data access object. A mapping of SQL queries to functions. You used to have to define these painstakingly in your SQLiteOpenHelper class. When you use a DAO, you call the methods, and Room takes care of the rest.

Repository:

A class that you create, for example using the WordRepository class. You use the Repository for managing multiple data sources.

Coroutines:

Coroutines are a great new feature of Kotlin which allow you to write asynchronous code in a sequential fashion. … However, like RxJava, coroutines have a number of little subtleties that you end up learning for yourself during development time, or tricks that you pick up from others.

5. Advantages of Room over SQLite

  • In case of SQLite, There is no compile time verification of raw SQLite queries. But in Room there is SQL validation at compile time.
  • As your schema changes, you need to update the affected SQL queries manually. Room solves this problem.
  • You need to use lots of boilerplate code to convert between SQL queries and Java data objects. But, Room maps our database objects to Java Object without boilerplate code.
  • Room is built to work with LiveData and RxJava for data observation, while SQLite does not

6. Important Annotations in Room

7. How to call the web-service?

A web service is a standard for exchanging information between different types of applications irrespective of language and platform. There are SOAP and RESTful web service.
Most of the application use the REST webservice which accept and return the JOSN data.

8. Implementation Step-by-Step

Add require dependencies to your project

dependencies {
    ...
    ...
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'androidx.core:core-ktx:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    def roomVersion = '2.3.0'
    def archLifecycleVersion = '2.2.0'
    def coreTestingVersion = '2.1.0'
    def materialVersion = '1.3.0'
    def coroutines = '1.3.8' // Room components  
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    androidTestImplementation "androidx.room:room-testing:$roomVersion"
    androidTestImplementation "androidx.arch.core:core-testing:$coreTestingVersion"
    implementation "androidx.room:room-ktx:$roomVersion"
    implementation 'org.conscrypt:conscrypt-android:2.2.1' // Kotlin components  
    api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines"
    api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines" // Material design  
    implementation "com.google.android.material:material:$materialVersion"
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.multidex:multidex:2.0.1' /*Retrofit & GSON Parsing*/
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2' /*Shimmer Animation*/
    implementation 'com.github.sharish:ShimmerRecyclerView:v1.3'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    /*Image Loading*/
    implementation 'com.github.bumptech.glide:glide:4.11.0' /*Multidex to support 64K Function*/
    implementation 'androidx.multidex:multidex:2.0.1' /*Dexter - Runtime Permission Lib*/
    implementation 'com.karumi:dexter:6.1.2'
    kapt 'com.android.databinding:compiler:3.1.4'
    /*Viewmodel Life cycle and others*/
    implementation 'androidx.lifecycle:lifecycle-viewmodel:2.3.1'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    kapt "androidx.lifecycle:lifecycle-compiler:$archLifecycleVersion"
    implementation 'androidx.core:core-ktx:1.5.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
    implementation 'androidx.lifecycle:lifecycle-common-java8:2.3.1' /*Pull to refresh*/
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'...
        ...
}

Implement Data binding

 dataBinding { enabled = true }

Create project structure

Implement the Retrofit to fetch the remote data

private val objRetrofit = Retrofit.Builder()
.baseUrl(APIConstant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(onGetBuilder().build())
.build()

Implement the Room Database to fetch the local data

@Database(entities = arrayOf(UniversitiesEntity::class), version = 1, exportSchema = true)  
public abstract class UniversitiesDatabase : RoomDatabase() {  
  
    abstract fun UniversitiesDao(): UniversitiesDao  
  
  companion object {  
        @Volatile  
  private var INSTANCE: UniversitiesDatabase? = null  
  
 fun getDatabaseClient(context: Context): UniversitiesDatabase {  
            return INSTANCE ?: synchronized(this) {  
  val instance = Room.databaseBuilder(  
                    context.applicationContext,  
                    UniversitiesDatabase::class.java,  
                    "roomdb_universities"  
  )  
                    .build()  
                INSTANCE = instance  
  // return instance  
  instance  
  }  
  }  
 }  
}

Create the UI to display the data

<?xml version="1.0" encoding="utf-8"?>  
<layout xmlns:tools="http://schemas.android.com/tools">  
 <androidx.appcompat.widget.LinearLayoutCompat 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"  
  android:background="@android:color/white"  
  android:orientation="vertical"  
  tools:context=".java.MainJavaActivity"  
  tools:ignore="PrivateResource">  
  
 <include  android:id="@+id/layToolbar"  
 layout="@layout/row_toolbar" />  
 <View style="@style/ListDivider"  android:background="@drawable/shape_shadow" />  
  
 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout  android:id="@+id/swipeContainer"  
  android:layout_width="match_parent"  
  android:layout_height="match_parent">  
  
 <com.cooltechworks.views.shimmer.ShimmerRecyclerView xmlns:app="http://schemas.android.com/apk/res-auto"  
  android:id="@+id/rv_universities_list"  
  android:layout_width="match_parent"  
  android:layout_height="match_parent"  
  app:shimmer_demo_layout="@layout/row_universities_item_shimmer"  
  app:shimmer_demo_layout_manager_type="linear_vertical" />  
  
 </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>  
 <include  android:id="@+id/layNetworkLost"  
 layout="@layout/activity_network_lost"  android:visibility="gone" />  
  
 </androidx.appcompat.widget.LinearLayoutCompat></layout>  

Map the data with UI using MVVM pattern

class UniversitiesViewModel(application: Application) : AndroidViewModel(application) {  
    lateinit var liveDataUniversitiesAPI: MutableLiveData<List<UniversitiesEntity>>  
    lateinit var liveDataUniversitiesRoom: LiveData<List<UniversitiesEntity>>  
    lateinit var apiUniversities: UniversitiesAPIRepository  
  
  /*Init API Object*/  
  fun initAPI() {  
        apiUniversities = UniversitiesAPIRepository.getInstance()  
        liveDataUniversitiesAPI = apiUniversities.getUniversities()  
    }  
  
    fun insertData(context: Context, name: String, country: String, code: String) {  
        UniversitiesRoomRepository.insertData(context, name, country, code)  
    }  
  
    fun getUniversitiesList(context: Context): LiveData<List<UniversitiesEntity>> {  
        liveDataUniversitiesRoom = UniversitiesRoomRepository.getUniversitiesListFromRoom(context)  
        return liveDataUniversitiesRoom  
  }  
  
}

Add required permission in Androidmanifest.xml

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
 <uses-permission android:name="android.permission.INTERNET" />  
  
 <application  android:name=".utils.AppController"  
  android:usesCleartextTraffic="true"  
  android:allowBackup="true"  
  android:networkSecurityConfig="@xml/network_security_config"  
   />  

Add required configuration properties in build.gradle (app)

androidExtensions { experimental = true }  
testOptions {  
 unitTests.returnDefaultValues = true }  
 android { lintOptions { checkReleaseBuilds false  abortOnError false } }  

Run it!

9. All in one – Full example

Check out my blog ChintanKhetiya for more details and full source code you can get from my Github repository.

10. Conclusion

Hopefully, this guide should have helped you in making your tasks easier in terms of many things. This is a very simple example. It is all about the free API here I have used which returns the JSON list of Universities.

  1. If network available – Fetch the data from web services using Retrofit, store in Room Database, updating UI using LiveData and Data Binding.
  2. If the network not available – Check any local records found from Room Database, If yes then updating UI using LiveData and Data Binding.
  3. If the network not available – No local record found then updating UI with network lost screen
  4. You can also sort the list data with Sort by university name and sort by country parameters
  5. During the loading you can see the Shimmer animation also
  6. To get updated records from the API – Just do Swipe to refresh. In addition, If you lost the network you can fetch the records by tap on Retry button.

There all are basic things which gives you the practical idea and you can compare with your application requirement.

Hope this helps you!

Feel free to reach me at any time on
LinkedIn
Github
ChintanKhetiya -Blog
Instagram AASE-ChintanKhetiya

Thank you!
Happy Coding 🙂

Understanding LiveData- LifeCycle in Android

Hey Folks, After a long time I’m back with the new blog, That is all about the LiveData. Many of you have doubts about this area. I will try to explain all things step by step. I am very excited to share this content with you and hope you are also.

Before jump into the main section let’s understand what we will cover today.

  • What is LiveData?
  • What is LiveData Lifecycle?
  • What is the advantage of the Live Data Lifecycle ?
  • Real Example
  • How to create LiveData Objects?
  • How to observe LiveData Objects?
  • How to update LiveData Objects

What is Live Data?

Let’s first look at the definition mentioned in the official Android documentation:

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

LiveData  is part of Android Jetpack compose component

Let’s have a simpler definition now.

In simple words, LiveData is basically a data holder and it is used to observe the changes of a particular view and then update the corresponding change. It is lifecycle-aware i.e. whenever a data is updated or changed then the updates will be sent to only those app components which are in active state. If the app component is not active and in the future, if it becomes active, then the updated data will be sent to that app component. So, you need not worry about the lifecycle of the app component while updating data.

What is LiveData Lifecycle?

Defines an object that has an Android Lifecycle. Fragment and FragmentActivity classes implement LifecycleOwner interface which has the getLifecycle method to access the Lifecycle. You can also implement LifecycleOwner in your own classes.

What is the advantage of the Live Data Lifecycle ?

  • Ensures your UI matches your data state
  • No memory leaks
  • No crashes due to stopped activities
  • No more manual lifecycle handling
  • Always up to date data
  • Proper configuration changes
  • Sharing resources

Real Example

Updating the UI of the application due to change in some data is one of the most used tasks in Android. For example, whenever you like some post on Instagram, then the like count will be increased and also the color of the like button will be changed to red from white. So, here we are changing the UI based on some data and there are many other examples of these kinds of UI change due to some change in data in Android.

So, these changes in the views of your app can be carried out with the help of ViewModel and to make the working of a ViewModel easy, Google introduced the concept of LiveData. LiveData is a part of Android Jetpack and in this blog, we are going to understand the concept of LiveData in Android.

So, here are the things that will encourage you to use LiveData in your application:

  • You can use LiveData with libraries like Room Persistent Library, Coroutines, etc.
  • Once a data is modified/changed, the observers will be notified about the change
  • But before notifying the observers, LiveData will check if the observer is live or not. If it is live, then the notification will be sent otherwise not. In this way, the crash due to stopped activities will be stopped.
  • While using LiveData, you need not worry about unsubscribing any observers.
  • If the inactive observer will be resumed in future, then the latest data will be sent to that observer.
  • No need to worry about activity recreation due to screen rotation because only the updated data will be sent.

Now, I hope you are clear with the LiveData basic understanding, concept and in which case we can use this. I am pretty sure that you want to jump into the code now. Yeah, Let’s Go!

How to create LiveData Objects?

Here, we are going to use MutableLiveData that will be used for updating the name.

private MutableLiveData<String> name;

set the data in LiveData

Here, we need to change/update the data in LiveData. The MutableLiveData publicly exposes two methods i.e. setValue and postValue to set the data in LiveData.

  • If you are working on the main thread, then both setValue and postValue will work in the same manner i.e. they will update the value and notify the observers.
  • If working in some background thread, then you can’t use setValue. You have to use postValue here with some observer. But the interesting thing about postValue is that the value will be change immediately but the notification that is to be sent to observers will be scheduled to execute on the main thread via the event loop with the handler.
viewModel.name.setValue(/** updated data **/);
or
viewModel.name.postValue(/** updated data **/);

Return that data by some function:

public LiveData<String> getName(){
     return name; 
}

How to observe LiveData Objects?

Finally, you need to observe the data in some view by using observers. One thing to be noted here is that only those observers will be notified that are active. When an observer comes from an inactive to an active state, then the updated data will be sent to it.


viewModel.getName().observe(this, name -> {
     //do some UI updation or other tasks
}

Conclusion

So, in this blog, we learned about LiveData and how to use it. We saw that if there is a change in data then that data will be reflected to all the observers associated with it but it only notifies the changes to the observers that are live or in the active state and not to that observer that are in the inactive state.

I will write a full example on LiveData with the Room Database in next blog for better understanding.

Hope you liked this blog. To learn more about some of the cool topics of Android, you can visit my blog www.chintankhetiya.wordpress.com and please follow me on Instagram aase_chintankhetiya for all technical updates.

Keep Learning and sharing 🙂

Chintan Khetiya 

Android Basic Utils Function

Which is the major issue or difficulty developer face during development ? just ask your self and you will find that answer is Utils function which we are using in daily basis. We are doing coding whole day most of the conman things are repeated in all project or module , only some part of the unique code , view and logic which we added. Developer are so lazzy to write same code again and again and make create utils class to make reusable code. Here i am sharing list of function which we are using in daily basis in android application development which will save your time to find from Google or Stackoverflow and write in your utils class or java class. The main objective of this task is Reuse ability of code , Time saving , Easy & Less coding.

  • You have two ways to use this Utils function :

  1. JAVA File
  2. Live Template

Direct form JAVA file :

  • You just need to add my created Utils JAVA file in your <package> and access using class object. You can find 120+ utils function in java file but that is not mandatory to add all in your application you can remove list of function which is not useful for your application so that will not save unnecessary code. see below example to see “How to use this class in your activity class?”

public class MainActivity extends Activity {
private CKAndroidUtils objCKUtils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
…..
…..objCKUtils = new CKAndroidUtils(this);
if (objCKUtils.isNetworkAvailable()) {
….. //Do your task
}
}

Live Template :

  • Code completion can improve your productivity by reducing how much you have to type, but there are situations when a more powerful tool is needed. Thanks to Android Studio and IntelliJ, live templates make it much easier to focus on just the things you care about. You can read one of the grate article regarding Live Template . You have to create CKAndroidUtils snippet file (XML)  which contains your code in XML formate and that will be use to access the function using short cut key : Ctrl + Alt + Shift + J  FUNCTION NAME .

How to create your snippet & share with others :

  • Path : File > Settings > Editor > Live Template > .. You can see Add or remove snippet code or template group from “+” or “-“ from right side button.
  • Now choose Android group or own created template to add snippet code. That will ask you Abbreviation = Function name , Description = What function do, Template text = your code, Type = java , xml ,other. Apply > Ok Done!   Now search it using give short cut key and access function any where in your application.
  • Now you can share added snippet code to other developer and setup same file to get access.

Check out below steps to configure the XML :

1. Download CKAndroidUtils snippet file
2. Go to “/.Android Studio/config /templetes folder (by default is hide folder at user /dir)
i.e /home/sotsys073/.AndroidStudio/config/templetes
3. Paste “CKAndroidUtils” file in above /dir.
4. Restart android studio and check CKAndroidUtils is available in File >> Settings >> Live template >> CKAndroidUtils
5. Short cut to access function : Ctrl + Alt + Shift + J  FUNCTION NAMENow you  are able to add function in template and know how to use it . Download CKAndroidUtils.java file and create your snippet or use directly. Start it now!!! Hope this will relay helpful for all of you.

Note : Please add function which you are using in project and not listed in below list so that will be helpful for other

List of Utils Function

Index

Function Name

1

askToExit()

2

showYesNoDialog()

3

showOkDialog()

4

isNetworkEnable()

5

isLocationEnable()

6

showProgressDialog()

7

hideProgressDialog()

8

showToast()

9

hideSoftKeyboard()

11

openSoftKeyboard()

12

dpToPixel()

13

pixelToDp()

14

getDeviceDensity()

15

getScreenHeight()

16

getScreenWidth()

17

getScreenSize()

18

openDialer()

19

isPlayServiceExist()

20

setDynamicListViewHeight()

21

switchActivity()

22

callActivityForResult()

23

adjustImageOrientation()

24

getRotateBitmap()

25

getCropBitmapToSquare()

26

getRoundedCornerBitmap()

27

getResizedBitmap()

28

getBitmapFromDrawable()

29

getDrawableFromUrl()

30

getMaskedBitmap()

31

getMaskedImageByColor()

32

getStorageDirectory()

33

downloadImageFromUrl()

34

moveFile()

35

copyFile()

36

deleteFile()

37

createDirectory()

38

shareDefaultIntent()

39

shareImageviaIntent()

40

calculateInSampleSize()

41

loadBase64toImageView()

42

getFileFromPath()

43

getBitmapFromPath()

44

getFileFromBitmap()

45

sendMailFromGmail()

46

showFBUserProfile()

47

showTwitterUserProfile()

48

showInstagramUserProfile()

49

getImagePathFromUri()

50

getUriFromBitmap()

51

getBitmapFromFile()

52

drawableToBitmap()

53

saveBmpToJPG()

54

resizeImageScale()

55

isRemoteFileExists()

56

cropCenter()

57

getBlurImagFromBitmap()

58

getBlurImagUsingRenderScript()

59

getThumbnail()

60

getBlurImageUsingGaussianBlur()

61

isCameraExist()

62

getDistanceBetweenLocation()

63

getAddressFromLocation()

64

getLocationFromAddress()

65

getLatitudeFromAddress()

66

getLongitudeFromAddress()

67

getAddressFromLocationByAPI()

68

setDirectionURL()

69

getZoomLevelByMarkers()

70

getZoomLevelByPolyline()

71

getZoomLevelByRadius()

72

getRadiusFromMeter()

73

getZoomLevelByMeters()

74

animateMarker()

75

initFragment()

76

addFragment()

77

replaceFragment()

78

removeFragment()

79

isFragmentExist()

80

showAdmobInterstitial()

81

setAdmobBanner()

82

setupGA()

83

SendDataToGA()

84

UncaughtExceptionHandler()

85

getCountryZipCode()

86

createFackBookHashKey()

87

isvalidString()

88

isvalidDouble()

89

isValidText()

90

isValidPassword()

91

isValidNumber()

92

isValidEmail()

93

rateTheApp()

94

shareTheApp()

95

getCountry()

96

callToPerson()

97

cancelNotification()

98

loadWebpage()

99

SetLocale()

100

getNetworkType()

101

IsServiceRunning()

102

getDeviceId()

103

getAppVersion()

104

getIPAddress()

105

getWIFIAddress()

106

getIMEI()

107

getBluetoothAddress()

108

getAccount()

109

isAppInstalled()

110

getCapcha()

111

getRandomInt()

112

getUniqueDeviceId()

113

printLog()

114

encryptToMD5()

115

compareDate()

116

isValidDate()

117

getMonthName()

118

getCurrentTime()

119

openDatePicker()

120

setCurrentDate()

121

openTimePicker()

122

getTimeStampFromDate()

123

getUTCDate()

124

getDaysCount()

125

getDateDifference()

126

showSnackBar()

127

NFCUtilsClass

 

How to Zoom & Scale Google map from center position android

Objective :

  • The main objective of this task is to show two markers (customer & driver) base on the distance with appropriate zoom level. Driver position will change base on location update & zoom level update base on the new distance calculated between two markers.

What user can do ?

  • User can zoom in & zoom out map from center position.(customer will be always in center of the map)
  • imgMapTransparent.setOnTouchListener(new MyScaleGestures(TrackingActivity.this,googleMap));

What user can’t do ?

  • User can’t scale map from X,Y position of the map area.
  • User can’t move map as default behaviors
  • All gestures event will be deactivate.
  • mGoogleMap.getUiSettings().setAllGesturesEnabled(false);

How driver location will update ?

  • If a driver changes his/her location from the previous location we will get notify in void onLocationChanged(Location location)this location will help us to calculate the distance between customer & driver.

How does it work ?

  • We will get a frequent update of driver location even app will kill from a background as they will move on the path. Now calculate the distance between customer & driver current location and update driver marker. Now calculate Zoom level base on distance and update map view to be more zoom in.
  • To achieve this we have used transparent image view over the map to zoom in & zoom out and get touch event of the map. So while user scales it from any X,Y position that will call onCameraChangeListner .Now we will calculate zoom level inside onCameraChangeListner and set customer marker to the center of the screen.

Calculate distance between two locations

public float getDistanceInMeter(double startLat, double startLong, double endLat, double endLong) {
Location sourceLoc = new Location(“”);
sourceLoc.setLatitude(startLat);
sourceLoc.setLongitude(startLong);
Location destLoc = new Location(“”);
destLoc.setLatitude(endLat);
destLoc.setLongitude(endLong);
float distanceInMeters = sourceLoc.distanceTo(destLoc);
return distanceInMeters;
}

 

Calculate zoom level from distance

public double getZoomForMetersWide(double desiredMeters, double latitude) {
final double latitudinalAdjustment = Math.cos(Math.PI * latitude / 180);
final double arg = EQUATOR_LENGTH * getScreenWidth() * latitudinalAdjustment / (desiredMeters * 256);
return Math.log(arg) / Math.log(2);
}

 

Update customer marker position

  • mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CUSTOMER_LOCATION, (float) ZOOM_LEVEL));

Update driver marker with animation

LatLngInterpolator latLngInterpolator = new LatLngInterpolator.Spherical();
MarkerAnimation.animateMarkerToGB(driverMarker, currentLatLong, latLngInterpolator);

 

Set Zoom level & Update Map view :

  • (Map only updates if zoom level changes from previous value)

// update map view
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(llTO, mGoogleMap.getCameraPosition().zoom));

mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
if (!isMapChangeRequired) {
isMapChangeRequired = true;
return;
}
double meterDistance = objUtils.getDistanceInMeter(llSprenter.latitude, llSprenter.longitude, llTO.latitude, llTO.longitude);
float Zoomlevel = (float)((float) objUtils.getZoomForMetersWide(meterDistance, llTO.latitude) – 0.3);
if (Zoomlevel != ZOOM_LEVEL) {
ZOOM_LEVEL = Zoomlevel;
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(llTO, (float) ZOOM_LEVEL));

} else {
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(llTO, mGoogleMap.getCameraPosition().zoom));
}
isMapChangeRequired = false;
}
});

Handle custom ScaleGesture & TouchListner over Google Map view

@Override
public boolean onTouch(View view, MotionEvent event) {
this.view = view;
gestureScale.onTouchEvent(event);
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
double zoom = googleMap.getCameraPosition().zoom;
zoom = zoom + Math.log(detector.getScaleFactor()) / Math.log(1.5 d);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(googleMap.getCameraPosition().target, (float) zoom);
googleMap.moveCamera(update);
return true;
}

Full MyScaleGestures.java
public class MyScaleGestures implements View.OnTouchListener, ScaleGestureDetector.OnScaleGestureListener {
private ScaleGestureDetector gestureScale;
private GoogleMap googleMap;

public MyScaleGestures(Context c, GoogleMap googleMap) {
gestureScale = new ScaleGestureDetector(c, this);
this.googleMap = googleMap;
}

@Override
public boolean onTouch(View view, MotionEvent event) {
gestureScale.onTouchEvent(event);
return true;
}

@Override
public boolean onScale(ScaleGestureDetector detector) {
double zoom = googleMap.getCameraPosition().zoom;
zoom = zoom + Math.log(detector.getScaleFactor()) / Math.log(1.5d);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(googleMap.getCameraPosition().target, (float) zoom);
googleMap.moveCamera(update);
return true;
}

@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}

@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
}

 

Map view with transparent ImageView

<RelativeLayout
android:id=”@+id/flMap”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:clickable=”true”
android:focusable=”true”
android:focusableInTouchMode=”true”>

<fragment
android:id=”@+id/layMapContainer”
android:name=”com.google.android.gms.maps.SupportMapFragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”com.googlemapdemo.MapsActivity” />

<ImageView
android:id=”@+id/imgMapTransparent”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:src=”@android:color/transparent” />

</RelativeLayout>

  • Now while driver change is location marker will move with animation and map will zoom out as per location change. Hope this will help you a lot. You can download sample code.

GitHub-download

How to create Facebook Hash Key in android ?

This is simple process  to generate Hash key and we already create  lots of time but again we forget that how to generate Hash key ? Even i am stupid one of them and again throw same query in Google. But Now i remember whole the process to generate hash key. When you start to create new Facebook application for android they ask Hash Key to validate your application.

Most of the time user confused to generate Hask key and Key Store , They confused that from where to start ? It mean which path should be use to generate key?

How to Generate android (Facebook ) Hash Key ?

Step 1 :  Download OpenSSL for Windows 

Step 2 :  Open the drive where you have install JDK. ,(in my case that is C:\)

Step 3 :  Extract your Open SSL zip here in root directory  (in my case C:\Program Files\)

Step 4 :  Copy :  JAVA > JDK 1.7.0_25 > bin

Step 5 :  Open Command prompt , Start  > Run > CMD

Step 6 : Now CMD will show User’s location (in my case C:\Users\chintan >_)

Step 7 : Using Step 4 paste that copied path here and enter ,

So it looks like this C:\Users\chintan > cd  C:\Program Files\Java\jdk1.7.0_25\bin 

Enter , so that will switch to new location. So now you should be here C:\Program Files\Java\jdk1.7.0_25\bin >_

Step 8 :  Now start from here ,

  • 8.1  keytool -export -alias myAlias (set alias name any)
  • 8.2 C:\Users\chintan\.android\debug.keystore ,(Get your Debug key store path and append after alias )
  • 8.3 C:\openssl-0.9.8k_WIN32\bin\openssl sha1 -binary(Get your openssl path and append after keystore path separate with "|") 8.3 C:\openssl-0.9.8k_WIN32\bin\openssl enc -a -e (append with "|")

So , whole URL should looks like ,

Step 9 : Enter if you are ready to get Hash Key 🙂

C:\Program Files\Java\jdk1.7.0_25\bin >keytool -export -alias myAlias -keystore C:\Users\chintan\.android\debug.keystore | C:\openssl-0.9.8k_WIN32\bin\openssl sha1 -binary | C:\openssl-0.9.8k_WIN32\bin\openssl enc -a -e

Camera Preview in android

Hello developers, again i am come up with new sample example about camera preview in your XML layout instead of  camera activity.

To see camera preview we require  SurfaceView and SurfaceHolder.

I have create simple XML Layout file in which i have set two buttons and to show real camera preview we need SurfaceView .

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello" />

<Button
android:id="@+id/startcamerapreview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- Start Camera Preview -" />

<Button
android:id="@+id/stopcamerapreview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- Stop Camera Preview -" />

<SurfaceView
android:id="@+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>

How to mange SurfaceView in java file ?

We will initialize Camera, SurfaceView & SurfaceHolder as global to mange the view. Here is the whole java file which help you easily.

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonStartCameraPreview = (Button) findViewById(R.id.startcamerapreview);
buttonStopCameraPreview = (Button) findViewById(R.id.stopcamerapreview);

surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

buttonStartCameraPreview.setOnClickListener( // write below code inside this block );
buttonStopCameraPreview.setOnClickListener( // write below code inside this block); } 

Implement SurfaceHolder.Callback

This will @Override method surfaceChanged , surfaceCreated , surfaceDestroyed You can write your optional code here as per your requirement.

Task of Show_Preview &  Stop_Preview ?

This is not two different function but i have just filter it so easy to understand.

 Show_Preview() {
if (!previewing) {
camera = Camera.open();
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Stop_Preview() {
if (camera != null && previewing) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if (v.getId() == R.id.startcamerapreview)
{
Show_Preview();
}
if (v.getId() == R.id.stopcamerapreview)
{
Stop_Preview();
}

}

And don’t forget to add android:name="android.permission.CAMERA" in Manifest file.

GitHub-download
GitHub-download

Picture Selection from Camera & Gallery

Hello Guys,
I am here after long time and today i am posting one new sample.

Today I have build simple example in which you can select either Camera or Gallery to pick up an image.For that you have to simple click on Default image and that will launch dialog to ask selection alternative Camera / Gallery.

You can choose any one of them and pick up single image form respective item index either it could be Camera or Gallery.

I will upload next sample in which you can select multiple images from Gallery and use that path.

One Major thing that i have use here and that is Copy Image to your own created Folder. It means when you Capture any image from Camera or Gallery that image will be copied and pasted into your specific /DIR and we will use that image path from target /dir.

So, You can save and safe your images in your own directory.

Now What you will learn from this post ?

  • How to Capture image from camera in android ?
  • How to Pick up  image from Gallery in android ?
  • How to launch alert dialog for image selection either Camera & Gallery ?
  • How to create folder in SD Card ?
  • How to copy image at specific folder in SD Card ?
  • How to create Random File name for image ?
  • How to set Header & Footer fix view using Linear Layout in android ?

Let start with XML layout. (I will show only major code here)

Main.xml

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >

<ImageView
android:id="@+id/user_photo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/user_logo" />
</LinearLayout> 

Image Selection Mode Camera or Gallery Dialog 

– After the selection of one of the mode you will get either Camera screen or Gallery screen , Here you have to select any single image.

– If you are not selecting any image then result should be blank.

public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");

myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});

myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();

}

After Selection of Image

– Yeah, Now you have select any single image and that will come with onActivityResult.
– Now do some copy & decoding task

The selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}

Copy, Decoding & Bitmap Creation Task

public void Image_Selecting_Task(Intent data) {
    try {
        Utility.uri = data.getData();
        if (Utility.uri != null) {
            // User had pick an image.
            Cursor cursor = getContentResolver().query(Utility.uri, new String[] {
                android.provider.MediaStore.Images.ImageColumns.DATA
            }, null, null, null);
            cursor.moveToFirst();
            // Link to the image
            final String imageFilePath = cursor.getString(0);

            //Assign string path to File
            Utility.Default_DIR = new File(imageFilePath);

            // Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
            Utility.Create_MY_IMAGES_DIR();

            // Copy your image 
            Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);

            // Get new image path and decode it
            Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);

            // use new copied path and use anywhere 
            String valid_photo = Utility.Paste_Target_Location.toString();
            b = Bitmap.createScaledBitmap(b, 150, 150, true);

            //set your selected image in image view
            user_photo.setImageBitmap(b);
            cursor.close();

        } else {
            Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
            toast.show();
        }
    } catch (Exception e) {
        // you get this when you will not select any single image 
        Log.e("onActivityResult", "" + e);

    }
}

Create Directory if not Exist

// Create New Dir (folder) if not exist 
public static File Create_MY_IMAGES_DIR() {
    try {
        // Get SD Card path & your folder name
        MY_IMG_DIR = new File(Environment.getExternalStorageDirectory(), "/My_Image/");

        // check if exist 
        if (!MY_IMG_DIR.exists()) {
            // Create New folder 
            MY_IMG_DIR.mkdirs();
            Log.i("path", ">>.." + MY_IMG_DIR);
        }
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("Create_MY_IMAGES_DIR", "" + e);
    }
    return MY_IMG_DIR;
}

Copy Image at specific Directory in sdcard

// Copy your image into specific folder 
public static File copyFile(File current_location, File destination_location) {
    Copy_sourceLocation = new File("" + current_location);
    Paste_Target_Location = new File("" + destination_location + "/" + Utility.Get_Random_File_Name() + ".jpg");

    Log.v("Purchase-File", "sourceLocation: " + Copy_sourceLocation);
    Log.v("Purchase-File", "targetLocation: " + Paste_Target_Location);
    try {
        // 1 = move the file, 2 = copy the file
        int actionChoice = 2;
        // moving the file to another directory
        if (actionChoice == 1) {
            if (Copy_sourceLocation.renameTo(Paste_Target_Location)) {
                Log.i("Purchase-File", "Move file successful.");
            } else {
                Log.i("Purchase-File", "Move file failed.");
            }
        }

        // we will copy the file
        else {
            // make sure the target file exists
            if (Copy_sourceLocation.exists()) {

                InputStream in = new FileInputStream(Copy_sourceLocation);
                OutputStream out = new FileOutputStream(Paste_Target_Location);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;

                while ((len = in .read(buf)) > 0) {
                    out.write(buf, 0, len);
                } in .close();
                out.close();

                Log.i("copyFile", "Copy file successful.");

            } else {
                Log.i("copyFile", "Copy file failed. Source file missing.");
            }
        }

    } catch (NullPointerException e) {
        Log.i("copyFile", "" + e);

    } catch (Exception e) {
        Log.i("copyFile", "" + e);
    }
    return Paste_Target_Location;
}

GitHub-download
GitHub-download

Sharing Text & Image In Twitter – Android Example

Out of 100 application 70 to 80 apps have sharing option either it could be an Android , Iphone or any other platform user can see the sharing Icon which having all social media like FaceBook, Google Plus (G+),Twitter, Mail,etc.

So now a day’s social media is a one of the major part of the application as well as user.

Well here I will share you one of them and that is Twitter Integration in android. So let’s start with coding.

In this post you will learn from starting if you had never implement Twitter in android. You will learn how to share your text message as well as picture also.

In first stage we will learn what should be minimum requirement to integrate Twitter.

 

Updates :

Dear All i know that my last code was not working and that is due to  Twitter4J lib and i have received so many comments to fix it so finally i have build same code with few changes as below.

1. Replace latest jar :

For latest .jar file you can download from   http://twitter4j.org/en/ , once you extract the folder you have to replace twitter4j-core-4.0.2.jar & twitter4j-media-support-4.0.2.jar inside the /lib.

2. Fix the Bug;

In previous code i was updating ui (Toast Message) from background thread so that will cause the issue and crashing the application. Now i have update with runOnUiThread so that will not throw the exception.

3. Emulator Testing:

Add SD card size if you are testing in emulator otherwise that will throw Permission error.

And you can get latest code from my Git Page. https://github.com/khetiyachintan/Android-Twitter-Example

Follow the below steps:

  • Open the https://dev.twitter.com/
  • My Application > Create New Application
  • Fill up some basic >>[ App Name, Description, Web Site, Call back URL ] Everything is mandatory so don’t blank anything you can read more details on same page.
  • Click on Checkbox to agree terms and condition
  • Write captcha and submit you will be get message to done successfully along with that you will be redirect to your KEY Screen and here is your data which will be use to implement in android.
  • You will get Consumer Key & Consumer Secrete Key
  • Now select the setting
  • > check on Read,Write and Access direct Message
  • > also check “Allow this application to be use to sign in with twitter”

Create New Application - Twitter
Create New Application – Twitter

Change your Two Keys & Run Sample

public final String consumer_key = "Replace your KEY";
public final String secret_key = "Replace your KEY";

Twitte to Twitter

public void onClickTwitt() {
	if (isNetworkAvailable()) {
	    Twitt_Sharing twitt = new Twitt_Sharing(MainActivity.this,
		    consumer_key, secret_key);
	    string_img_url = "http://3.bp.blogspot.com/_Y8u09A7q7DU/S-o0pf4EqwI/AAAAAAAAFHI/PdRKv8iaq70/s1600/id-do-anything-logo.jpg";
	    string_msg = "https://chintankhetiya.wordpress.com/";
	    // here we have web url image so we have to make it as file to
	    // upload
	    String_to_File(string_img_url);
	    // Now share both message & image to sharing activity
	    twitt.shareToTwitter(string_msg, casted_image);

	} else {
	    showToast("No Network Connection Available !!!");
	}
    }

How to convert String Image URL to File or Image ?
// this function will make your image to file

public File String_to_File(String img_url) {

	try {
	    File rootSdDirectory = Environment.getExternalStorageDirectory();

	    casted_image = new File(rootSdDirectory, "attachment.jpg");
	    if (casted_image.exists()) {
		casted_image.delete();
	    }
	    casted_image.createNewFile();

	    FileOutputStream fos = new FileOutputStream(casted_image);

	    URL url = new URL(img_url);
	    HttpURLConnection connection = (HttpURLConnection) url
		    .openConnection();
	    connection.setRequestMethod("GET");
	    connection.setDoOutput(true);
	    connection.connect();
	    InputStream in = connection.getInputStream();

	    byte[] buffer = new byte[1024];
	    int size = 0;
	    while ((size = in.read(buffer)) > 0) {
		fos.write(buffer, 0, size);
	    }
	    fos.close();
	    return casted_image;

	} catch (Exception e) {

	    System.out.print(e);
	    // e.printStackTrace();

	}
	return casted_image;
    }

Now up to here i have describe how to config Twitter and how to share image and text in Twitter.Download full code and learn Twitter other files also. How they manage the User REQUEST and return RESPONSE according to same.

I haven’t write a code for Login session so now that is your task how maintain login session and how to Log out.

Hope you like it my post and you will learn grate things form this post.

Twitter Sharing Twitter Login Dialog

GitHub-download
GitHub-download