Thursday, October 10, 2013

Android Almanac - Code Snippet Repo

Hi there! This section i will totatlly dedicate to android dev´s out there! It is as little Android Almanac containing common code snippets for the different purposes and tasks. I will be growing permanently. So if you miss something, just leave a constructive comment and i will try my best to accomplish that ok. Hope you like it.

How to detect device's 3G, wifi or internet connection

private boolean isConnectedToInternet(Context ctx) {

        NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null || !info.isConnected()) {
            return false;
        }
        if (info.isRoaming()) {
            // here is the roaming option you can change it if you want to
            // disable internet while roaming, just return false
            return false;
        }
        return true;
    }

Easy way to give feedback to users while pressing ImageView

final ImageView eraseBtn = (ImageView)findViewById(R.id.eraseBtn);
         eraseBtn.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    eraseBtn.setColorFilter(getResources().getColor(R.color.translucent_black));
                    eraseBtn.invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    eraseBtn.setColorFilter(null);
                    eraseBtn.invalidate();
                    break;
                default:
                    break;
                }
                return false;
            }
        });
Define the translucent black color like this in your strings.xml file:
< ? xml version="1.0" encoding="utf-8" ? >
< resources >
     ....
    < color name="translucent_black" >#51000000< / color>
     ....
< / resources>

How to compute degrees from MouseEvent (x,y coordinates)

In some cases, we need to compute the degrees from a give coordinate. Like from an event. Here is a simple way how to do it:

    private float getDegrees(MotionEvent event) {
        double radians = Math.atan2(event.getY(1) - event.getY(0), event.getX(1) - event.getX(0));
        return (float) Math.toDegrees(radians);
    }

Listening to orientation changes onSensorChanged()

In some cases, we need to implement SensorEventListener and implement onSensorChanded. While listening to it, i lost many yours looking for a simple approach which allows me to simple decide if my fone is lying on the side or if it stands. A very nice and simple way is to listen to its angles like that:

... code omitted ...

public void onSensorChanged(SensorEvent event) {
        float pitch = event.values[1];
        float roll = event.values[2];
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            if (pitch < -45 && pitch > -135) {
                onLandscapePhoneStands();
            } else if (pitch > 45 && pitch < 135) {
                onLandscapePhoneOnHead();
            } else if (roll > 45) {
                onLandscapePhoneLyingOnTheLeftSide();
            } else if (roll < -45) {
                onLandscapePhoneLyingOnTheRightSide();
            }
        } else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            if (pitch < -45 && pitch > -135) {
                onPhoneStands();
            } else if (pitch > 45 && pitch < 135) {
                onPhoneOnHead();
            } else if (roll > 45) {
                onPhoneLyingOnTheLeftSide();
            } else if (roll < -45) {
                onPhoneLyingOnTheRightSide();
            }
        }
    }

... code omitted ...

How to remove padding from AlertDialog on Android

I had a task to solve, which was very tricky. I needed to display an alert dialog, which presents an image (using the whole space of the dialog) without any buttons. Just a fullscreen picture on it. The problem was, that on the top side of the dialog, was always a border line remaining. No matter what i did or set in the layout.xml. I lost many hours searching for a proper solution. At the end the solution was as simple as i thought, but very tricky. All you need to do, is to call the following piece of code after calling the show() method on your dialogBuilder or on your dialog itself.

... code ommited...

dialogBuilder.show(); 

ViewGroup parent = (ViewGroup)view.getParent();

parent.setPadding(0, 0, 0, 0);

... code ommited ...

Getting the current display size

That´s a very common task for diffent purposes. Here a snippet for it:

DisplayMetrics metrics = getResources().getDisplayMetrics();
  int displayWidth = metrics.widthPixels;
  int displayHeight = metrics.heightPixels;

Rounded Corners by Layouts

Sometimes you'll need to be a little more sofisticated with your layout. One task i had, was to round the corners from my fragment layout, setting stroke type, color and radius. This may also be helpfull to you. In the folder drawable define a shape.xml called: rounded_layout_corners.xml with the content bellow and set it to the android:background attribute of your layout in the xml file.:


    
    
    
    


Rounded Corners by Layouts without bottom line

More examples with rounded corners but this way hidding the bottom line. For this kind of layout you'll need to create the drawable folder for portrait and drawable-land for landscape mode.

Here's the portrait layout i called rounded_layout_corner.xml
 
    
    
     
     
    
    
     
 
And here's the landscape layout i called also rounded_layout_corner.xml but put it in the drawable-land folder.
 
     
    
     
     
    
    
     
 

Supporting Multiple Screen Sizes

That´s a very common task. Here the most important infos you need to know.

drawable-ldpi (120 dpi, Low density screen) - 36px x 36px
drawable-mdpi (160 dpi, Medium density screen) - 48px x 48px
drawable-hdpi (240 dpi, High density screen) - 72px x 72px
drawable-xhdpi (320 dpi, Extra-high density screen) - 96px x 96px
drawable-xxhdpi or drawable-480dpi (480 dpi, XHDPI density screen) - 144px x 144px

Reacting to different orientations

That´s another very common task. Here one option you may like it:

private boolean onPhoneMovement() {
  boolean isPhoneLyingOnTheSide = false;
  DisplayMetrics metrics = getResources().getDisplayMetrics();
  int displayWidth = metrics.widthPixels;
  int displayHeight = metrics.heightPixels;
  switch (getWindowManager().getDefaultDisplay().getRotation()) {
  case Surface.ROTATION_0:
  case Surface.ROTATION_180: {
   onPhoneStands(displayHeight);
   isPhoneLyingOnTheSide = false;
   break;
  }
  case Surface.ROTATION_90:
  case Surface.ROTATION_270: {
   onPhoneLiesOnTheSide(displayWidth);
   isPhoneLyingOnTheSide = true;
   break;
  }
  }
  return isPhoneLyingOnTheSide;
 }

Setting Width and Height to Layouts

That can be very usefull in some cases:

private void onPhoneLiesOnTheSide(int displayWidth) {
  this.toReplace = (LinearLayout) findViewById(R.id.toReplace);
  this.toReplace.getLayoutParams().height = this.buttonBackground.getHeight();
  this.toReplace.getLayoutParams().width = displayWidth - this.buttonBackground.getWidth();
 }

 private void onPhoneStands(int displayHeight) {
  this.toReplace = (LinearLayout) findViewById(R.id.toReplace);
  this.toReplace.getLayoutParams().height = displayHeight - this.buttonBackground.getHeight();
  this.toReplace.getLayoutParams().width = this.buttonBackground.getWidth();
 }

Fragment Replacement and Animation (Slide In and Slide Out)

Attention: If you've never worked with fragments, so please read my previous post about it first. dynamically fragment replacement android This snippet could be a differencial in your app. create a folder anim and anim-land in the folder res. Then put those xml-files in it. In folder anim create a xml file called slide_in.xml


    


The in the same folder anim create a xml file called slide_out.xml


    


The in the folder anim-land create a xml file called slide_in.xml


    


And last but no least in the folder anim-land create a xml file called slide_out.xml


    



Then try this here:
 private void hideFragmen(final Fragment framgmentToShow, boolean isPhoneLyingOnTheSide) {
  FragmentTransaction transaction = getFragmentManager().beginTransaction();
  transaction.setCustomAnimations(R.anim.slide_out, R.anim.slide_in);
  transaction.replace(R.id.toReplace, framgmentToShow);
  transaction.hide(framgmentToShow);
  transaction.commit();
 }

 private void showFragment(final Fragment framgmentToShow, boolean isPhoneLyingOnTheSide) {
  FragmentTransaction transaction = getFragmentManager().beginTransaction();
  transaction.setCustomAnimations(R.anim.slide_out, R.anim.slide_in);
  transaction.replace(R.id.toReplace, framgmentToShow);
  transaction.show(framgmentToShow);
  transaction.commit();
 }

Load/Decode Bitmap from Resource with BitmapFactory

You'll need this line several times while developing with Android.

  Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);

Rotate icons depending on phone Orientation

That´s a nice one. Small, fine and native. Because buttons are also views you can use this i a very generic way.

private void setIconRotation(int degrees) {
  for (View view : viewsToRotate) {
   view.setRotation(degrees);
  }
}

Fix/fixing a layout on the right side of your phone

That's also a good one. No matter what kind of the screen orientation you have. Just fix(post it) your layout in the right corner of your phone.

public void handleRotationChange(int rotation) {
  switch (rotation) {
  case Surface.ROTATION_0:
  case Surface.ROTATION_180: {
   // ***********************************************************
   // rotate toolbar (fix it on the right)
   // ***********************************************************
   this.layoutToolbar.setOrientation(LinearLayout.HORIZONTAL);
   this.layoutToolbar.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
   LayoutParams params = (LayoutParams) this.layoutToolbar.getLayoutParams();
   params.gravity = Gravity.BOTTOM;
   params.width = LayoutParams.MATCH_PARENT;
   params.height = LayoutParams.WRAP_CONTENT;
   // ***********************************************************
   // rotate icons
   // ***********************************************************
   setIconRotation(0);
  }
   break;

  case Surface.ROTATION_90:
  case Surface.ROTATION_270: {
   // ***********************************************************
   // rotate toolbar (fix it on the bottom)
   // ***********************************************************
   this.layoutToolbar.setOrientation(LinearLayout.VERTICAL);
   this.layoutToolbar.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
   LayoutParams params = (LayoutParams) this.layoutToolbar.getLayoutParams();
   params.gravity = Gravity.RIGHT;
   params.width = LayoutParams.WRAP_CONTENT;
   params.height = LayoutParams.MATCH_PARENT;
   // ***********************************************************
   // rotate icons
   // ***********************************************************
   setIconRotation(0);
  }
   break;
  }
 }

Showing/show simple info message on the screen

private void showMessage(String msg) {
  Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
 }

GPS distance calculation from one point to another


public double calculeDistanciaEmMetrosComoDouble(double lat1, double lng1, double lat2, double lng2) {
  return calculeDistancia(lat1, lng1, lat2, lng2);
 }

 /** calcula a distância de um ponto ao outro (longitude, latitude) retornando a distância com o suffix "m" no final*/
 public String calculeDistanciaEmMetros(double lat1, double lng1, double lat2, double lng2) {
  double distanciaCalculada = calculeDistancia(lat1, lng1, lat2, lng2);
  return definaQuantosNumerosAposVirgula(2, distanciaCalculada) + " m";
 }
 
 /** calcula a distância de um ponto ao outro (longitude, latitude) retornando a distância com o suffix "km" no final*/
 public String calculeDistanciaEmKilometros(double lat1, double lng1, double lat2, double lng2) {
  double distanciaCalculada = calculeDistancia(lat1, lng1, lat2, lng2);
  double kilometros = distanciaCalculada / 1000;
  return definaQuantosNumerosAposVirgula(2, kilometros) + " km";
 }
 
 /** calcula a distância de um ponto ao outro (longitude, latitude) retornando a distância em miles (1.609km) com o suffix "miles" no final*/
 public String calculeDistanciaEmMiles(double lat1, double lng1, double lat2, double lng2) {
  double distanciaCalculada = calculeDistancia(lat1, lng1, lat2, lng2);
  double miles = distanciaCalculada / 1609.344;
  return definaQuantosNumerosAposVirgula(2, miles) + " miles";
 }
 
 /** calcula a distância de um ponto ao outro (longitude, latitude) retornando a distância em yards (0.9144m) com o suffix "yards" no final*/
 public String calculeDistanciaEmYards(double lat1, double lng1, double lat2, double lng2) {
  double distanciaCalculada = calculeDistancia(lat1, lng1, lat2, lng2);
  double yards = distanciaCalculada / 0.9144;
  return definaQuantosNumerosAposVirgula(2, yards) + " yards";
 }
 
 /** calcula a distância de um ponto ao outro (longitude, latitude) retornando a distância em feets (0.3048m) com o suffix "feets" no final*/
 public String calculeDistanciaEmFeets(double lat1, double lng1, double lat2, double lng2) {
  double distanciaCalculada = calculeDistancia(lat1, lng1, lat2, lng2);
  double feets = distanciaCalculada / 0.3048;
  return definaQuantosNumerosAposVirgula(2, feets) + " feets";
 }
 
 /** calcula a distância de um ponto ao outro (longitude, latitude) retornando a distância em metros"*/
 private double calculeDistancia(double lat1, double lng1, double lat2, double lng2) {
  double earthRadius = 3958.75;
  double dLat = Math.toRadians(lat2 - lat1);
  double dLng = Math.toRadians(lng2 - lng1);
  double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
    + Math.cos(Math.toRadians(lat1))
    * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
    * Math.sin(dLng / 2);
  double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  double dist = earthRadius * c;
  int meterConversion = 1609;
  double result = (dist * meterConversion);
  return result;

 }
 
 private String definaQuantosNumerosAposVirgula(int qnt, double amount){
  NumberFormat df = DecimalFormat.getInstance();
  df.setMinimumFractionDigits(2);
  df.setMaximumFractionDigits(2);
  return df.format(amount);
 }

Hide Application Titlebar


public void hideApplicationTitleBar() {
  requestWindowFeature(Window.FEATURE_NO_TITLE);
 }

Set Application Orientation


setRequestedOrientation(defineActivityOrientation());
public int defineActivityOrientation() {
  return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
 }

GPS Locatition Manager, LastKnownLocation, Wifi, Network


protected LocationManager locationManager;
protected String provider;
protected Geocoder coder;
private void initGeoLocation() {
  this.addressFinder = new AddressFinder(this, this.autoCompleteSearch);
  this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  showMessageOnGpsDeactivated();
  // Define the criteria how to select the locatioin provider -> use default
  this.provider = locationManager.getBestProvider(new Criteria(), false);
  this.coder = new Geocoder(this);
 }
public boolean showMessageOnGpsDeactivated() {
  boolean isGpsDeactivated = false;
  if (!isGpsProviderEnabled() || !isNetworkProviderEnabled()) {
   showModalGpsActivateDialog();
   isGpsDeactivated = true;
  }
  return isGpsDeactivated;
 }
private boolean isGpsProviderEnabled() {
  return this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 }

 private boolean isNetworkProviderEnabled() {
  return this.locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
 }
public boolean isOnline() {
  boolean isConnected = false;
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo netInfo = cm.getActiveNetworkInfo();
  if (netInfo != null && netInfo.isConnectedOrConnecting()) {
   isConnected = true;
  }
  return isConnected;
 }
public boolean isWiFiOnline() {
  boolean isConnected = false;
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  if (mWifi != null && mWifi.isConnectedOrConnecting()) {
   isConnected = true;
  }
  return isConnected;
 }
public void showModalGpsActivateDialog() {

  LayoutInflater inflater = getLayoutInflater();
  View view = inflater.inflate(R.layout.layout_toast, (ViewGroup) findViewById(R.id.layout_toast_gps));

  new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(getResources().getText(R.string.toast_gps_dialog_title))
    .setPositiveButton(getResources().getText(R.string.toast_gps_dialog_button_text), new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
      navigateTo(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
     }

    }).setView(view).setCancelable(false).show();
 }
public Location getLastKnownLocation() {
  Location location = null;
  if (isOnline()) {
   if (!showMessageOnGpsDeactivated()) {
    if (isLocationAvailable()) {
     location = this.locationManager.getLastKnownLocation(this.provider);
    } else {
     showMessage(this, getResources().getString(R.string.toast_gps_dialog_no_gps_available));
    }
   }
  } else {
   showModalNoNetworkDialog();
  }
  return location;
 }

 public boolean isLocationAvailable() {
  this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  this.provider = locationManager.getBestProvider(new Criteria(), false);
  this.coder = new Geocoder(this);
  return this.locationManager.getLastKnownLocation(this.provider) != null;
 }

Navigation, Intent, Google Play Store, Webpage


/** Use this method to get passed values over Intent.SetExtras(...) */
 public String getPassedUserInputSelection(String key) {
  return (String) getIntent().getExtras().get(key);
 }

 /** Use this method to navigate from one activity to another passing values to the target activity */
 public void navigateToPassingValues(Context fromActivity, Class toActivityClass, String bundleKey, Bundle bundle) {
  Intent activityToStart = createActivityToStart(fromActivity, toActivityClass);
  activityToStart.putExtra(bundleKey, bundle);
  startActivity(activityToStart);
 }

 /** Use this method to navigate from one activity to another passing values to the target activity */
 public void navigateToPassingValues(Context fromActivity, Class toActivityClass, String key, String value) {
  Intent activityToStart = createActivityToStart(fromActivity, toActivityClass);
  activityToStart.putExtra(key, value);
  startActivity(activityToStart);
 }

 /** Use this method to navigate from one activity to another */
 public void navigateTo(Context fromActivity, Class toActivityClass) {
  startActivity(createActivityToStart(fromActivity, toActivityClass));
 }

 /** Use this method to navigate directly to a given intent */
 public void navigateTo(Intent intent) {
  startActivity(intent);
 }

 private Intent createActivityToStart(Context fromActivity, Class toActivityClass) {
  return new Intent(fromActivity, toActivityClass);
 }

 /** Use this method to open the google play store from this app */
 public void navigateToGooglePlayStore() {
  final String appName = "com.treslines.onibuspe";
  try {
   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
  } catch (android.content.ActivityNotFoundException anfe) {
   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
  }
 }

 public void navigateToTreslines() {
  final String webpage = "http://www.treslines.com/index.html";
  try {
   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(webpage)));
  } catch (android.content.ActivityNotFoundException anfe) {
   // If anything goes wrong, don't disturb the user experience. just don't open the webpage
  }
 }
 
 public void navigateToWebpage(String address) {
  final String webpage = address;
  try {
   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(webpage)));
  } catch (android.content.ActivityNotFoundException anfe) {
   // If anything goes wrong, don't disturb the user experience. just don't open the webpage
  }
 }

 /** Use this method to display messages to the user */
 public void showMessage(Context context, String msg) {
  Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
  toast.setGravity(Gravity.CENTER, 0, 0);
  toast.show();
 }

AutoComplete, MultiAutoCompleteTextView


/** Use this method to create a custom autocomplete with NoTokenizer and no suggestions flags */
 public void createAutoComplete(MultiAutoCompleteTextView autoComplete, String[] contentToShow) {
  autoComplete.setAdapter(new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, contentToShow));
  autoComplete.setTokenizer(getTokenizerForMultiAutoCompleteTextView());
  autoComplete.setRawInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
 }

 /** Use this method to create a custom Tokenizer with no comma(,) termination */
 public NoTokenizer getTokenizerForMultiAutoCompleteTextView() {
  return new NoTokenizer();
 }

 private class NoTokenizer extends MultiAutoCompleteTextView.CommaTokenizer {

  @Override
  public int findTokenEnd(CharSequence text, int cursor) {
   return super.findTokenEnd(text, cursor);
  }

  @Override
  public int findTokenStart(CharSequence text, int cursor) {
   return super.findTokenStart(text, cursor);
  }

  @Override
  public CharSequence terminateToken(CharSequence text) {
   CharSequence terminateToken = super.terminateToken(text);
   terminateToken = terminateToken.toString().replace(" ,", "").replace(", ", "");
   return terminateToken;
  }

 }

Creating array from string.xml


public String[] createLinhasFromStringXml() {
  return getResources().getStringArray(R.array.linha_array);
 }

Inflater to put into your abstracted class


public View inflateContentView(int layoutId) {
  LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  return inflater.inflate(layoutId, null);
 }

DB, database date parser


import android.annotation.SuppressLint;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressLint("SimpleDateFormat")
public class DbDateParser {
 private static final String format = "yyyy-MM-dd";

 public static Date stringToDate(String data) {
  Date dDate = null;
  SimpleDateFormat formatter = new SimpleDateFormat(format);
  try {
   dDate = formatter.parse(data);
  } catch (ParseException e) {
  }
  return dDate;
 }

 public static String dateToString(Date data) {
  return dateToString(data, format);
 }

 public static String dateToString(Date data, String format) {
  SimpleDateFormat formatter = new SimpleDateFormat(format);
  return formatter.format(data);
 }

 public static int getHour(Date data) {
  try {
   SimpleDateFormat formatter = new SimpleDateFormat("HH");
   return Integer.parseInt(formatter.format(data));
  } catch (Exception ex) {
   return -1;
  }
 }

 public static int getMinute(Date data) {
  try {
   SimpleDateFormat formatter = new SimpleDateFormat("mm");
   return Integer.parseInt(formatter.format(data));
  } catch (Exception ex) {
   return -1;
  }
 }

 public static int getDay(Date data) {
  try {
   SimpleDateFormat formatter = new SimpleDateFormat("dd");
   return Integer.parseInt(formatter.format(data));
  } catch (Exception ex) {
   return -1;
  }
 }

 public static int getMonth(Date data) {
  try {
   SimpleDateFormat formatter = new SimpleDateFormat("MM");
   return Integer.parseInt(formatter.format(data));
  } catch (Exception ex) {
   return -1;
  }
 }

 public static int getYear(Date data) {
  try {
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
   return Integer.parseInt(formatter.format(data));
  } catch (Exception ex) {
   return -1;
  }
 }

 public static Date getFullHour_String2Date(String data) {
  try {
   SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
   return formatter.parse(data);
  } catch (Exception ex) {
   return new Date();
  }
 }
}

Ormlite, SQLite, DatabaseHelper


import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.treslines.entity.EmpresaEntity;
import com.treslines.entity.ItinerarioEntity;
import com.treslines.entity.LinhaEntity;
import com.treslines.entity.ParadaEntity;
import com.treslines.entity.ReferenciaEntity;
import com.treslines.entity.RotaEntity;
import com.treslines.entity.RoteiroEntity;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

 private static final String DATABASE_NAME = "databasename.db";
 private static final int DATABASE_VERSION = 1;

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

 @Override
 public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
  try {
   Log.i("DB", "onCreate: create tables if not exists");
   TableUtils.createTableIfNotExists(connectionSource, LinhaEntity.class);
   TableUtils.createTableIfNotExists(connectionSource, ReferenciaEntity.class);
   TableUtils.createTableIfNotExists(connectionSource, RoteiroEntity.class);
   TableUtils.createTableIfNotExists(connectionSource, RotaEntity.class);
   TableUtils.createTableIfNotExists(connectionSource, EmpresaEntity.class);
   TableUtils.createTableIfNotExists(connectionSource, ItinerarioEntity.class);
   TableUtils.createTableIfNotExists(connectionSource, ParadaEntity.class);
  } catch (SQLException e) {
   Log.e(DatabaseHelper.class.getSimpleName(), "Can't create database", e);
   throw new RuntimeException(e);
  }
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
  try {
   // delete all tables
   Log.i("DB", "onUpgrade: drop old tables and create new tables");
   TableUtils.dropTable(connectionSource, ParadaEntity.class, true);
   TableUtils.dropTable(connectionSource, ItinerarioEntity.class, true);
   TableUtils.dropTable(connectionSource, EmpresaEntity.class, true);
   TableUtils.dropTable(connectionSource, RotaEntity.class, true);
   TableUtils.dropTable(connectionSource, RoteiroEntity.class, true);
   TableUtils.dropTable(connectionSource, ReferenciaEntity.class, true);
   TableUtils.dropTable(connectionSource, LinhaEntity.class, true);
   // create new tables
   onCreate(db, connectionSource);
  } catch (SQLException e) {
   Log.e(DatabaseHelper.class.getSimpleName(), "Can't drop databases", e);
   throw new RuntimeException(e);
  }
 }

 @Override
 public void close() {
  super.close();
 }
}

import com.j256.ormlite.field.DatabaseField;

// ORMLite download addresses
// ormlite-android-4.45: //www.java2s.com/Code/Jar/o/Downloadormliteandroid445jar.htm
// ormlite-core-4.45: http://sourceforge.net/projects/ormlite/files/

public abstract class AbstractEntity {

 @DatabaseField(columnName="_id", generatedId = true)
 private Integer id;
 @DatabaseField(columnName="timestamp")
 private String timestamp;
 
 // ormlite require default constructor
 public AbstractEntity() {
  super();
 }
 
 public AbstractEntity(Integer id, String timestamp) {
  setId(id);
  setTimestamp(timestamp);
 }

 public Integer getId() {return id;}
 public void setId(Integer id) {this.id = id;}
 public String getTimestamp() {return timestamp;}
 public void setTimestamp(String timestamp) {this.timestamp = timestamp;}

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((id == null) ? 0 : id.hashCode());
  result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  AbstractEntity other = (AbstractEntity) obj;
  if (id == null) {
   if (other.id != null)
    return false;
  } else if (!id.equals(other.id))
   return false;
  if (timestamp == null) {
   if (other.timestamp != null)
    return false;
  } else if (!timestamp.equals(other.timestamp))
   return false;
  return true;
 } 
}

import java.util.ArrayList;
import java.util.Collection;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName="empresa")
public class EmpresaEntity extends AbstractEntity implements Comparable{

 @DatabaseField(columnName="empresa_nome")
 private String nome;
 @DatabaseField(columnName="empresa_abreviacao")
 private String abreviacao;
 @DatabaseField(columnName="empresa_codigo")
 private String codigo;
 @ForeignCollectionField(columnName="empresa_linhas")
 private Collection linhas = new ArrayList();
 
 // ormlite require default constructor
 public EmpresaEntity(){
  super();
 }
 
 public EmpresaEntity(String codigo,String abreviacao,String nome, Collection linhas){
  setCodigo(codigo);
  setAbreviacao(abreviacao);
  setNome(nome);
  setLinhas(linhas);
 }
 
 public EmpresaEntity(String codigo,String abreviacao,String nome){
  setCodigo(codigo);
  setAbreviacao(abreviacao);
  setNome(nome);
 }
 
 public Collection getLinhas() {return linhas;}
 public void setLinhas(Collection linhas) {this.linhas = linhas;}
 public String getNome() {return nome;}
 public void setNome(String nome) {this.nome = nome;}
 public String getAbreviacao() {return abreviacao;}
 public void setAbreviacao(String abreviacao) {this.abreviacao = abreviacao;}
 public String getCodigo() {return codigo;}
 public void setCodigo(String codigo) {this.codigo = codigo;}

 @Override
 public int compareTo(EmpresaEntity another) {
  if (equals(another)) {
   return 0;
  }
  return -1;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = super.hashCode();
  result = prime * result + ((abreviacao == null) ? 0 : abreviacao.hashCode());
  result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
  result = prime * result + ((linhas == null) ? 0 : linhas.hashCode());
  result = prime * result + ((nome == null) ? 0 : nome.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (!super.equals(obj))
   return false;
  if (getClass() != obj.getClass())
   return false;
  EmpresaEntity other = (EmpresaEntity) obj;
  if (abreviacao == null) {
   if (other.abreviacao != null)
    return false;
  } else if (!abreviacao.equals(other.abreviacao))
   return false;
  if (codigo == null) {
   if (other.codigo != null)
    return false;
  } else if (!codigo.equals(other.codigo))
   return false;
  if (linhas == null) {
   if (other.linhas != null)
    return false;
  } else if (!linhas.equals(other.linhas))
   return false;
  if (nome == null) {
   if (other.nome != null)
    return false;
  } else if (!nome.equals(other.nome))
   return false;
  return true;
 }
}

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👇

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👆