Tutorials, Free Online Tutorials,It Challengers provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, core java, sql, php, c language etc. for beginners and professionals.

Breaking

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts
1:52 pm

How to get String in response using Retrofit 2? Retrofit Android example

Today we are going to look at another awesome library Retrofit to make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier. As an example, we are going to download some json and show it in RecyclerView as a list.

retrofit get api example
Retrofit get api example

 Follow those steps:-

1.Add the permission to access internet in the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="demo.mukesh.app.com.myapplication">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

6:52 am

Retrofit Android Example

Today we are going to look at another awesome library Retrofit to make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier. As an example, we are going to download some json and show it in RecyclerView as a list.

 Follow those steps:-

1.Add the permission to access internet in the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="demo.mukesh.app.com.myapplication">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

2.Open build.gradle and add Retrofit, Gson dependencies

dependencies {

    implementation 'com.android.support:recyclerview-v7:27.1.1'
//retrofit, gson
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
}

First, we need to know what type of JSON response we will be receiving
 

 3.Creating Model Class


public class Test {
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}


4. Let’s see how our APIInterface.java class looks like

public interface APIInterface {

    @GET("posts")
    Call<ArrayList<Test>> getALLData();
}

5.Create APIClient.java Setting Up the Retrofit Interface
 
public class APIClient {
    private static String BASE_URL="https://jsonplaceholder.typicode.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                //.client(client)
                .build();

        return retrofit;
    }

}

 
6. MyAdapter.java
 
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private Context context;
    private ArrayList<Test> arrTest;

    public MyAdapter(Context context, ArrayList<Test> arrTest) {
        this.context = context;
        this.arrTest = arrTest;

    }

    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Test test= arrTest.get(position);
        holder.title.setText(test.getTitle());
        holder.desc.setText(test.getBody());

    }

    @Override
    public int getItemCount() {
        return arrTest.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title,desc;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.tvTitle);
            desc=(TextView)itemView.findViewById(R.id.tvDesc);
        }
    }
}
 
7.MainActivity.java
public class MainActivity extends AppCompatActivity {
    private ArrayList<Test> arrTest;
    private Activity activity;
    private RecyclerView recyclerView;
    private MyAdapter adapter;

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

    private void callAPI() {
        APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        Call<ArrayList<Test>> call = apiInterface.getALLData();
        call.enqueue(new Callback<ArrayList<Test>>() {
            @Override
            public void onResponse(Call<ArrayList<Test>> call, Response<ArrayList<Test>> response) {
                arrTest = response.body();
                initRecycler();
            }

            @Override
            public void onFailure(Call<ArrayList<Test>> call, Throwable t) {

            }
        });
    }

    private void initRecycler() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager mLayout = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(mLayout);
        adapter = new MyAdapter(activity, arrTest);
        recyclerView.setAdapter(adapter);
    }
}
 


2:05 pm

Android Firebase Tutorial Working With Realtime Database

Android Firebase User Registration 

  • What is Firebase?

Firebase is a mobile and web application platform with tools and infrastructure designed to help developers build high-quality apps. Firebase is made up of complementary features that developers can mix-and-match to fit their needs. 

  • Features of Firebase?

Adding Firebase to our Project
  • Now click on create a new project. 












  • Give your app a name and click on create project.


  • Now you will see the Firebase Panel. You need to click on Android Icon here.















  • Now you will see a panel here you need to put the package name of your project. You can get the package name from AndroidManifest.xml file. Copy the package name and paste it here and then click on Add App.


































  • When you click Add App, a file named google-services.json will be downloaded. You need to paste this file inside app directory of your project. See the below image for explanation.
























  • The Google services plugin for Gradle loads the google-services.json file you just downloaded. Modify your build.gradle files to use the plugin.



























12:57 am

Android Zoom Controls in Android studio

Step 1: Create a new project and name it ZoomControlsApp.

Step 2: Open res -> layout ->content_main and add following code 
In this step we add the code for displaying a ImageView and ZoomControls.




Add image into drawable folder

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" 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" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.mukesh.zoombuttondemo.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="match_parent" 
android:layout_height="wrap_content"
android:text="Zoom Control Button"
android:id="@+id/textView2"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Zoom Control Button"
android:id="@+id/textView2"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="300dp"     
android:layout_height="400dp"       
android:id="@+id/imageView2"        
android:layout_centerHorizontal="true"      
android:layout_marginTop="10dp"       
android:src="@drawable/image"/>

<ZoomControls       
  android:layout_width="wrap_content"     
  android:layout_height="wrap_content"     
  android:id="@+id/zoomControls1"      
  android:layout_below="@id/imageView2"      
  android:layout_centerVertical="true"      
  android:layout_centerHorizontal="true" />

</RelativeLayout>




Step 3: Open Src/Java  -> package -> MainActivity.java



package com.example.mukesh.zoombuttondemo;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.ZoomControls;

public class Main1Activity extends AppCompatActivity {
    ZoomControls zoom1;
    ImageView img1;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        zoom1=(ZoomControls)findViewById(R.id.zoomControls1);
        img1=(ImageView)findViewById(R.id.imageView2);

        zoom1.setOnZoomInClickListener(new View.OnClickListener() {
            @Override          
              public void onClick(View v) {
                float x=img1.getScaleX();
                float y=img1.getScaleY();

                img1.setScaleY(x+1);
                img1.setScaleY(y+1);
            }
        });

        zoom1.setOnZoomOutClickListener(new View.OnClickListener() {
            @Override           
              public void onClick(View v) {
                float x=img1.getScaleX();
                float y=img1.getScaleY();
                img1.setScaleY(x-1);
                img1.setScaleY(y-1);
            }
        });

    }

}