Option 1
In the AndroidManifest.xml add ‘screenOrientation’ property in activity tag
<activity - - - - - - - - - - - - - - android:screenOrientation="portrait" />
Option 2
In the onCreate function add the following line of code before setContentView() function
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_main); //------ }
Android Retrofit 2.1 HTTP client :
In this example i have divided in to 5 steps :
1. Add gradle dependency
2. Create models for accessing the final data (in this example, the api response json converting to java object this object class is called model )
3. Create interface to define api end point
4. Create a service class for interacting our java code with retrofit.
5. Make the api calls wherever you required
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0'
User.java
public class User { public int id; public String name; public String email; public String phone; }
ApiInterface.java
import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import samples.bm.com.firebaselogin2.models.User; public interface ApiInterface { @GET("get/users") Call<List<User>> getAllUsers(); //List<User> is the response from api @GET("get/user") Call<User> getUser( @Query("id") int id); //using query param (get/user?id=17479666). User is the response from the api //@GET("get/user/{id}") //Call<User> getUser( @Query("id") int id); //using path param (get/user/17479666) @POST("register/user") Call<User> registerUser(@Body User user); @FormUrlEncoded @POST("update/{id}/user") Call<User> updateUser(@Field("name") String name, @Field("phone") String phone, @Path("id") String id); }
expected api response
get/users
[ { "id": 17479666, "name": "name1", "email": "name1@domain.com", "phone": "3435353535434" }, { "id": 17479668, "name": "name3", "email": "name3@domain.com", "phone": "3435353343434" } ]
get/user
{ "id": 17479666, "name": "name1", "email": "name1@domain.com", "phone": "3435353535434" }
ApiService.java
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ApiService { private static ApiInterface service; private static String BASE_URL = "https://api.domain.com/"; //your api domain public static ApiInterface getInstance() { if (service == null) { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); service = retrofit.create(ApiInterface.class); } return service; } }
Retrofit supports synchronous and asynchronous request execution.
Asynchronous Requests
GET calls
ApiService.getInstance().getAllUsers().enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { //api success List<User> users = response.body(); } @Override public void onFailure(Call<List<User>> call, Throwable t) { Log.e("Apicall", t.getMessage()); } });
GET call with query string/param OR GET call with path string/param
int id=17479666; ApiService.getInstance().getUser(id).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //api success User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { Log.e("Apicall", t.getMessage()); } });
Post call
POST call with body param
User user = new User("samoe", "some@ss.com", "234242424"); ApiService.getInstance().registerUser(user).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //api success User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { Log.e("Apicall", t.getMessage()); } });
POST call with form encoding
String name = "some name"; String phone = "54686868"; String id="17479666"; ApiService.getInstance().updateUser(name, phone, id).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //api success User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { Log.e("Apicall", t.getMessage()); } }); }
Synchronous request
You can also call the apis synchronously.
try { List<User> users = ApiService.getInstance().getAllUsers().execute().body(); } catch (IOException e) { e.printStackTrace(); }
You cannot run this code in main tread you will get exception like ( java.lang.RuntimeException:Unable to start activity ComponentInfo{ …. } android.os.NetworkOnMainThreadException). So better to use synchronous request in services or asyncTask.
How to create AsyncTask : https://wiki.workassis.com/android-asynctask
How to create Service : https://wiki.workassis.com/android-intentservice-example
Androidmanifest.xml
You need to use NoactionBar theme
---- ---- <activity android:name=".SplashActivity" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> --- ----
Activity class (SplashActivity.java)
public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); } }
There are two step required for implementing Green Dao ORM library in to android project
1. Create generator java module
2. Implement data base interaction in Activity
The generator module contains a single class containing the data model definition. This will automatically generate model class and Dao calss for the database interaction
In android studio got File->New-> New Module select Java Library
Give library name and class name
After adding the library the folder structure will be like this
add GreenDao dependency in the created module, and sync
compile 'de.greenrobot:greendao-generator:2.1.0'
for Green dao 3.x please use the plugin
compile 'org.greenrobot:greendao-generator:3.1.0'
Add the following code in GeneratorClass.java file. Here we defining a users table scema
import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; public class GeneratorClass { public static void main(String[] args) throws Exception { //place where db folder will be created inside the project folder Schema schema = new Schema(1,"samples.bm.com.greendaoe1.db"); //Entity Users or table Users Entity user= schema.addEntity("Users"); user.addIdProperty(); //It is the primary key for uniquely identifying a row user.addStringProperty("name").notNull(); //Not null is SQL constrain user.addStringProperty("email"); user.addStringProperty("password"); //user.addDateProperty("date"); // ./app/src/main/java/ ---- com/codekrypt/greendao/db is the full path new DaoGenerator().generateAll(schema, "./app/src/main/java"); } }
for Green dao 3.x:- just change the imports
import org.greenrobot.greendao.generator.DaoGenerator; import org.greenrobot.greendao.generator.Entity; import org.greenrobot.greendao.generator.Schema;
Run GeneratorClass.java file
It will Create a db folder inside out main app package
Add Green Dao gradle dependency in our main project and sync
compile 'de.greenrobot:greendao:2.1.0'
for Green dao 3.x:-
compile 'org.greenrobot:greendao:3.1.1'
MainActivity .java
import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import samples.bm.com.greendaoe1.db.DaoMaster; import samples.bm.com.greendaoe1.db.DaoSession; import samples.bm.com.greendaoe1.db.Users; import samples.bm.com.greendaoe1.db.UsersDao; public class MainActivity extends AppCompatActivity { //Dao --> Data Access Object private UsersDao userDao; // Sql access object private final String DB_NAME = "my-app-db"; //Name of Db file in the Device EditText mEtName; EditText mEtEmail; EditText mEtPassword; ArrayAdapter<String> mAdapter; ListView mListView; List<String> mResult = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initialise DAO userDao = setupDb(); //Setting up form elements Button btnSave = (Button) findViewById(R.id.btn_Save); mEtName = (EditText) findViewById(R.id.et_name); mEtEmail = (EditText) findViewById(R.id.et_email); mEtPassword = (EditText) findViewById(R.id.et_password); mListView = (ListView) findViewById(R.id.lv_result); mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mResult); mListView.setAdapter(mAdapter); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = mEtName.getText().toString(); String email = mEtEmail.getText().toString(); String password = mEtPassword.getText().toString(); Users user = new Users(null, name, email, password);// Class Object, Id is auto increment SaveToSQL(user); generateResult(); mEtName.setText(""); mEtEmail.setText(""); mEtPassword.setText(""); } }); generateResult(); } private void generateResult() { List<Users> usersList = getFromSQL(); int size = usersList.size(); if (size > 0) { mResult.clear(); for (int i = 0; i < size; i++) { Users currentItem = usersList.get(i); mResult.add (0,currentItem.getId() + ", " + currentItem.getName() + ", " + currentItem.getEmail() + ", " + currentItem.getPassword()); } ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged(); } } //---------------------------------SQL QUERY Functions-----------------------------------------// public List<Users> getFromSQL() { List<Users> userses = userDao.queryBuilder().orderDesc(UsersDao.Properties.Id).build().list(); return userses; } public void SaveToSQL(Users user) { userDao.insert(user); } //----------------------------***END SQL QUERY***---------------------------------------------// //-------------------------------DB Setup Functions---------------------------------------------// //Return the Configured LogDao Object public UsersDao setupDb() { DaoMaster.DevOpenHelper masterHelper = new DaoMaster.DevOpenHelper(this, DB_NAME, null); //create database db file if not exist SQLiteDatabase db = masterHelper.getWritableDatabase(); //get the created database db file DaoMaster master = new DaoMaster(db);//create masterDao DaoSession masterSession = master.newSession(); //Creates Session session return masterSession.getUsersDao(); } //-------------------------***END DB setup Functions***---------------------------------------// }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="samples.bm.com.greendaoe1.MainActivity"> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" /> <EditText android:id="@+id/et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" /> <Button android:id="@+id/btn_Save" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:layout_marginTop="20dp" android:text="Result" android:textStyle="bold" /> <ListView android:id="@+id/lv_result" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
Out Put
Note:-
While running you app you need to set app from tine toolbar and run
Ref:
(For using multiple layout in RecyclerView check this tutorial )
Add ‘com.android.support:recyclerview‘ in Gradle dependencies and sync it
my app/build.gradle file
apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "24.0.1" defaultConfig { applicationId "samples.bm.com.myapplication" minSdkVersion 14 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.android.support:recyclerview-v7:24.2.0' }
MainActivity
package samples.bm.com.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements MyMediatorInterface { private MyAdapter mAdapter; private ArrayList<UserModel> usersList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usersList = new ArrayList<>(); usersList.add(new UserModel("Jos", "123546567")); usersList.add(new UserModel("Kiran", "456546456")); usersList.add(new UserModel("Manu", "5678")); usersList.add(new UserModel("Roy", "67443453")); usersList.add(new UserModel("Musthu", "456353")); usersList.add(new UserModel("Jaffer", "4644")); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_my_recycler_view); recyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); mAdapter = new MyAdapter(usersList, this); recyclerView.setAdapter(mAdapter); } @Override public void userItemClick(int pos) { Toast.makeText(MainActivity.this, "Clicked User : " + usersList.get(pos).name, Toast.LENGTH_SHORT).show(); } }
Model
package samples.bm.com.myapplication; public class UserModel { public String name; public String phone; public UserModel(String name, String phone) { this.name = name; this.phone = phone; } }
Adapter
package samples.bm.com.myapplication; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.lang.ref.WeakReference; import java.util.ArrayList; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { ArrayList<UserModel> mUsersList; WeakReference<Context> mContextWeakReference; public MyAdapter(ArrayList<UserModel> usersList, Context context) { mUsersList = usersList; this.mContextWeakReference = new WeakReference<Context>(context); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = mContextWeakReference.get(); if (context != null) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_user_item, parent, false); return new MyViewHolder(itemView, context); } return null; } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { Context context = mContextWeakReference.get(); if (context == null) { return; } UserModel currentUser = mUsersList.get(position); holder.TvName.setText(currentUser.name); holder.TvPhone.setText(currentUser.phone); } @Override public int getItemCount() { return mUsersList.size(); } //holder public static class MyViewHolder extends RecyclerView.ViewHolder { public TextView TvName, TvPhone; public LinearLayout ll; public MyViewHolder(View itemView, final Context context) { super(itemView); TvName = (TextView) itemView.findViewById(R.id.tv_name); TvPhone = (TextView) itemView.findViewById(R.id.tv_phone); ll = (LinearLayout) itemView.findViewById(R.id.ll_layout); ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((MainActivity) context).userItemClick(getAdapterPosition()); } }); } } }
Interface:
package samples.bm.com.myapplication; public interface MyMediatorInterface { void userItemClick(int pos); }
Layouts
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="samples.bm.com.myapplication.MainActivity" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> <android.support.v7.widget.RecyclerView android:id="@+id/rv_my_recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
Recycler View row
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/ll_layout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="20px"> <TextView android:id="@+id/tv_name" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="right" /> </LinearLayout>
Out Put
If you want to add data to RecyclerView add data into the Array List (eg:- usersList.add(new UserModel(“new name”, “345”)); and you can call the adapter function notifyItemInserted() or notifyDatasetChanged().
mAdapter.notifyItemInserted(position);
mAdapter.notifyDataSetChanged(); //this function you can call with any activity (inset,update,delete) but it is expensive
While editing edit the value in array list and call notifyItemChanged(position), while deleting delete the position from array list and call notifyItemRemoved(position)
String objects are immutable ( once created can not be changed ) and it will stored in the Constant String Pool , so if you chose to do a lot of manipulations with String objects, you will end up with a lot of abandoned String objects in the String pool. To avoiding this memory loss we can use StringBuilder or StringBuffer and can be modified over and over again without causing memory loss
StringBuffers are thread-safe, they have synchronized methods to control access so that only one thread can access a StringBuffer object’s synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.
String from = "From : "; String to = " To : "; StringBuilder builder = new StringBuilder(); builder.append(from); builder.append("Manager"); builder.append(to); builder.append("Developer"); Log.i("Result : ", builder.toString());
StringBuilder’s access is not synchronized so that it is not thread-safe. The performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance.
String from = "From : "; String to = " To : "; String str = new StringBuffer() .append(from) .append("Manager") .append(to) .append("Developer") .toString(); Log.i("Result : ",str);
ref:
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/tutorial/java/data/buffers.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html