In this Post, I will explain how to import and use External SQLite DB in Android. You can import and use SQLite database with the exten...

How to use External SQLite DB in Android How to use External SQLite DB in Android

A blog about android developement

How to use External SQLite DB in Android

In this Post, I will explain how to import and use External SQLite DB in Android.
You can import and use SQLite database with the extensions like .db, .db3,sqlite and sqlite3.
The External DB is created with some desktop applications like SQLite Browser, SQLite Converter and so on.
After Generating the DB paste that into your App's assets folder.
Code:
DBHelper.class
Create a class named as DBHelper extending with SQLiteHelper. Paste the following code in that class.
public class DBHelper extends SQLiteOpenHelper {
    Context context;
    String DB_PATH;
    String divider = "/";
    String DB_NAME;

    public DBImporterExporter(Context context, String DB_NAME) {
        super(context, DB_NAME, null, 1);
        this.context = context;
        this.DB_NAME = DB_NAME;
        DB_PATH = divider + "data" + divider + "data" + divider + context.getPackageName() + divider + "databases/";
    }

    public boolean isDataBaseExists() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    public void importDataBaseFromAssets() throws IOException {

        this.getReadableDatabase();

        InputStream myInput = context.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        Toast.makeText(context.getApplicationContext(), "Successfully Imported", Toast.LENGTH_SHORT).show();
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }
 
}
The DB is Imported by using the following code
DBImporterExporter dbImporterExporter = new DBImporterExporter(getApplicationContext(), "external_db_android.sqlite");
 try {
  dbImporterExporter.importDataBaseFromAssets();
    } catch (IOException e) {
  e.printStackTrace();
}
To Check the Existence of DB use the following snippet in your class
dbImporterExporter.isDataBaseExists()
Download Source Code



Having trouble while using this code or any doubt, comment me

Fast and Easiest way ever : Open Android Studio Open Your Project Click on Gradle (From Right Side Panel, you will see  Gradle Bar ) ...

Android Tips - How to get SHA1 key in Android Studio without CMD Android Tips - How to get SHA1 key in Android Studio without CMD

A blog about android developement

Fast and Easiest way ever :
  1. Open Android Studio
  2. Open Your Project
  3. Click on Gradle (From Right Side Panel, you will see Gradle Bar)
  4. Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of your Project)
  5. Click on Your Project (Your Project Name form List (root))
  6. Click on Tasks
  7. Click on android
  8. Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)
The Following Screens explains the steps

Android Tips - How to get SHA1 key in Android Studio without CMD

SCREEN-1

Android Tips - How to get SHA1 key in Android Studio without CMD

SCREEN-2

Android Tips - How to get SHA1 key in Android Studio without CMD


SCREEN-3


In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to ...

QR-Code Generator - Library QR-Code Generator - Library

A blog about android developement

QR-CODE  GENERATOR - Library
In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input.
How to Import the Library:
Gradle:
compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0'
Permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
How to use this Library:
After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code
// Initializing the QR Encoder with your value to be encoded, type you required and Dimension
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
try {
  // Getting QR-Code as Bitmap
  bitmap = qrgEncoder.encodeAsBitmap();
  // Setting Bitmap to ImageView
  qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
  Log.v(TAG, e.toString());
}
Save QR Code as Image
// Save with location, value, bitmap returned and type of Image(JPG/PNG).
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
For more Details Visit Here
Github Link:
Open Github
Leave Comment about this Library.

Hello friends, In this post, I will show how to send mail with GMail using OAuth2.0 in Android. This Project contains a lot of steps l...

Java Mail API using GMAIL OAuth API in Android Java Mail API using GMAIL OAuth API in Android

A blog about android developement

Java Mail API using GMAIL OAuth API in Android
Hello friends, In this post, I will show how to send mail with GMail using OAuth2.0 in Android. This Project contains a lot of steps like Permission, Google Play Service check to do.
So, please download the project to perform GMail API completely.

First of All, we have to generate OAuth key in Google API Console. To Generate OAuth Key, use your SHA1 key and your app's Package Name as in your Manifest.Paste Following code in your Command Prompt to get SHA1 key in Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Project Structure

Create a new Project in Android Studio with the required Specifications.

AndroidManifest.xml

Don't forget to add the following permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<!--Added for Accessing External Storage-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
We have to add the following Jar Files into your Project as like Normal Java Mail API.
  1. mail.jar
  2. activation.jar
  3. additionnal.jar
Download Jars From Server

build.gradle

Open your app level build.gradle file add the following lines.
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.google.android.gms:play-services-identity:8.4.0'
    compile('com.google.api-client:google-api-client-android:1.22.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-gmail:v1-rev44-1.22.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile files('libs/mail.jar')
    compile files('libs/activation.jar')
    compile files('libs/additionnal.jar')
}
Initialize the Google API Client as in the following.
GoogleAccountCredential mCredential;
String[] SCOPES = {
    GmailScopes.GMAIL_LABELS,
    GmailScopes.GMAIL_COMPOSE,
    GmailScopes.GMAIL_INSERT,
    GmailScopes.GMAIL_MODIFY,
    GmailScopes.GMAIL_READONLY,
    GmailScopes.MAIL_GOOGLE_COM
};
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
  getApplicationContext(), Arrays.asList(SCOPES))
  .setBackOff(new ExponentialBackOff());
Following line is used to start Account Pick in Android
// Start a dialog from which the user can choose an account
startActivityForResult(mCredential.newChooseAccountIntent(), Utils.REQUEST_ACCOUNT_PICKER);
Use the following code to generate and initialize all the processes regarding this project.
// Async Task for sending Mail using GMail OAuth
    private class MakeRequestTask extends AsyncTask {
        private com.google.api.services.gmail.Gmail mService = null;
        private Exception mLastError = null;
        private View view = sendFabButton;

        public MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.gmail.Gmail.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName(getResources().getString(R.string.app_name))
                    .build();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                return getDataFromApi();
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        private String getDataFromApi() throws IOException {
            // getting Values for to Address, from Address, Subject and Body
            String user = "me";
            String to = Utils.getString(edtToAddress);
            String from = mCredential.getSelectedAccountName();
            String subject = Utils.getString(edtSubject);
            String body = Utils.getString(edtMessage);
            MimeMessage mimeMessage;
            String response = "";
            try {
                mimeMessage = createEmail(to, from, subject, body);
                response = sendMessage(mService, user, mimeMessage);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return response;
        }

        // Method to send email
        private String sendMessage(Gmail service,
                                   String userId,
                                   MimeMessage email)
                throws MessagingException, IOException {
            Message message = createMessageWithEmail(email);
            // GMail's official method to send email with oauth2.0
            message = service.users().messages().send(userId, message).execute();

            System.out.println("Message id: " + message.getId());
            System.out.println(message.toPrettyString());
            return message.getId();
        }

        // Method to create email Params
        private MimeMessage createEmail(String to,
                                        String from,
                                        String subject,
                                        String bodyText) throws MessagingException {
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            MimeMessage email = new MimeMessage(session);
            InternetAddress tAddress = new InternetAddress(to);
            InternetAddress fAddress = new InternetAddress(from);

            email.setFrom(fAddress);
            email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
            email.setSubject(subject);

            // Create Multipart object and add MimeBodyPart objects to this object
            Multipart multipart = new MimeMultipart();

            // Changed for adding attachment and text
            // This line is used for sending only text messages through mail
            // email.setText(bodyText);

            BodyPart textBody = new MimeBodyPart();
            textBody.setText(bodyText);
            multipart.addBodyPart(textBody);

            if (!(activity.fileName.equals(""))) {
                // Create new MimeBodyPart object and set DataHandler object to this object
                MimeBodyPart attachmentBody = new MimeBodyPart();
                String filename = activity.fileName; // change accordingly
                DataSource source = new FileDataSource(filename);
                attachmentBody.setDataHandler(new DataHandler(source));
                attachmentBody.setFileName(filename);
                multipart.addBodyPart(attachmentBody);
            }

            // Set the multipart object to the message object
            email.setContent(multipart);
            return email;
        }

        private Message createMessageWithEmail(MimeMessage email)
                throws MessagingException, IOException {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            email.writeTo(bytes);
            String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
            Message message = new Message();
            message.setRaw(encodedEmail);
            return message;
        }

        @Override
        protected void onPreExecute() {
            mProgress.show();
        }

        @Override
        protected void onPostExecute(String output) {
            mProgress.hide();
            if (output == null || output.length() == 0) {
                showMessage(view, "No results returned.");
            } else {
                showMessage(view, output);
            }
        }

        @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            Utils.REQUEST_AUTHORIZATION);
                } else {
                    showMessage(view, "The following error occurred:\n" + mLastError.getMessage());
                    Log.v("Error", mLastError.getMessage());
                }
            } else {
                showMessage(view, "Request Cancelled.");
            }
        }
    }

Screens:

Screen1
Screen2
Screen3
Screen4
Screen5

Important

You should add the following lines in proguard while releasing your APK
-keep class com.google.** 
Thanks to Kaba Droid42 for this.

Download Source Code

You can download the full source from the following Github link. If you Like this library, Please star it in Github.

Hello friends, In this post, I will show you how to upload Image/Video/Any Files to the Server in Android using Retrofit 2. In Retrofit 2...

Upload File to Server using Retrofit in Android Upload File to Server using Retrofit in Android

A blog about android developement

Upload file using Retrofit
Hello friends, In this post, I will show you how to upload Image/Video/Any Files to the Server in Android using Retrofit 2. In Retrofit 2 Image or any type of files will be uploaded as Multipart. The File is received using php.

This Code is Updated with Multiple File Upload.

Upload Single File

Web Part:

Create a PHP file named as upload_image.php and paste the following lines.
<?php
$target_dir = "uploads/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
if (isset($_FILES["file"])) 
{
   if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name)) 
   {
     $success = true;
     $message = "Successfully Uploaded";
   }
   else 
   {
      $success = false;
      $message = "Error while uploading";
   }
}
else 
{
      $success = false;
      $message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);

?>

Project Structure

Create a new Project in Android Studio with the required Specifications.

Codes:

AndroidManifest.xml
Don't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
build.gradle
Open your app level build.gradle file add the following lines.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0' 
    // dependency for Retrofit 2
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
}
AppConfig.java
Create AppConfig.java and replace it with the following lines
class AppConfig {

    private static String BASE_URL = "http://mushtaq.16mb.com/";
    static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}
ApiConfig.java
Create ApiConfig.java and replace it with the following lines
interface ApiConfig {
    @Multipart
    @POST("retrofit_example/upload_image.php")
    Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
ServerResponse.java
Create ServerResponse.java and replace it with the following lines. The Data Names are same as the Names in PHP(for example success and message)
class ServerResponse {

    // variable name should be same as in the json response from php
    @SerializedName("success")
    boolean success;
    @SerializedName("message")
    String message;

    String getMessage() {
        return message;
    }

    boolean getSuccess() {
        return success;
    }

}
activity_main.xml
Create activity_main.xml and Paste the following lines
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:scrollbars="none"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:id="@+id/preview"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:scaleType="centerCrop"
            android:src="@drawable/placeholder" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/pick_img"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Pick Image" />

            <Button
                android:id="@+id/pick_vdo"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:text="Pick Video" />

        </LinearLayout>

        <Button
            android:id="@+id/upload"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload" />

        <TextView
            android:id="@+id/filename1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="FileName 1: " />

        <TextView
            android:id="@+id/filename2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="FileName 2: " />

        <Button
            android:id="@+id/uploadMultiple"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload Multiple" />
    </LinearLayout>
</ScrollView>

Function to upload file:

// Uploading Image/Video
private void uploadFile() {
    progressDialog.show();

    // Map is used to multipart the file using okhttp3.RequestBody    File file = new File(mediaPath);

    // Parsing any Media type file    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

    ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
    Call call = getResponse.uploadFile(fileToUpload, filename);
    call.enqueue(new Callback() {
    @Override        
    public void onResponse(Call call, Response response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                if (serverResponse.getSuccess()) {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                }
            } else {
                assert serverResponse != null;
                Log.v("Response", serverResponse.toString());
            }
            progressDialog.dismiss();
        }

        @Override        
        public void onFailure(Call call, Throwable t) {

        }
    });
}

Upload Multiple Files

To Upload Multiple files, I made some changes as in the following.
Create a PHP file named as upload_multiple_files.php and paste the following lines.
<?php
 
$target_dir = "uploads/";
$target_file_name1 = $target_dir.basename($_FILES["file1"]["name"]);
$target_file_name2 = $target_dir.basename($_FILES["file2"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
if (isset($_FILES["file1"])&&isset($_FILES["file2"])) 
{
 if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file_name1)
  && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file_name2)) 
 {
  $success = true;
  $message = "Successfully Uploaded";
 }
 else 
 {
  $success = false;
  $message = "Error while uploading";
 }
}
else 
{
 $success = false;
 $message = "Required Field Missing";
}

$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);

?>

Function to upload multiple file:

Add the following code to upload multiple files in your activity/fragment
// Uploading Image/Video
 private void uploadMultipleFiles() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
        File file1 = new File(mediaPath1);

        // Parsing any Media type file
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

        MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
        MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
        call.enqueue(new Callback<serverresponse>() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

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

            }
        });
    }
ApiConfig.java
Add the following interface for uploading multiple files in ApiConfig.java
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call <serverresponse> uploadMulFile(@Part MultipartBody.Part file1, @Part MultipartBody.Part file2);

Full Source Code

Create MainActivity.java and Paste the following lines
This Code is Updated with Multiple File Upload.
public class MainActivity extends AppCompatActivity {

    Button btnUpload, btnMulUpload, btnPickImage, btnPickVideo;
    String mediaPath, mediaPath1;
    ImageView imgView;
    String[] mediaColumns = {MediaStore.Video.Media._ID};
    ProgressDialog progressDialog;
    TextView str1, str2;

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

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Uploading...");

        btnUpload = (Button) findViewById(R.id.upload);
        btnMulUpload = (Button) findViewById(R.id.uploadMultiple);
        btnPickImage = (Button) findViewById(R.id.pick_img);
        btnPickVideo = (Button) findViewById(R.id.pick_vdo);
        imgView = (ImageView) findViewById(R.id.preview);
        str1 = (TextView) findViewById(R.id.filename1);
        str2 = (TextView) findViewById(R.id.filename2);

        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadFile();
            }
        });

        btnMulUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadMultipleFiles();
            }
        });

        btnPickImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, 0);
            }
        });

        // Video must be low in Memory or need to be compressed before uploading...
        btnPickVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, 1);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == 0 && resultCode == RESULT_OK && null != data) {

                // Get the Image from data
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mediaPath = cursor.getString(columnIndex);
                str1.setText(mediaPath);
                // Set the Image in ImageView for Previewing the Media
                imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();

            } // When an Video is picked
            else if (requestCode == 1 && resultCode == RESULT_OK && null != data) {

                // Get the Video from data
                Uri selectedVideo = data.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

                mediaPath1 = cursor.getString(columnIndex);
                str2.setText(mediaPath1);
                // Set the Video Thumb in ImageView Previewing the Media
                imgView.setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this, selectedVideo));
                cursor.close();

            } else {
                Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }

    }

    // Providing Thumbnail For Selected Image
    public Bitmap getThumbnailPathForLocalFile(Activity context, Uri fileUri) {
        long fileId = getFileId(context, fileUri);
        return MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
    }

    // Getting Selected File ID
    public long getFileId(Activity context, Uri fileUri) {
        Cursor cursor = context.managedQuery(fileUri, mediaColumns, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
            return cursor.getInt(columnIndex);
        }
        return 0;
    }

    // Uploading Image/Video
    private void uploadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadFile(fileToUpload, filename);
        call.enqueue(new Callback<serverresponse>() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

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

            }
        });
    }

    // Uploading Image/Video
    private void uploadMultipleFiles() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
        File file1 = new File(mediaPath1);

        // Parsing any Media type file
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

        MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
        MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

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

            }
        });
    }

}

Download Code:

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Post your doubts and comments in the comments section.  

Featured In  Created By How to use this Library: Gradle:  compile 'androidmads.updatehandler:updatehandler:1.0.3' M...

Automatic Update Checker for Android - Library Automatic Update Checker for Android - Library

A blog about android developement

Automatic Update Checker for Android - Library

Featured In 
Android Arsenal-UpdateHandler
Created By

How to use this Library:

Gradle: 
compile 'androidmads.updatehandler:updatehandler:1.0.3'
Maven:
<dependency>
  <groupId>androidmads.updatehandler</groupId>
  <artifactId>updatehandler</artifactId>
  <version>1.0.3</version>
  <type>pom</type>
</dependency>
How to use this Library: 
After importing this library, use the following lines to check version update for your application automatically.
/** 
* This library works in release mode only with the same JKS key used for 
* your Previous Version
*/
UpdateHandler updateHandler = new UpdateHandler(MainActivity.this);
// to start version checker
updateHandler.start();
// prompting intervals
updateHandler.setCount(2);
// to print new features added automatically
updateHandler.setWhatsNew(true);
// to enable or show default dialog prompt for version update
updateHandler.showDefaultAlert(true);
// listener for custom update prompt
updateHandler.setOnUpdateListener(new UpdateListener() {
    @Override
    public void onUpdateFound(boolean newVersion, String whatsNew) {
        Log.v("Update", String.valueOf(newVersion));
        Log.v("Update", whatsNew);
    }
});

Demo:
Alert Without What' New


Alert With What' New


Update Prompt with Custom Listener

Hello friends, today we will see a simple CRUD Example in Android using Active Android Library .This is a perfect alternate for SQLite i...

CRUD Operation using Active Android CRUD Operation using Active Android

A blog about android developement

CRUD Operation using Active Android
Hello friends, today we will see a simple CRUD Example in Android using Active Android Library.This is a perfect alternate for SQLite in Android.

About Active Android

ActiveAndroid is an active record style ORM (object relational mapper). What does that mean exactly? Well, ActiveAndroid allows you to save and retrieve SQLite database records without ever writing a single SQL statement. ActiveAndroid takes care of all the setup for Accessing the database in android.

Project Setup

In the project you just created go to the app level build.gradle file and add these lines.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

    //Add this line
    compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'
}

repositories {
    jcenter()
    //Add these two lines
    mavenCentral()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}

AndroidManifest.xml
Don't forget to add the following lines in your manifest fileAdd the following lines to initialize the ActiveAndroid.
<meta-data
    android:name="AA_DB_NAME"
    android:value="test.db" />
<meta-data
    android:name="AA_DB_VERSION"
    android:value="5" />
<meta-data
    android:name="AA_MODELS"
    android:value="com.androidmads.actvieandroidexample.Details" />
Create a class named MyApplication to initialize ActiveAndroid library. Add this Class in manifest file within application tag.
package com.androidmads.actvieandroidexample.app;

import android.app.Application;
import com.activeandroid.ActiveAndroid;

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //Initializing Active Android
        ActiveAndroid.initialize(this);
    }
}
Create a Model class for Each table extended with activeandroid
package com.androidmads.actvieandroidexample;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

/**
 * Created by Mushtaq on 27-05-2016.
 */
@Table(name = "Details")
public class Details extends Model {

    @Column(name = "Name")
    public String name;

    @Column(name = "Age")
    public String age;

}
Create a layout file and paste the following lines
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dp"
        android:text="@string/app_name"
        android:textSize="16sp"
        android:background="@drawable/tv_bg"/>

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:hint="@string/hint_enter_name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:hint="@string/hint_enter_age"
        android:inputType="number" />

    <EditText
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:hint="@string/hint_enter_id"
        android:inputType="number" />

    <Button
        android:id="@+id/insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/insert" />

    <Button
        android:id="@+id/readAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/read_all" />

    <Button
        android:id="@+id/read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/read_one" />

    <Button
        android:id="@+id/deleteAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/delete_all" />

    <Button
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/delete" />

    <Button
        android:id="@+id/update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/update" />
</LinearLayout>
To insert data into the Database use Model.save()
// Save Data
public void insertData(Details details){
    id = details.save();
    Log.v("id_value", String.valueOf(id));
    recreate();
}
To read all data from the Database use query as in the following
// Read All Data
Select().from(Details.class).orderBy("id ASC").execute();
To read data from the Database use query as in the following
// Read Data
Select().from(Details.class).where("id = ?", id).executeSingle();
To delete or delete All data from the Database use new Delete() query as in the following
// delete all 
new Delete().from(Details.class).execute();
// delete particular data 
Details.delete(Details.class , id);// where id is long type data
To update data from the Database use save() as in insert query as in the following. But, you have to get Primary id
// Update Data
Details details = Select().from(Details.class).where("id = ?", id).executeSingle();
details.name = holder.edt_name.getText().toString().trim();
details.age = holder.edt_age.getText().toString().trim();
details.save();

Download Full Source Code

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Post your doubts and comments in the comments section.  

Hello friends, In this Tutorial. In this post, I will show you how to use Accessibility Service for Android. Before that, we need to know ...

How Create a Accessibility Service in Android How Create a Accessibility Service in Android

A blog about android developement

How Create a Accessibility Service in Android

Hello friends, In this Tutorial. In this post, I will show you how to use Accessibility Service for Android. Before that, we need to know What is Accessibility Service.

Accessibility Service

Here, I am taking an example for creating Virtual Service Button instead of Default Back Button.

Project Structure:

Create a new Project in Android Studio with the required Specifications.

Codes:

AndroidManifest.xml
Don't forget to add the following permission in your manifest file.
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Don't forget to add the following Lines in your manifest file to create service for your application.
<service
    android:name=".MyService"
    android:label="@string/app_name"
    android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
       <intent-filter>
          <action android:name="android.accessibilityservice.AccessibilityService" />
       </intent-filter>
 </service>
MainActivity.java
Open MainActivity.java and replace it with the following code
package example.backbutton;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        // Permission for Manifest.permission.SYSTEM_ALERT_WINDOW in Android M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(getApplicationContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1);
            }
        }

  // Code to start the Service
        startService(new Intent(getApplication(), MyService.class));
    }
}
MyService.java
Open MyService.java and replace it with the following code
package example.backbutton;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.ImageView;

public class MyService extends AccessibilityService {

    WindowManager windowManager;
    ImageView back,home,notification,minimize;
    WindowManager.LayoutParams params;
    AccessibilityService service;

    @SuppressLint("RtlHardcoded")
    @Override
    public void onCreate() {
        super.onCreate();

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        back = new ImageView(this);
        home = new ImageView(this);
        minimize = new ImageView(this);
        notification = new ImageView(this);

        back.setImageResource(R.mipmap.ic_back);
        home.setImageResource(R.mipmap.ic_home);
        minimize.setImageResource(R.mipmap.ic_min);
        notification.setImageResource(R.mipmap.ic_notification);

  params= new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.CENTER_VERTICAL|Gravity.RIGHT;
        params.x = 10;
        params.y = 50;

        windowManager.addView(home, params);

        params= new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.CENTER_VERTICAL|Gravity.RIGHT;
        params.x = 10;
        params.y = 100;

        windowManager.addView(minimize, params);

        params= new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.CENTER_VERTICAL|Gravity.RIGHT;
        params.x = 10;
        params.y = 150;

        windowManager.addView(notification, params);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        notification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        minimize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

    }

    @Override
    public void onInterrupt() {

    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d("TAG", "onServiceConnected");
    }

}

Important Note

Finally go to Settings --> Accessibility --> Your Application --> Turn ON

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSON...

How to Perform Rest API using Retrofit in Android (Part-2) How to Perform Rest API using Retrofit in Android (Part-2)

A blog about android developement

How to Perform Rest API using Retrofit in Android (Part-2)

How to Perform Rest API using Retrofit in Android

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley.In Previous Part, I showed the PHP Scripts to perform basic CRUD operations. In this part, Contains the informations about how to perform Retrofit Operations in Android.

Project Structure:

Create New Project in Android Studio with blank activity as in the following.

We need Retrofit Library for working with that. For Android Studio you just need to paste below line of code under dependency of build.gradle file.
compile 'com.squareup.retrofit:retrofit:1.9.0'
For eclipse users download jar file from below link and add to you project.
Download jar

AndroidManifest.xml

Don't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>

AppConfig.class

Create AppConfig.class and replace it with the following code.It is used as helper class for web services
package androidmads.example.retrofitexample.helper;

import com.google.gson.JsonElement;

import retrofit.Callback;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;

public class AppConfig {

 public interface insert {
  @FormUrlEncoded
  @POST("/personal_details/insertData.php")
  void insertData(
    @Field("name") String name,
    @Field("age") String age,
    @Field("mobile") String mobile,
    @Field("email") String email,
    Callback<Response> callback);
 }

 public interface read {
  @GET("/personal_details/displayAll.php")
  void readData(Callback<JsonElement> callback);
 }

 public interface delete {
  @FormUrlEncoded
  @POST("/personal_details/deleteData.php")
  void deleteData(
    @Field("id") String id,
    Callback<Response> callback);
 }

 public interface update {
  @FormUrlEncoded
  @POST("/personal_details/updateData.php")
  void updateData(
    @Field("id") String id,
    @Field("name") String name,
    @Field("age") String age,
    @Field("mobile") String mobile,
    @Field("email") String email,
    Callback<Response> callback);
 }
}

activity_main.xml

Create activity_main.xml and replace it with the following code
<?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:orientation="vertical"
 android:padding="@dimen/activity_vertical_margin"
 tools:context="example.retrofit.MainActivity">

 <EditText
  android:id="@+id/name"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="center"
  android:hint="@string/name_hint"
  android:inputType="textPersonName" />
   
 <EditText
  android:id="@+id/age"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="center"
  android:hint="@string/age_hint"
  android:inputType="number" />
 
 <EditText
  android:id="@+id/mobile"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="center"
  android:hint="@string/mob_no_hint"
  android:inputType="phone"  />
 
 <EditText
  android:id="@+id/mail"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="center"
  android:hint="@string/mail_hint"
  android:inputType="textEmailAddress" />

 <Button
  android:gravity="center"
  android:id="@+id/insert"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="@string/ins_hint" />

 <Button
  android:gravity="center"
  android:id="@+id/retrieve"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="@string/read_hint" />

</LinearLayout>

MainActivity.class

Create MainActivity.class and replace it with the following code
package androidmads.example.retrofitexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import androidmads.example.retrofitexample.helper.AppConfig;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainActivity extends AppCompatActivity {

 String BASE_URL = "http://192.168.1.32";

 EditText edt_name, edt_age, edt_mobile, edt_mail;
 Button btn_insert, btn_display;

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

  edt_name = (EditText) findViewById(R.id.name);
  edt_age = (EditText) findViewById(R.id.age);
  edt_mobile = (EditText) findViewById(R.id.mobile);
  edt_mail = (EditText) findViewById(R.id.mail);
  btn_insert = (Button) findViewById(R.id.insert);
  btn_display = (Button) findViewById(R.id.retrieve);

  btn_insert.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    insert_data();
   }
  });

  btn_display.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent i = new Intent(getApplicationContext(),DisplayData.class);
    startActivity(i);
   }
  });
 }

 public void insert_data() {

  RestAdapter adapter = new RestAdapter.Builder()
    .setEndpoint(BASE_URL) //Setting the Root URL
    .build();

  AppConfig.insert api = adapter.create(AppConfig.insert.class);

  api.insertData(
    edt_name.getText().toString(),
    edt_age.getText().toString(),
    edt_mobile.getText().toString(),
    edt_mail.getText().toString(),
    new Callback() {
     @Override
     public void success(Response result, Response response) {

      try {

      BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
      String resp;
      resp = reader.readLine();
      Log.d("success", "" + resp);

      JSONObject jObj = new JSONObject(resp);
      int success = jObj.getInt("success");

      if(success == 1){
        Toast.makeText(getApplicationContext(), "Successfully inserted", Toast.LENGTH_SHORT).show();
      } else{
         Toast.makeText(getApplicationContext(), "Insertion Failed", Toast.LENGTH_SHORT).show();
      }

     } catch (IOException e) {
      Log.d("Exception", e.toString());
     } catch (JSONException e) {
      Log.d("JsonException", e.toString());
     }
    }

    @Override
    public void failure(RetrofitError error) {
      Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
     }
    }
  );
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.menu_main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // Handle action bar item clicks here. The action bar will
  // automatically handle clicks on the Home/Up button, so long
  // as you specify a parent activity in AndroidManifest.xml.
  int id = item.getItemId();

  //noinspection SimplifiableIfStatement
  if (id == R.id.action_settings) {
   return true;
  }

  return super.onOptionsItemSelected(item);
 }
}

DisplayData.class

Create DisplayData.class and replace it with the following code
package androidmads.example.retrofitexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.JsonElement;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import androidmads.example.retrofitexample.helper.AppConfig;
import androidmads.example.retrofitexample.helper.ListViewAdapter;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class DisplayData extends AppCompatActivity {

 String BASE_URL = "http://192.168.1.32";

 ListView details_list;
 ListViewAdapter displayAdapter;
 ArrayList id = new ArrayList<>();
 ArrayList name = new ArrayList<>();
 ArrayList age = new ArrayList<>();
 ArrayList mobile = new ArrayList<>();
 ArrayList email = new ArrayList<>();

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

  details_list = (ListView) findViewById(R.id.retrieve);
  displayAdapter = new ListViewAdapter(getApplicationContext(), id, name, age, mobile, email);
  displayData();

  details_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
    Intent i = new Intent(getApplicationContext(),UpdateData.class);
    i.putExtra("id",id.get(position));
    i.putExtra("name",name.get(position));
    i.putExtra("age",age.get(position));
    i.putExtra("mobile",mobile.get(position));
    i.putExtra("email", email.get(position));
    startActivity(i);

   }
  });

  details_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
   @Override
   public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long ids) {
    delete(id.get(position));
    return true;
   }
  });
 }

 public void displayData() {

  RestAdapter adapter = new RestAdapter.Builder()
    .setEndpoint(BASE_URL) //Setting the Root URL
    .build();

  AppConfig.read api = adapter.create(AppConfig.read.class);
  api.readData(new Callback() {
      @Override
      public void success(JsonElement result, Response response) {

       String myResponse = result.toString();
       Log.d("response", "" + myResponse);
       try {
        JSONObject jObj = new JSONObject(myResponse);
        int success = jObj.getInt("success");
        if (success == 1) {
         JSONArray jsonArray = jObj.getJSONArray("details");
         for (int i = 0; i < jsonArray.length(); i++) {
         JSONObject jo = jsonArray.getJSONObject(i);
         id.add(jo.getString("id"));       name.add(jo.getString("name"));       age.add(jo.getString("age"));       mobile.add(jo.getString("mobile"));       email.add(jo.getString("email"));
          details_list.setAdapter(displayAdapter);
        } else {
        Toast.makeText(getApplicationContext(), "No Details Found", Toast.LENGTH_SHORT).show();
        }
       } catch (JSONException e) {
        Log.d("exception", e.toString());
       }
      }

      @Override
      public void failure(RetrofitError error) {
       Log.d("Failure", error.toString());
       Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
      }
     }
  );
 }

 public void delete(String id){

  RestAdapter adapter = new RestAdapter.Builder()
    .setEndpoint(BASE_URL) //Setting the Root URL
    .build();

  AppConfig.delete api = adapter.create(AppConfig.delete.class);
  api.deleteData(
    id,
    new Callback() {
     @Override
     public void success(Response result, Response response) {

      try {

       BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
       String resp;
       resp = reader.readLine();
       Log.d("success", "" + resp);

       JSONObject jObj = new JSONObject(resp);
       int success = jObj.getInt("success");

       if(success == 1){
         Toast.makeText(getApplicationContext(), "Successfully deleted", Toast.LENGTH_SHORT).show();
        recreate();
       } else{
        Toast.makeText(getApplicationContext(), "Deletion Failed", Toast.LENGTH_SHORT).show();
       }
      } catch (IOException e) {
       Log.d("Exception", e.toString());
      } catch (JSONException e) {
       Log.d("JsonException", e.toString());
      }
     }

     @Override
     public void failure(RetrofitError error) {
      Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
      }
     }
   );

  }

}

ListViewAdapter.class

Create ListViewAdapter.class and replace it with the following code
package androidmads.example.retrofitexample.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
 
import androidmads.example.retrofitexample.R;

public class ListViewAdapter extends BaseAdapter {

 private final Context context;
 private final ArrayList id;
 private final ArrayList name;
 private final ArrayList age;
 private final ArrayList mobile;
 private final ArrayList email;
 LayoutInflater layoutInflater;

 public ListViewAdapter(Context ctx, ArrayList id, ArrayList name, ArrayList age,
      ArrayList mobile, ArrayList email) {
  this.context = ctx;
  this.id = id;
  this.name = name;
  this.age = age;
  this.mobile = mobile;
  this.email = email;

 }

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

 @Override
 public Object getItem(int position) {
  return position;
 }

 @Override
 public long getItemId(int position) {
  return position;
 }

 @SuppressLint("ViewHolder")
 @Override
 public View getView(final int position, View view, ViewGroup parent) {

  Holder holder = new Holder();
  layoutInflater = (LayoutInflater) context.getSystemService
    (Context.LAYOUT_INFLATER_SERVICE);

  view = layoutInflater.inflate(R.layout.list_item, null);
  holder.txt_name=(TextView)view.findViewById(R.id.name);
  holder.txt_age=(TextView)view.findViewById(R.id.age);
  holder.txt_mobile=(TextView)view.findViewById(R.id.mobile);
  holder.txt_mail=(TextView)view.findViewById(R.id.mail);

  holder.txt_name.setText(name.get(position));
  holder.txt_age.setText(age.get(position));
  holder.txt_mobile.setText(mobile.get(position));
  holder.txt_mail.setText(email.get(position));

  return view;
 }

 static class Holder {
  TextView txt_name,txt_age,txt_mobile,txt_mail;
 }
}

UpdateData.class

Create UpdateData.class and replace it with the following code
package androidmads.example.retrofitexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.JsonElement;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import androidmads.example.retrofitexample.helper.AppConfig;
import androidmads.example.retrofitexample.helper.ListViewAdapter;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class UpdateData extends AppCompatActivity {

 String BASE_URL = "http://192.168.1.32";

 EditText edt_name, edt_age, edt_mobile, edt_mail;
 Button btn_update;

 String id, name, age, mobile, email;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_update);

  edt_name = (EditText) findViewById(R.id.name);
  edt_age = (EditText) findViewById(R.id.age);
  edt_mobile = (EditText) findViewById(R.id.mobile);
  edt_mail = (EditText) findViewById(R.id.mail);
  btn_update = (Button) findViewById(R.id.update);

  Intent i = getIntent();
  id = i.getStringExtra("id");
  name = i.getStringExtra("name");
  age = i.getStringExtra("age");
  mobile = i.getStringExtra("mobile");
  email = i.getStringExtra("email");

  edt_name.setText(name);
  edt_age.setText(age);
  edt_mobile.setText(mobile);
  edt_mail.setText(email);

  btn_update.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
     
    // "id" is used as a reference for modification in Data
    update_data(id);

   }
  });

 }

 public void update_data(String id) {

  RestAdapter adapter = new RestAdapter.Builder()
    .setEndpoint(BASE_URL) //Setting the Root URL
    .build();

  AppConfig.update api = adapter.create(AppConfig.update.class);
  api.updateData(
    id,
    edt_name.getText().toString(),
    edt_age.getText().toString(),
    edt_mobile.getText().toString(),
    edt_mail.getText().toString(),
    new Callback() {
     @Override
     public void success(Response result, Response response) {

      try {

       BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
       String resp;
       resp = reader.readLine();
       Log.d("success", "" + resp);
       JSONObject jObj = new JSONObject(resp);
       int success = jObj.getInt("success");

       if (success == 1) {
       Toast.makeText(getApplicationContext(), "Successfully updated", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getApplicationContext(),DisplayData.class));
        finish();
       } else {
         Toast.makeText(getApplicationContext(), "Update Failed", Toast.LENGTH_SHORT).show();
       }
      } catch (IOException e) {
       Log.d("Exception", e.toString());
      } catch (JSONException e) {
       Log.d("JsonException", e.toString());
      }
     }

     @Override
     public void failure(RetrofitError error) {
      Toast.makeText(UpdateData.this, error.toString(), Toast.LENGTH_LONG).show();
     }
    }
  );
 }

}

References:

  1. MakeInfo:Retrofit Android Tutorial
  2. Retrofit Android Example

Download Full Source Code

Download Code