Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: Android

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: Android
Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

JavaScript Alternatives Method SetInterval and ClearInterval in Android

JavaScript Alternatives Method SetInterval and ClearInterval in Android

 
Javascript Setinterval

Hello Friends as We know Switching from Web Developers to Android we Stuck in Some Situation of Methods and How we use Such Methods.

Here i Give a simple Method of JavaScript Which is.

SetInterval = for Creating Task Multiple Times Until we Not Stop it.
Clearinterval = For Stoping SetInterval Task.

Lets Create a Demo page and see How it Works?


<!DOCTYPE html>
<html>
<head>
 <title>Set Interval and Clear interval in JavaScript</title>
</head>
<body>
<p>Example of Set interval and Clear interval</p>
<div id="data">
 
</div>
<script type="text/javascript">
 var myHtmlDiv=document.getElementById("data");
 var loop=0;
 var s=setInterval(function(){
  myHtmlDiv.innerHTML+='A Text After 1 seconds <br>';
 
  if(loop==10){
   //stop my setinterval function after 10 times if you want infinte times executing then remove the if condition means no clearinterval method
   clearInterval(s);
  }
  loop++;
 },1000);
</script>
</body>
</html>


Result :

Javascript Setinterval



Now Lets How We Use this Methods in Android?

So We Can use This Method Simply in Android by Using this Methods

 
      final Timer timer= new Timer();
        timer.scheduleAtFixedRate(new TimerTask(){
            @Override
            public void run(){
                testi++;
                if(testi==5){
                    Log.i("Complete","TaskComplete");
                    timer.cancel();
                }
                Log.i("tag", "A Kiss every 5 seconds");
            }
        },0,5000);
0

Android Autocomplete Location Search

Android Autocomplete Location Search

Android Autocomplete Location Search

  

 

First visit

https://console.developers.google.com/

And Create A New Project And Generate a API key

After That Create A New Android studio Project

Android Autocomplete Location Search


Then edit build.gradle file  and google library dependency


    compile 'com.google.android.gms:play-services-location:11.8.0'
compile 'com.android.volley:volley:1.1.0'


like this in build.gradle.

Google location dependency


After that sync now

gradle sync


Then open AndroidManifest.xml file and add meta for Data And Value for google api which we generate in first step.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sswebtricks.sanjeev.autocompletelocation">
<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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data android:name="com.google.android.geo.API_KEY" android:value="API KEY PUT HERE"/>
    </application>

</manifest>
Now Create a location model for google place api.
Location Model


LocationModel.java



package com.sswebtricks.sanjeev.autocompletelocation;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by sanjeev on 4/2/18.
 */

public class LocationModel {

    private static final String TAG = LocationModel.class.getSimpleName();

    private static final String URL = "https://maps.googleapis.com/maps/api/place";
    private static final String API_TYPE = "/autocomplete";
    private static final String OUTPUT = "/json";

    private static final String KEY = "YOUR_API_KEY";

    public ArrayList autocomplete (String input) {
        ArrayList resultList = null;

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();

        try {
            StringBuilder sb = new StringBuilder(URL + API_TYPE + OUTPUT);
            sb.append("?key=" + KEY);
            sb.append("&types=(cities)");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e(TAG, "Api Error", e);
            return resultList;
        } catch (IOException e) {
            Log.e(TAG, "Connection Error", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        try {
            JSONObject Object = new JSONObject(jsonResults.toString());
            JSONArray PredictArray = Object.getJSONArray("predictions");

            resultList = new ArrayList(PredictArray.length());
            for (int i = 0; i < PredictArray.length(); i++) {
                resultList.add(PredictArray.getJSONObject(i).getString("description"));
                
                          }
        } catch (JSONException e) {
            Log.e(TAG, "Cannot Parse Json", e);
        }

        return resultList;
    }
}

Location Model Java

Now come to layout file which is activity_main.xml

activity_main.xml



<?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"
    tools:context="com.sswebtricks.sanjeev.autocompletelocation.MainActivity">
<LinearLayout
    android:padding="10dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/autocomplete"
        android:hint="Type in your Location" />
</LinearLayout>
    <LinearLayout
        android:padding="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:padding="5dp"
            android:layout_weight="1"
            android:id="@+id/lat"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:padding="5dp"
            android:layout_weight="1"
            android:id="@+id/lng"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</LinearLayout>
</RelativeLayout>

It look like this

activity main layout

activity main layout

Now create a layout resource file for list item

list_item.xml


<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="#000"
    android:padding="10dp"
    android:text="Location"
    android:id="@+id/autocompleteText" />

look like this.

list item



Now create LocationAdapter


LocationAdapter.java

package com.sswebtricks.sanjeev.autocompletelocation;

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import java.util.ArrayList;

/**
 * Created by sanjeev on 4/2/18.
 */

public class LocationAdapter extends ArrayAdapter implements Filterable {

    ArrayList resultList;

    Context mContext;
    int mResource;

    LocationModel mPlaceAPI = new LocationModel();

    public LocationAdapter(Context context, int resource) {
        super(context, resource);

        mContext = context;
        mResource = resource;
    }

    @Override
    public int getCount() {
        
        return resultList.size();
    }

    @Override
    public String getItem(int position) {
        return resultList.get(position);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    resultList = mPlaceAPI.autocomplete(constraint.toString());

                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }

                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }
        };

        return filter;
    }
}

Now MainActivity.java Code :
 
 
package com.sswebtricks.sanjeev.autocompletelocation;

import android.app.ProgressDialog;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;
    TextView tlat;
    TextView tlong;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tlat=(TextView)findViewById(R.id.lat);
        tlong=(TextView)findViewById(R.id.lng);
        progressDialog=new ProgressDialog(this);
        AutoCompleteTextView autocompleteView = (AutoCompleteTextView)findViewById(R.id.autocomplete);
        autocompleteView.setAdapter(new LocationAdapter(getApplicationContext(), R.layout.list_item));
        autocompleteView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
             
                String description = (String) parent.getItemAtPosition(position);
                FindLatLong(description);
                Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void FindLatLong(String description) {

        progressDialog.setMessage("Fetching Details..");
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url = Uri.parse("https://maps.googleapis.com/maps/api/geocode/json")
                .buildUpon()
                .appendQueryParameter("key"Your API KEY")
                .appendQueryParameter("address", URLEncoder.encode(description))
                .build().toString();
        StringRequest sr = new StringRequest(com.android.volley.Request.Method.GET, url, new com.android.volley.Response.Listener() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                try {
                    JSONObject jsonObj = new JSONObject(response);
                    if(jsonObj.getJSONArray("results")!=null) {
                        JSONArray destination_addresses = jsonObj.getJSONArray("results");
                        JSONObject geometry= (JSONObject) destination_addresses.get(0);
                        String lat=String.format("%.4f",geometry.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
                        String lng=String.format("%.4f",geometry.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
                        Log.d("element", response.toString());
                        tlat.setText("Lat : "+lat);
                        tlong.setText("Long : "+lng);

                    }
                    else{
                        Toast.makeText(MainActivity.this, "Error in finding ", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();

                }
                Log.d("Response", response);

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                Log.d("Errors", String.valueOf(error));
            }
        });
        queue.add(sr);
        sr.setRetryPolicy(new DefaultRetryPolicy(
                20000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

}

Now Run Your App And Don't Forget To Put Api Key

MainActivity Auto Complete

Android Auto Complete

Android Auto Complete


Download Complete Source Code
0

Android Firebase Messaging

Android Firebase Messaging

Android Firebase Messaging

Step 1. Create New Android Project

Firebase Messaging Project


Step 2. Open 2nd build.gradle file and paste the dependency

compile 'com.google.firebase:firebase-core:11.8.0'
compile 'com.google.firebase:firebase-messaging:11.8.0'
//and in bottom put this line

apply plugin: 'com.google.gms.google-services'
  
Now its look like this
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.sswebtricks.sanjeev.firebasetutorial"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
}


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-core:11.8.0'
    compile 'com.google.firebase:firebase-messaging:11.8.0'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
apply plugin: 'com.google.gms.google-services'

Step 2a. Open 1st build.gradle file and paste the classpath
        classpath 'com.google.gms:google-services:3.1.1' // google-services plugin

Now file look like this
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.1.1' // google-services plugin
        

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


Firebase Gradle Dependency


Step 3. Open AndroidManifest.xml file and paste the service code and notification color for firebase inside application Tag 

<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/marker" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<service
android:name=".MyFirebaseMessagingService">
 <intent-filter>
 <action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
 </service>
 <service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
AndroidManifest Firebase
Step 4. Create MyFirebaseMessagingService.class which is firebase messaging service which is responsible for receiving our firebase notification
package com.sswebtricks.sanjeev.firebasetutorial;

import android.app.Service;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;


import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());


        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }
        sendNotification(remoteMessage.getNotification().getBody());
    }
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.project_id);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.marker)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Firebase Message Service

Step 5. Create MyFirebaseInstanceIDService.class which is firebase messaging service for generating our firebase tokens
package com.sswebtricks.sanjeev.firebasetutorial;

import android.app.Service;

/**
 * Created by sanjeev on 31/1/18.
 */

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {

    }

}

Firebase Instance

Step 6. Create New Project in https://console.firebase.google.com/
Add android to your project and download google-services.json which you got when generating your project.

Step 7. Then from right nav click on Android->then Select Project and Paste the google-services.json in app directory

Firebase google-services.json

Step 8. Now we are Ready to check our messages Go to Firebase Console then Grow->Notifcation and send your test Message

Firebase Notification Dashboard

Step 9. Then Check in Your App

Firebase Notification Tray
Video Tutorial
Download Source Code Download
0

Android Retrofit Complete Tutorial

Android Retrofit Complete Tutorial

Android Retrofit Tutorial
Start Android New Project in Android Studio



Then Copy the Retrofit Dependency and paste in build.gradle
From Here : -
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
After That click on sync now
. Now gradle downloading dependecy wait few seconds

Now Add the Internet Permission in AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Now we are using dummy Api which gives us JSON Array data of post
https://jsonplaceholder.typicode.com/posts



Now we are creating 4 subpackages under your main project packages
1. for modal
2.for retrofit api
3.for activity
4.for adapter.

Lets Start For Modal

Since we are Seeing That Our Modal Response Which had

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
]
userid
title
id
and body keys under json Array .

Now Lets start Model PostModel.java
PostModel.java



 
package com.sswebtricks.sanjeev.retrofitdemo.model;
import com.google.gson.annotations.SerializedName;
/**
 * Created by sanjeev on 18/1/18.
 */
public class PostModel {
    @SerializedName("userId")
    private String userId;
    @SerializedName("id")
    private String id;
    @SerializedName("title")
    private String title;
    @SerializedName("body")
    private String body;
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getId() {
        return id;
    }
    public void setId(String 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;
    }
}
Now Creating ApiClient.java which is Sending And Receiving Response From Server Here We Use Reftrofit .



ApiClient.java
package com.sswebtricks.sanjeev.retrofitdemo.api;
/**
 * Created by sanjeev on 18/1/18.
 */
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
    public static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
Now Defining The Api End Point Which Contain Information About where we sending request And What keys we passed .
Each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and the parameters of this method can also have special annotations (@Query, @Path, @Body .)

Take a look to other annotations:
@Path – this will be replace under url method like (post/{id}) id will be replaced by value
@Query – this is key pair value under our methods for calling api like

@Body – We generally use this for json body passing
@Header – Contain Header information
Like content-type,Authorization etc



ApiInterface.java
package com.sswebtricks.sanjeev.retrofittutorial.api;

import com.sswebtricks.sanjeev.retrofittutorial.model.ItemsModel;
import com.sswebtricks.sanjeev.retrofittutorial.model.PostModel;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by sanjeev on 18/1/18.
 */

public interface ApiInterface {
    @GET("posts")
    Call<List<PostModel>> get_post();
    //requesting json array that why i take inside list
}
Now Creating Layout (activity_main.xml)



 
<android .support.constraint.constraintlayout="" android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.sswebtricks.sanjeev.retrofitdemo.activity.MainActivity" 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">
<gridview android:horizontalspacing="0dp" android:id="@+id/gridview" android:layout_height="match_parent" android:layout_width="match_parent" android:numcolumns="1" android:scrollbars="horizontal" android:stretchmode="columnWidth" android:verticalspacing="0dp">
</gridview>
</android>
Now (grdiitem.xml)

 
<android .support.v7.widget.cardview="" android:clickable="true" android:foreground="?android:attr/selectableItemBackground" android:id="@+id/cards" android:layout_height="500dp" android:layout_margin="10dp" android:layout_weight="1" android:layout_width="match_parent" card_view:cardcornerradius="5dp" card_view:cardelevation="5dp" card_view:cardusecompatpadding="true" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto">
    <relativelayout android:layout_height="match_parent" android:layout_width="match_parent">
        <imageview android:adjustviewbounds="true" android:id="@+id/img" android:layout_gravity="top" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/nature"/>
    <textview android:id="@+id/title" android:layout_below="@id/img" android:layout_height="wrap_content" android:layout_width="match_parent" android:padding="5dp" android:text="2" android:textcolor="@color/white" android:textsize="20dp"/>
    <textview android:fontfamily="serif" android:id="@+id/body" android:layout_below="@id/title" android:layout_height="wrap_content" android:layout_margintop="20dp" android:layout_width="wrap_content" android:padding="5dp" android:shadowcolor="#fff" android:text="Total" android:textcolor="#fff" android:textsize="15dp" android:textstyle="bold"/>
    </relativelayout>
</android>
Now Adapter For adding our griditem.xml in activity_main.xml

Adapter includes the modal and our layout file and model information which model data append in our layout file.



MyAdapter.java
package com.sswebtricks.sanjeev.retrofitdemo.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sswebtricks.sanjeev.retrofitdemo.R;
import com.sswebtricks.sanjeev.retrofitdemo.model.ItemModal;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by sanjeev on 18/1/18.
 */
public class MyAdapter extends BaseAdapter {
    private List mItems = new ArrayList();
    private final LayoutInflater mInflater;
    public MyAdapter(Context context, List items) {
        mInflater = LayoutInflater.from(context);
        mItems=items;
    }
    @Override
    public int getCount() {
        return mItems.size();
    }
    @Override
    public ItemModal getItem(int i) {
        return mItems.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        TextView title;
        TextView body;
        ImageView imageView;
        CardView cardView;
        if (v == null) {
            v = mInflater.inflate(R.layout.griditem, viewGroup, false);
            v.setTag(R.id.title, v.findViewById(R.id.title));
            v.setTag(R.id.body, v.findViewById(R.id.body));
            v.setTag(R.id.cards,v.findViewById(R.id.cards));
            v.setTag(R.id.img,v.findViewById(R.id.img));
        }
        title = (TextView) v.getTag(R.id.title);
        body = (TextView) v.getTag(R.id.body);
        cardView=(CardView)v.getTag(R.id.cards);
        imageView=(ImageView)v.getTag(R.id.img);
        ItemModal item = getItem(i);
        title.setText(item.title);
        body.setText(item.body);
        imageView.setImageResource(R.drawable.nature);
        cardView.setCardBackgroundColor(item.colors);
        return v;
    }

}
And A Modal ItemModal.java





It includes the information of our data like title and body
package com.sswebtricks.sanjeev.retrofitdemo.model;
/**
 * Created by sanjeev on 18/1/18.
 */
public class ItemModal {
    public final String title;
    public final String body;
    public int colors;
    public ItemModal(String title, String body,int colors) {
        this.title = title;
        this.body= body;
        this.colors=colors;
    }
}
Now Our Final MainActivity.java


 
It conatin api interface which implement here and adapter first we take response from server the appending in our list then we update the adpter for new data.
package com.sswebtricks.sanjeev.retrofittutorial.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.Toast;

import com.sswebtricks.sanjeev.retrofittutorial.R;
import com.sswebtricks.sanjeev.retrofittutorial.adapter.MyAdapter;
import com.sswebtricks.sanjeev.retrofittutorial.api.ApiClient;
import com.sswebtricks.sanjeev.retrofittutorial.api.ApiInterface;
import com.sswebtricks.sanjeev.retrofittutorial.model.ItemsModel;
import com.sswebtricks.sanjeev.retrofittutorial.model.PostModel;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView=(GridView)findViewById(R.id.gridview);
        CallApi();
    }
    public void CallApi(){
        ApiInterface apiInterface=ApiClient.getRetrofit().create(ApiInterface.class);
        Call<List<PostModel>> call=apiInterface.get_post();
        call.enqueue(new Callback<List<PostModel>>() {
            @Override
            public void onResponse(retrofit2.Call<List<PostModel>> call, Response<List<PostModel>> response) {

                List<PostModel> list=response.body();
                List<ItemsModel> mlist=new ArrayList<ItemsModel>();
                for (int i=0;i<List.size();i++){
                    mlist.add(new ItemsModel(list.get(i).getTitle(),list.get(i).getBody()));
                }
                MyAdapter myAdapter=new MyAdapter(getApplicationContext(),mlist);
                gridView.setAdapter(myAdapter);
            }

            @Override
            public void onFailure(retrofit2.Call<List<PostModel>> call, Throwable t) {
                Toast.makeText(getApplicationContext(),"Error Fetching ",Toast.LENGTH_SHORT);
            }
        });

    }
}
Also put a image image file in drawble folder named “nature.jpg”

Now Our Final App Look Like this.





 Complete Offline Docs And Project

Docs : - Retrofit Tutorial 

Project : - Download Project

Video Tutorial

1

Android Reverse Engineering

Android Reverse Engineering


Today We start Android Reverse Enginnering By Using Simple Method To get Source Code Of Any Android App.

Lets Start

Download 


Then Extract It

After That 

Open That Folder in Terminal 

Now

cd jadx
./gradlew dist 
 
This Will Take Time for gradle build and gradle download
 
After That
 
You Can now run command 

build/jadx/bin/jadx-gui

 
It Open A Gui window .


Now you can open your app and see the source codes.
0

Android Login and Signup

Android Login and Sign up Complete Demo


              Download Complete Android Login and Signup Demo Project 

0

Laravel login And Signup Api service

Laravel login And Sign up API service

 

Download Complete Project for Laravel Login and Signup Api service

0