Showing posts with label android. Show all posts

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

android

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


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

android

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.

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

android

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

android

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.  

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

android

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

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, JSONPars...

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

A blog about android developement

android

Rest using Retrofit
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. This post is Split into Two Parts.
  1. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations.
  2. Second Part Contains how to perform Retrofit Operations in Android.

Architecture of Retrofit Web Service

We need 3 Things for Complete Retrofit Architecture.
  1. RestAdapter
  2. An Interface with all networking methods and parameters.
  3. Getter Setter Class to save data coming from server.

Project Structure:

Create MySQL DataBase and PHP Scripts.
Following image shows my database structure.

PHP Scripts:

I created db_config.php which contains the script to connect DB.
<?php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "retrofit_example");

$db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
 
if($db == false){
 echo "No connection";
}                        
?>
I created db_function.php which contains the script to execute queries.
<?php
include("db_config.php");
 
function insertData($name,$age,$mobile,$email){
 global $db;
 $result=mysqli_query($db , "INSERT INTO personal_detail(name,age,mobile,email) VALUES('$name','$age','$mobile','$email')")or die(mysqli_error($db));
 return $result;
}

function displayAll(){
 global $db;
 $result=mysqli_query($db , "SELECT * FROM personal_detail")or die(mysqli_error($db));
 return $result;
}

function deleteData($id){
 global $db;
 $result=mysqli_query($db , "DELETE FROM personal_detail WHERE id = '$id'")or die(mysqli_error($db));
 return $result;
}

function updateData($id,$name,$age,$mobile,$email){
 global $db;
 $result=mysqli_query($db , "UPDATE `personal_detail` SET `name`='$name',`age`='$age', `mobile`='$mobile', `email`='$email' WHERE id = '$id'")or die(mysqli_error($db));
 return $result;
}
?>
I created insertData.php which contains the script to insert data.
<?php
include ('db_function.php');
$response = array();
 
//Getting post data 
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];
$mobile = $_REQUEST['mobile'];
$email = $_REQUEST['email'];

if (isset($_REQUEST['name']) && isset($_REQUEST['age']) && isset($_REQUEST['mobile']) && isset($_REQUEST['email'])){
 
 $result=insertData($name,$age,$mobile,$email);
 if ($result) {
  $response["success"] = 1;
  $response["message"] = "Successfully saved"; 
  echo json_encode($response);
 } 
 else {
  $response["success"] = 0;
  $response["message"] = "Oops! An error occurred."; 
  echo json_encode($response);
 }
} 
else {
 $response["success"] = 0;
 $response["message"] = "Required field(s) is missing";  
 echo json_encode($response);
}
?>
I created displayAll.php which contains the script to display all data from DB.
<?php
include ('db_function.php');
 
$response = array();
$result = displayAll(); 

if(mysqli_num_rows($result)>0) {

 $response["details"] = array();
 while ($row = mysqli_fetch_array($result)){
  $data = array();
  $data["id"]=$row["id"];
  $data["name"]=$row["name"];
  $data["age"]=$row["age"];
  $data["mobile"]=$row["mobile"];
  $data["email"]=$row["email"];
  array_push($response["details"], $data);
 }
  if($result){
   $response["success"] = 1;
   $response["message"] = "Successfully Displayed";
   echo json_encode($response);
  }
  else{
   $response["success"] = 0;
   $response["message"] = "Try Again";
   echo json_encode($response);
  }
}
else {
 // no results found
 $response["success"] = 0;
 $response["message"] = "No Details Found";
 echo json_encode($response);
}
if($db == true){
 mysqli_close($db); //Closing the Connection
}
?>
I created deleteData.php which contains the script to delete a data from DB.
<?php
include ('db_function.php');
$response = array();

//Getting post data 
$id = $_REQUEST["id"];

if(isset($id)){
 
 $result = deleteData($id); 

 if($result){
  $response["success"] = 1;
  $response["message"] = "Successfully Deleted";
  echo json_encode($response);
 }
 else{
  $response["success"] = 0;
  $response["message"] = "Try Again";
  echo json_encode($response);
 }
}
else {
 // no results found
 $response["success"] = 0;
 $response["message"] = "Required Fields are Missing";
 echo json_encode($response);
}
if($db == true){
 mysqli_close($db);
}
?>
I created updateData.php which contains the script to update a data from DB.
<?php
include ('db_function.php');
$response = array();
 
//Getting post data 
$id = $_REQUEST["id"];
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];
$mobile = $_REQUEST['mobile'];
$email = $_REQUEST['email'];

if (isset($id) && isset($name) && isset($age) && isset($mobile) && isset($email)){
 
 $result=updateData($id,$name,$age,$mobile,$email);
 if ($result) {
  $response["success"] = 1;
  $response["message"] = "Successfully updated"; 
  echo json_encode($response);
 } 
 else {
  $response["success"] = 0;
  $response["message"] = "Oops! An error occurred."; 
  echo json_encode($response);
 }
} 
else {
 $response["success"] = 0;
 $response["message"] = "Required field(s) is missing";  
 echo json_encode($response);
}
?>

References:

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

Goto Next Part:

In this post, I will show you how to Create Digital Signature in Android. Project Structure: Create a new Project in Eclipse/Android ...

How to Create a Digital Signature Application in Android How to Create a Digital Signature Application in Android

A blog about android developement

android

How to Create a Digital Signature Application in Android
In this post, I will show you how to Create Digital Signature in Android.

Project Structure:

Create a new Project in Eclipse/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.WRITE_EXTERNAL_STORAGE"></uses-permission>
color.xml
Create color.xml and replace it with the following code
<resources>
    <color name="ColorPrimaryDark">#3367d6</color>
    <color name="ColorPrimary">#4285f4</color>
</resources>
strings.xml
Create strings.xml and replace it with the following code
<resources>
 <string name="app_name">Digital Signature</string>
 <string name="hello_world">Hello world!</string>
 <string name="action_settings">Settings</string>
 <string name="hint_sign">Get Signature</string>
 <string name="dialog_title">SIGN HERE</string>
 <string name="hint_cancel">Cancel</string>
 <string name="hint_clear">Clear</string>
 <string name="hint_save">Save</string>
</resources>
activity_toolbar.xml
Create activity_toolbar.xml and replace it with the following code
<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="wrap_content"
    tools:context="@string/app_name">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/AppTheme"
        app:popupTheme="@style/AppTheme" />

</RelativeLayout>
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"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/white">

    <include layout="@layout/activity_toolbar" />

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

        <Button
            android:id="@+id/signature"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hint_sign"
            android:padding="5dp"
            android:background="@color/ColorPrimary" />
    </LinearLayout>

</LinearLayout>
dialog_signature.xml
Create dialog_signature.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:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="400dp"
    android:orientation="vertical"
    android:background="@android:color/white">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/ColorPrimaryDark"
        android:text="@string/dialog_title"
        android:textColor="@android:color/white"
        android:padding="5dp"
        android:gravity="center"/>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:background="@android:color/white">

        <Button
            android:id="@+id/cancel"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="@string/hint_cancel"
            tools:ignore="ButtonStyle"
            android:textColor="@android:color/white"
            android:background="@color/ColorPrimary" />

        <Button
            android:id="@+id/clear"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="@string/hint_clear"
            tools:ignore="ButtonStyle"
            android:textColor="@android:color/white"
            android:background="@color/ColorPrimary" />

        <Button
            android:id="@+id/getsign"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="@string/hint_save"
            tools:ignore="ButtonStyle"
            android:textColor="@android:color/white"
            android:background="@color/ColorPrimary" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:orientation="vertical" />

</LinearLayout>
MainActivity.java
Open MainActivity.java and replace it with the following code
package com.example.digitalsignature;
 
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
 
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
 
public class MainActivity extends AppCompatActivity {

 Toolbar toolbar;
 Button btn_get_sign, mClear, mGetSign, mCancel;

 File file;
 Dialog dialog;
 LinearLayout mContent;
 View view;
 signature mSignature;
 Bitmap bitmap;

 // Creating Separate Directory for saving Generated Images
 String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/";
 String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
 String StoredPath = DIRECTORY + pic_name + ".png";

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

  // Setting ToolBar as ActionBar
  toolbar = (Toolbar) findViewById(R.id.toolbar);
  setSupportActionBar(toolbar);

  // Button to open signature panel
  btn_get_sign = (Button) findViewById(R.id.signature);

  // Method to create Directory, if the Directory doesn't exists
  file = new File(DIRECTORY);
  if (!file.exists()) {
   file.mkdir();
  }

  // Dialog Function
  dialog = new Dialog(MainActivity.this);
  // Removing the features of Normal Dialogs
  dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
  dialog.setContentView(R.layout.dialog_signature);
  dialog.setCancelable(true);

  btn_get_sign.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
   // Function call for Digital Signature
    dialog_action();

   }
  });
 }
 // Function for Digital Signature
 public void dialog_action() {
 
  mContent = (LinearLayout) dialog.findViewById(R.id.linearLayout);
  mSignature = new signature(getApplicationContext(), null);
  mSignature.setBackgroundColor(Color.WHITE);
  // Dynamically generating Layout through java code
  mContent.addView(mSignature, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
  mClear = (Button) dialog.findViewById(R.id.clear);
  mGetSign = (Button) dialog.findViewById(R.id.getsign);
  mGetSign.setEnabled(false);
  mCancel = (Button) dialog.findViewById(R.id.cancel);
  view = mContent;

  mClear.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    Log.v("tag", "Panel Cleared");
    mSignature.clear();
    mGetSign.setEnabled(false);
   }
  });
  mGetSign.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    Log.v("tag", "Panel Saved");
    view.setDrawingCacheEnabled(true);
    mSignature.save(view, StoredPath);
    dialog.dismiss();
    Toast.makeText(getApplicationContext(), "Successfully Saved", Toast.LENGTH_SHORT).show();
    // Calling the same class
    recreate();
   }
  });
  mCancel.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    Log.v("tag", "Panel Cancelled");
    dialog.dismiss();
    // Calling the same class
    recreate();
   }
  });
  dialog.show();
 }

 public class signature extends View {
  private static final float STROKE_WIDTH = 5f;
  private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
  private Paint paint = new Paint();
  private Path path = new Path();

  private float lastTouchX;
  private float lastTouchY;
  private final RectF dirtyRect = new RectF();

  public signature(Context context, AttributeSet attrs) {
   super(context, attrs);
   paint.setAntiAlias(true);
   paint.setColor(Color.BLACK);
   paint.setStyle(Paint.Style.STROKE);
   paint.setStrokeJoin(Paint.Join.ROUND);
   paint.setStrokeWidth(STROKE_WIDTH);
  }

  public void save(View v, String StoredPath) {
   Log.v("tag", "Width: " + v.getWidth());
   Log.v("tag", "Height: " + v.getHeight());
   if (bitmap == null) {
    bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
   }
   Canvas canvas = new Canvas(bitmap);
   try {
    // Output the file
    FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
    v.draw(canvas);
    // Convert the output file to Image such as .png
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
    mFileOutStream.flush();
    mFileOutStream.close();
   } catch (Exception e) {
    Log.v("log_tag", e.toString());
   }
  }

  public void clear() {
   path.reset();
   invalidate();
  }

  @Override
  protected void onDraw(Canvas canvas) {
   canvas.drawPath(path, paint);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
   float eventX = event.getX();
   float eventY = event.getY();
   mGetSign.setEnabled(true);

   switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
     path.moveTo(eventX, eventY);
     lastTouchX = eventX;
     lastTouchY = eventY;
     return true;

    case MotionEvent.ACTION_MOVE:
 
    case MotionEvent.ACTION_UP:
     resetDirtyRect(eventX, eventY);
     int historySize = event.getHistorySize();
     for (int i = 0; i < historySize; i++) {
      float historicalX = event.getHistoricalX(i);
      float historicalY = event.getHistoricalY(i);
      expandDirtyRect(historicalX, historicalY);
      path.lineTo(historicalX, historicalY);
     }
     path.lineTo(eventX, eventY);
     break;
    default:
     debug("Ignored touch event: " + event.toString());
     return false;
   }

   invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
     (int) (dirtyRect.top - HALF_STROKE_WIDTH),
     (int) (dirtyRect.right + HALF_STROKE_WIDTH),
     (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

    lastTouchX = eventX;
    lastTouchY = eventY;

    return true;
  }

  private void debug(String string) {
   Log.v("log_tag", string);
  }

  private void expandDirtyRect(float historicalX, float historicalY) {
   if (historicalX < dirtyRect.left) {
    dirtyRect.left = historicalX;
   } else if (historicalX > dirtyRect.right) {
    dirtyRect.right = historicalX;
   }

   if (historicalY < dirtyRect.top) {
    dirtyRect.top = historicalY;
   } else if (historicalY > dirtyRect.bottom) {
    dirtyRect.bottom = historicalY;
   }
  }

  private void resetDirtyRect(float eventX, float eventY) {
   dirtyRect.left = Math.min(lastTouchX, eventX);
   dirtyRect.right = Math.max(lastTouchX, eventX);
   dirtyRect.top = Math.min(lastTouchY, eventY);
   dirtyRect.bottom = Math.max(lastTouchY, eventY);
  }
 }
}

Screen Shots

Screen 1
Screen 2
Screen 3

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.  

In this post, I will show you how to add and remove grids in GridView. And also, I am explained about SharedPreferences. Project Structure...

How to Add and Remove Grids in GridView Dynamically How to Add and Remove Grids in GridView Dynamically

A blog about android developement

android


In this post, I will show you how to add and remove grids in GridView. And also, I am explained about SharedPreferences.
Project Structure:
Create a new Project in Eclipse/Android Studio with the required Specifications.
Codes:
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"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:weightSum="5"
 android:orientation="vertical">

 <GridView
  android:id="@+id/gridView1"
  android:layout_width="match_parent"
  android:layout_height="0dp"
  android:columnWidth="100dp"
  android:gravity="center"
  android:numColumns="auto_fit"
  android:stretchMode="columnWidth"
  android:layout_weight="4.5"/>

 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="0dp"
  android:layout_weight="0.5"
  android:orientation="horizontal"
  android:weightSum="2" >

  <Button
   android:id="@+id/btn_add"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:background="@null"
   android:text="@string/hint_add"/>

  <Button
   android:id="@+id/btn_remove"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:background="@null"
   android:text="@string/hint_remove"/>

 </LinearLayout>

</LinearLayout>

activity_main_single.xml
Create activity_main_single.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"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="5dp"
 android:orientation="vertical"
 android:gravity="center">

 <ImageView
  android:id="@+id/grid_item_image"
  android:layout_width="50dp"
  android:layout_height="50dp"
  android:src="@mipmap/ic_launcher"
  android:contentDescription="@string/app_name"
  android:gravity="center" />

 <TextView
  android:id="@+id/grid_item_label"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="@string/label"
  android:textSize="15sp"
  android:gravity="center" />

</LinearLayout>

MainActivity.java
Open MainActivity.java and replace it with the following code
package com.example.grid;
 
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
 
import com.example.grid.adapter.ImageAdapter;
 
import java.util.ArrayList;
 
public class MainActivity extends Activity {

 GridView gridView;
 Button btn_add, btn_remove;
 ImageAdapter adapter;
 ArrayList<String> list;
 SharedPreferences sharedPreferences;
 SharedPreferences.Editor editor;
 String Pref_Name = "Grid";
 int count = 3;

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

  gridView = (GridView) findViewById(R.id.gridView1);
  btn_add = (Button) findViewById(R.id.btn_add);
  btn_remove = (Button) findViewById(R.id.btn_remove);

  sharedPreferences = getSharedPreferences(Pref_Name, MODE_PRIVATE);
  count = sharedPreferences.getInt("count", 3);

  list = new ArrayList<>();

  for (int i = 0; i < count; i++) {
   list.add("");
  }

  adapter = new ImageAdapter(this, list);
  gridView.setAdapter(adapter);

  btn_add.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    list.add("");
    adapter.notifyDataSetChanged();
    gridView.setAdapter(adapter);

    editor = sharedPreferences.edit();
    editor.putInt("count", count + 1);
    editor.apply();

    Toast.makeText(getApplicationContext(), "One Image Added", Toast.LENGTH_SHORT).show();

   }
  });

  btn_remove.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    list.remove("");
    adapter.notifyDataSetChanged();
    gridView.setAdapter(adapter);

    editor = sharedPreferences.edit();
    editor.putInt("count", count - 1);
    editor.apply();

    Toast.makeText(getApplicationContext(), "One Image Removed", Toast.LENGTH_SHORT).show();
   }
  });
 }
}
ImageAdapter.java
Open ImageAdapter.java and replace it with the following code
package com.example.grid.adapter;
 
import android.content.Context;
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.example.grid.R;
 
import java.util.ArrayList;
 
public class ImageAdapter extends BaseAdapter {
  
 private Context context;
 private ArrayList list = new ArrayList<>();

 public ImageAdapter(Context context, ArrayList list) {
  this.context = context;
  this.list = list;
 }

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

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

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

 public View getView(int position, View convertView, ViewGroup parent) {

  LayoutInflater inflater = (LayoutInflater) Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  convertView = inflater.inflate(R.layout.activity_main_single, null);
  TextView textView = (TextView) convertView.findViewById(R.id.grid_item_label);
  ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_item_image);

  int option = ((position+1)%3);

  switch (option) {
   case 0:
    textView.setText("Windows");
    imageView.setImageResource(R.drawable.windows_logo);
    break;
   case 1:
    textView.setText("Android");
    imageView.setImageResource(R.drawable.android_logo);
    break;
   case 2:
    textView.setText("IOS");
    imageView.setImageResource(R.drawable.ios_logo);
    break;
   default:
    textView.setText("Android");
    imageView.setImageResource(R.drawable.android_logo);
    break;
  }

  return convertView;

 }

}

Download Full Source Code


Download Code

In this post, I will show you how to perform CRUD ( C reate, R ead, U pdate and D elete) operation with Images from Gallery in SQLite...

How to perform CRUD Operations in Android SQLite with Blob How to perform CRUD Operations in Android SQLite with Blob

A blog about android developement

android

How to perform CRUD Operations in Android SQLite with Blob

In this post, I will show you how to perform CRUD (Create,Read, Update and Delete) operation with Images from Gallery in SQLite which is embedded in Android devices.
Codes:
AndroidManifest.xml
Don't forget to add the following permission in your manifest file.

DBHelper.java
Open DBHelper.java and replace it with the following code.
package com.example.blob.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
public class DBHelper extends SQLiteOpenHelper {

 static DBHelper dbhelper;
 static final String DATABASE_NAME = "IMAGE_EX";
 static final int DATABASE_VERSION = 1;
 public static final String IMAGE_TABLE="image_table";
 public static final String IMAGE_="image";
 public static final String IMAGE_NAME="image_name";
 public static final String IMAGE_ID="id";

 public static final String IMAGE_EX = "CREATE TABLE "+IMAGE_TABLE+" ("+IMAGE_ID + " INTEGER PRIMARY KEY,"+IMAGE_NAME+ " VARCHAR(55) DEFAULT NULL," + IMAGE_+" BLOB DEFAULT NULL);";

 public DBHelper(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {

  db.execSQL(IMAGE_EX);

 }
  
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  Log.w(DBHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion+ ". Old data will be destroyed");
  db.execSQL("DROP TABLE IF EXISTS"+ IMAGE_TABLE);
  }
  
 }


InsertHelper.java

Open InsertHelper.java and replace it with the following code.
package com.example.blob.helper;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
 
public class InsertHelper {

 private Context context;
 private SQLiteDatabase mDb;
 private DBHelper dbHelper;

 public InsertHelper(Context context) {
  this.context = context;
 }

 public InsertHelper open() throws SQLException {
  dbHelper = new DBHelper(context);
  mDb = dbHelper.getWritableDatabase();
  return this;
 }

 public void close() {
  dbHelper.close();
 }

 public long insert_profile(byte[] byteImage, String data){

  ContentValues values = new ContentValues();
  values.put(DBHelper.IMAGE_, byteImage);
  values.put(DBHelper.IMAGE_NAME, data);

  Log.w("Position: ", "Inserted Values-->" + values);

  return mDb.insert(DBHelper.IMAGE_TABLE, null, values);

 }
}

UpdateHelper.java

Open UpdateHelper.java and replace it with the following code.
package com.example.blob.helper;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
 
public class UpdateHelper {

 private Context context;
 private SQLiteDatabase mDb;
 private DBHelper dbHelper;

 public UpdateHelper(Context context) {
  this.context = context;
 }

 public UpdateHelper open() throws SQLException {
  dbHelper = new DBHelper(context);
  mDb = dbHelper.getWritableDatabase();
  return this;
 }

 public void close() {
  dbHelper.close();
 }

 public long update_profile(String id, byte[] byteImage, String data) {

  ContentValues Values = new ContentValues();
  Values.put(DBHelper.IMAGE_NAME,data);
  Values.put(DBHelper.IMAGE_,byteImage);
         return mDb.update(DBHelper.IMAGE_TABLE, Values, DBHelper.IMAGE_ID + "=" + id, null);

 }
}


DeleteHelper.java

Open DeleteHelper.java and replace it with the following code.
package com.example.blob.helper;
 
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
 
public class DeleteHelper {

 private Context context;
 private SQLiteDatabase mDb;
 private DBHelper dbHelper;

 public DeleteHelper(Context context) {
  this.context = context;
 }

 public DeleteHelper open() throws SQLException {
  dbHelper = new DBHelper(context);
  mDb = dbHelper.getWritableDatabase();
  return this;
 }

 public void close() {
  dbHelper.close();
 }

 public long delete_profile(String id) {
 
  return mDb.delete(DBHelper.IMAGE_TABLE, DBHelper.IMAGE_ID + "=" + id, null);

 }
}

activity_main.xml
Create activity_main.xml and replace it with the following code.
<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:weightSum="5"
 tools:context=".MainActivity">

 <Button
  android:id="@+id/add"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.3"
  android:background="@android:color/holo_red_dark"
  android:text="@string/add_hint"
  android:textColor="@android:color/white"/>

 <ListView
  android:id="@+id/list"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_weight="4.7"/>
 
</LinearLayout>

list_item_profile.xml
Create list_item_profile.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"
 android:id="@+id/ll"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:orientation="horizontal"
 android:padding="13dp">

 <ImageView
  android:id="@+id/profile_image"
  android:layout_width="75dp"
  android:layout_height="75dp"
  android:contentDescription="@string/app_name"
  android:scaleType="fitXY"
  android:src="@mipmap/ic_launcher"/>

 <TextView
  android:id="@+id/profile_name"
  android:layout_width="250dp"
  android:layout_height="match_parent"
  android:gravity="center"
  android:padding="5dp"
  android:text="@string/app_name"/>

</LinearLayout>
MainActivity.java
Open MainActivity.java and replace it with the following code.
package com.example.blob;
 
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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.ListView;
import android.widget.Toast;
 
import com.example.blob.adapter.ProfileListAdapter;
import com.example.blob.helper.DBHelper;
import com.example.blob.helper.DeleteHelper;
 
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {

 Button btn_add;
 ListView listView;
 ArrayList image_name = new ArrayList<>();
 ArrayList image = new ArrayList<>();
 ArrayList image_id = new ArrayList<>();
 ProfileListAdapter adapter;
 Intent intent;
 DBHelper dbHelper;
 DeleteHelper del;
 SQLiteDatabase database;

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

  btn_add = (Button) findViewById(R.id.add);
  listView = (ListView) findViewById(R.id.list);

  // Clear the ArrayLists
  image_name.clear();
  image.clear();
  image_id.clear();

  display_data();

  // the helper class for DB creation operation
  dbHelper = new DBHelper(this);

  // the helper class for doing delete operation
  del = new DeleteHelper(this);

  btn_add.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    intent = new Intent(MainActivity.this, AddUpdateActivity.class);
    intent.putExtra("update", false);
    startActivity(intent);
    finish();
   }
  });

  // click event for updating the selected profile
  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView parent, View view, int position, long id) {
    intent = new Intent(MainActivity.this, AddUpdateActivity.class);
    intent.putExtra("id", image_id.get(position));
    intent.putExtra("image", image.get(position));
    intent.putExtra("name", image_name.get(position));
    intent.putExtra("update", true);
    startActivity(intent);
   }
  });

  // long click event for deleting the selected profile
  listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
   @Override
   public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) {

    del.open();
    long ret = del.delete_profile(image_id.get(position));
    del.close();

    if(ret>0){
     Toast.makeText(getApplicationContext(), "Try Again!", Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(getApplicationContext(), "Successfully Deleted!", Toast.LENGTH_SHORT).show();
 
     // default function to call the same class
     recreate();
    }
 
    return true;
   }
  });
 
 }

 public void display_data() {

  dbHelper = new DBHelper(this);
  database = dbHelper.getWritableDatabase();

  // Query to select all profiles
  String select_data = "SELECT * FROM " + DBHelper.IMAGE_TABLE;
 
  Cursor sCursor = database.rawQuery(select_data, null);
 
  if (sCursor.moveToFirst()) {
   do { 
image_id.add(sCursor.getString(sCursor.getColumnIndex(DBHelper.IMAGE_ID)));
     image_name.add(sCursor.getString(sCursor.getColumnIndex(DBHelper.IMAGE_NAME)));
     image.add(sCursor.getBlob(sCursor.getColumnIndex(DBHelper.IMAGE_)));

    Log.v("Response:", " " + image_name + " " + image);

   } while (sCursor.moveToNext());
  }
  sCursor.close();
  adapter = new ProfileListAdapter(MainActivity.this, image_id, image_name, image);
  listView.setAdapter(adapter);
 }
}
ProfileListAdapter.java
Open ProfileListAdapter.java and replace it with the following code.
package com.example.blob.adapter;
 
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
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.example.blob.R;
 
import java.util.ArrayList;
 
public class ProfileListAdapter extends BaseAdapter {

 Context mContext;
 ArrayList image_id;
 ArrayList image_name;
 ArrayList image;
 LayoutInflater layoutInflater;
 ImageView profile;
 TextView name;
 byte[] bytes;

 public ProfileListAdapter(Context mContext, ArrayList image_id,        ArrayList image_name, ArrayList image) {
  this.mContext = mContext;
  this.image_id = image_id;
  this.image_name = image_name;
  this.image = image;
 }

 public int getCount() {
  return image_id.size();
 }

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

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

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

  layoutInflater = ((Activity) mContext).getLayoutInflater();
  convertView = layoutInflater.inflate(R.layout.list_item_profile, null);

  profile = (ImageView) convertView.findViewById(R.id.profile_image);
  name = (TextView) convertView.findViewById(R.id.profile_name);

  name.setText(image_name.get(position));
  bytes = image.get(position);

  // Decoding Bitmap from stored ByteArray
  profile.setImageBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));

  return convertView;
 }
}
activity_dashboard.xml
Create activity_dashboard.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"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center"
 android:orientation="vertical">

 <ImageView
  android:id="@+id/imageView"
  android:layout_width="200dp"
  android:layout_height="200dp"
  android:layout_gravity="center_horizontal"
  android:contentDescription="@string/iv"
  android:src="@mipmap/ic_launcher" />

 <EditText
  android:id="@+id/editText"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal"
  android:layout_margin="10dp"
  android:hint="@string/name" />

 <Button
  android:id="@+id/button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal"
  android:text="Insert" />
</LinearLayout>
AddUpdateActivity.java
Open AddUpdateActivity.java and replace it with the following code.
package com.example.blob;
 
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.blob.helper.DBHelper;
import com.example.blob.helper.InsertHelper;
import com.example.blob.helper.UpdateHelper;
 
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
 
public class AddUpdateActivity extends AppCompatActivity {

 ImageView img1;
 EditText edt1;
 Button btn1;
 int SELECT_PICTURE = 1;
 SQLiteDatabase db;
 DBHelper mHelper;
 String selectedImagePath;
 byte[] byteImage = null;
 Intent intent;
 boolean isUpdate;
 String id, data;

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

  // the helper class for DB creation operation
  mHelper = new DBHelper(this);
  img1 = (ImageView) findViewById(R.id.imageView);
  edt1 = (EditText) findViewById(R.id.editText);
  btn1 = (Button) findViewById(R.id.button);

  isUpdate = getIntent().getBooleanExtra("update", false);
  if (isUpdate) {
   id = getIntent().getStringExtra("id");
   byteImage = getIntent().getByteArrayExtra("image");
   data = getIntent().getStringExtra("name");

   // Decoding Bitmap from stored ByteArray from preview the stored image
   img1.setImageBitmap(BitmapFactory.decodeByteArray(byteImage, 0, byteImage.length));
   edt1.setText(data);
   btn1.setText("Update");
  }

  // Onclick event to select the image from gallery
  img1.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_PICTURE);
   }
  });

  // Onclick event to do insert or update the data based on isUpdate
  btn1.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    data = edt1.getText().toString();
    if (data.equals("")) {
     Toast.makeText(getApplicationContext(), "Enter Name!", Toast.LENGTH_SHORT).show();
    } else {
     if (isUpdate) {
      updateData(data, id);
     } else {
      saveData(data);
     }
    }
   }
  });

 }

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == RESULT_OK) {
   if (requestCode == SELECT_PICTURE) {
    Uri selectedImageUri = data.getData();
    String[] projection = {MediaStore.MediaColumns.DATA};
    Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();
    selectedImagePath = cursor.getString(column_index);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
      && options.outHeight / scale / 2 >=REQUIRED_SIZE)
     scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath, options);
    // Preview for Selected Image
    img1.setImageBitmap(bitmap);
   }
  }
 }

 // Function for insertion
 private void saveData(String data) {
  db = mHelper.getWritableDatabase();
  // the helper class for doing insert operation
  InsertHelper ins = new InsertHelper(this);
  ins.open();

  try {
   // Encoding the Selected Image into ByteArray
   if (selectedImagePath != null) {
    FileInputStream in_stream = new FileInputStream(selectedImagePath);
    BufferedInputStream bif = new BufferedInputStream(in_stream);
    byteImage = new byte[bif.available()];
    bif.read(byteImage);
   } else {
    Toast.makeText(getApplicationContext(), "Please Select Image!", Toast.LENGTH_SHORT).show();
   }
 
   if (byteImage != null) {
    // Function call to insert data
    long ret = ins.insert_profile(byteImage, data);
    if (ret > 0) {
     Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(this.getBaseContext(), "Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
     intent = new Intent(AddUpdateActivity.this, MainActivity.class);
     startActivity(intent);
     finish();
    }
   } else {
    Toast.makeText(getApplicationContext(), "Select Image", Toast.LENGTH_SHORT).show();
   }
  } catch (IOException e) {
    Toast.makeText(getApplicationContext(), "Error Exception!", Toast.LENGTH_SHORT).show();
  }
  ins.close();
  db.close();
 }

 // Function for Updating the already stored value
 private void updateData(String data, String id) {
  db = mHelper.getWritableDatabase();
 
  UpdateHelper upd = new UpdateHelper(this);
  upd.open();
 
  try {
   // Encoding the Selected Image into ByteArray
   if (selectedImagePath != null) {
    FileInputStream in_stream = new FileInputStream(selectedImagePath);
    BufferedInputStream bif = new BufferedInputStream(in_stream);
    byteImage = new byte[bif.available()];
    bif.read(byteImage);
   }

   // Function call to update data
   long ret = upd.update_profile(id, byteImage, data);

   if (ret > 0) {
    Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_SHORT).show();
   } else {
    Toast.makeText(this.getBaseContext(), "Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
    intent = new Intent(AddUpdateActivity.this, MainActivity.class);
    startActivity(intent);
    finish();
   }
  } catch (IOException e) {
   Toast.makeText(getApplicationContext(), "Error Exception!", Toast.LENGTH_SHORT).show();
  }
  upd.close();
  db.close();
 }
}

Download Full Source Code


Download Code