Android Working with RecyclerView

build.gradle

compile 'com.android.support:recyclerview-v7:25.3.1'

Country.java

public class Country {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    private String name;
    private String capital;
}

country_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textViewCountryName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginEnd="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="50dp"
        android:layout_marginStart="10dp"
        android:gravity="center"
        android:text="Country Name"
        android:textStyle="bold"
        android:textAppearance="@android:style/TextAppearance.Large" />

    <TextView
        android:id="@+id/textViewCountryCapital"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/textViewCountryName"
        android:layout_toRightOf="@+id/textViewCountryName"
        android:gravity="center"
        android:text="Capital Name"
        android:textAppearance="@android:style/TextAppearance.Large" />
</RelativeLayout>

CountryAdapter.java

public class CountryAdapter extends RecyclerView.Adapter<CountryAdapter.CountryViewHolder> {

    private List<Country> countryList;

    public CountryAdapter(List<Country> countries)
    {
        this.countryList=countries;
    }

    @Override
    public CountryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.country_row, parent, false);

        CountryViewHolder viewHolder=new CountryViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(CountryViewHolder holder, int position) {

        Country country=countryList.get(position);

        holder.textViewCountryName.setText(country.getName());
        holder.textViewCountryCapital.setText(country.getCapital());
    }

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

    public class CountryViewHolder extends RecyclerView.ViewHolder{

        public TextView textViewCountryName;
        public TextView textViewCountryCapital;

        public CountryViewHolder(View itemView) {
            super(itemView);

            textViewCountryName= (TextView) itemView.findViewById(R.id.textViewCountryName);
            textViewCountryCapital= (TextView) itemView.findViewById(R.id.textViewCountryCapital);
        }
    }
}

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ir.mhdr.a082.MainActivity">


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    List<Country> countryList=new ArrayList<>();
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;

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

        generateCountries();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // animate items with DefaultItemAnimator
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        // specify an adapter (see also next example)
        adapter = new CountryAdapter(countryList);
        recyclerView.setAdapter(adapter);
    }

    private void generateCountries()
    {
        Country country1=new Country();
        country1.setName("Iran");
        country1.setCapital("Tehran");

        Country country2=new Country();
        country2.setName("Netherlands");
        country2.setCapital("Amsterdam");

        Country country3=new Country();
        country3.setName("Turkey");
        country3.setCapital("Ankara");

        Country country4=new Country();
        country4.setName("Ukraine");
        country4.setCapital("Kiev");


        Country country5=new Country();
        country5.setName("Russia");
        country5.setCapital("Moscow");

        Country country6=new Country();
        country6.setName("Chile");
        country6.setCapital("Santiago");

        Country country7=new Country();
        country7.setName("United States");
        country7.setCapital("Washington, D.C.");

        countryList.add(country1);
        countryList.add(country2);
        countryList.add(country3);
        countryList.add(country4);
        countryList.add(country5);
        countryList.add(country6);
        countryList.add(country7);
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/082
https://developer.android.com/training/material/lists-cards.html
https://developer.android.com/guide/topics/ui/layout/recyclerview.html
https://guides.codepath.com/android/using-the-recyclerview
http://www.androidhive.info/2016/01/android-working-with-recycler-view/

Disable swipe in a ViewPager on Android

public class CustomViewPager extends ViewPager {

private boolean enabled;

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.enabled = true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (this.enabled) {
        return super.onTouchEvent(event);
    }

    return false;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (this.enabled) {
        return super.onInterceptTouchEvent(event);
    }

    return false;
}

public void setPagingEnabled(boolean enabled) {
    this.enabled = enabled;
}
}
CustomViewPager mViewPager = (CustomViewPager) findViewById(R.id.pager);
mViewPager.setPagingEnabled(false);

References
http://stackoverflow.com/questions/31000076/how-to-make-swipe-disable-in-a-view-pager-in-android

BottomNavigationView is not full width on Android

The BottomNavigationView is not displayed as full width because it is not supposed to.
If you want to fill the space behind the BottomNavigationView, you can set the background color of the view to be the same color as the items background:

<android.support.design.widget.BottomNavigationView
     android:background="@color/bottom_view_color"
     app:itemBackground="@color/bottom_view_color"

     // .... />

References
http://stackoverflow.com/questions/41432902/bottomnavigationview-is-not-full-width/

Determine when Fragment becomes visible in ViewPager

@Override
public void setUserVisibleHint(boolean visible)
{
    super.setUserVisibleHint(visible);
    if (visible && isResumed())
    {
        //Only manually call onResume if fragment is already visible
        //Otherwise allow natural fragment lifecycle to call onResume
        onResume();
    }
}

@Override
public void onResume()
{
    super.onResume();
    if (!getUserVisibleHint())
    {
        return;
    }

    //INSERT CUSTOM CODE HERE
}

References
http://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager
https://developer.android.com/reference/android/app/Fragment.html#setUserVisibleHint(boolean)
https://developer.android.com/reference/android/app/Fragment.html#setMenuVisibility(boolean)

LibreOffice PPA

sudo apt-get install python-software-properties
sudo apt-add-repository ppa:libreoffice/ppa
sudo apt update

Create an Index using JPA

@Entity
@Table(name = "region",
       indexes = {@Index(name = "my_index_name",  columnList="iso_code", unique = true),
                  @Index(name = "my_index_name2", columnList="name",     unique = false)})
public class Region{

    @Column(name = "iso_code", nullable = false)
    private String isoCode;

    @Column(name = "name", nullable = false)
    private String name;

} 

or

@Entity
@Table(name    = "company__activity", 
       indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{

References
http://stackoverflow.com/questions/3405229/specifying-an-index-non-unique-key-using-jpa

Java 8 Stream Examples

public class Java8Tester {
   public static void main(String args[]){
      System.out.println("Using Java 7: ");
    
      // Count empty strings
      List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
      System.out.println("List: " +strings);
      long count = getCountEmptyStringUsingJava7(strings);
    
      System.out.println("Empty Strings: " + count);
      count = getCountLength3UsingJava7(strings);
    
      System.out.println("Strings of length 3: " + count);
    
      //Eliminate empty string
      List<String> filtered = deleteEmptyStringsUsingJava7(strings);
      System.out.println("Filtered List: " + filtered);
    
      //Eliminate empty string and join using comma.
      String mergedString = getMergedStringUsingJava7(strings,", ");
      System.out.println("Merged String: " + mergedString);
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
    
      //get list of square of distinct numbers
      List<Integer> squaresList = getSquares(numbers);
      System.out.println("Squares List: " + squaresList);
      List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
    
      System.out.println("List: " +integers);
      System.out.println("Highest number in List : " + getMax(integers));
      System.out.println("Lowest number in List : " + getMin(integers));
      System.out.println("Sum of all numbers : " + getSum(integers));
      System.out.println("Average of all numbers : " + getAverage(integers));
      System.out.println("Random Numbers: ");
    
      //print ten random numbers
      Random random = new Random();
    
      for(int i=0; i < 10; i++){
         System.out.println(random.nextInt());
      }
    
      System.out.println("Using Java 8: ");
      System.out.println("List: " +strings);
    
      count = strings.stream().filter(string->string.isEmpty()).count();
      System.out.println("Empty Strings: " + count);
    
      count = strings.stream().filter(string -> string.length() == 3).count();
      System.out.println("Strings of length 3: " + count);
    
      filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());
      System.out.println("Filtered List: " + filtered);
    
      mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
      System.out.println("Merged String: " + mergedString);
    
      squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());
      System.out.println("Squares List: " + squaresList);
      System.out.println("List: " +integers);
    
      IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();
    
      System.out.println("Highest number in List : " + stats.getMax());
      System.out.println("Lowest number in List : " + stats.getMin());
      System.out.println("Sum of all numbers : " + stats.getSum());
      System.out.println("Average of all numbers : " + stats.getAverage());
      System.out.println("Random Numbers: ");
    
      random.ints().limit(10).sorted().forEach(System.out::println);
    
      //parallel processing
      count = strings.parallelStream().filter(string -> string.isEmpty()).count();
      System.out.println("Empty Strings: " + count);
   }
  
   private static int getCountEmptyStringUsingJava7(List<String> strings){
      int count = 0;
    
      for(String string: strings){
    
         if(string.isEmpty()){
            count++;
         }
      }
      return count;
   }
  
   private static int getCountLength3UsingJava7(List<String> strings){
      int count = 0;
    
      for(String string: strings){
    
         if(string.length() == 3){
            count++;
         }
      }
      return count;
   }
  
   private static List<String> deleteEmptyStringsUsingJava7(List<String> strings){
      List<String> filteredList = new ArrayList<String>();
    
      for(String string: strings){
    
         if(!string.isEmpty()){
             filteredList.add(string);
         }
      }
      return filteredList;
   }
  
   private static String getMergedStringUsingJava7(List<String> strings, String separator){
      StringBuilder stringBuilder = new StringBuilder();
    
      for(String string: strings){
    
         if(!string.isEmpty()){
            stringBuilder.append(string);
            stringBuilder.append(separator);
         }
      }
      String mergedString = stringBuilder.toString();
      return mergedString.substring(0, mergedString.length()-2);
   }
  
   private static List<Integer> getSquares(List<Integer> numbers){
      List<Integer> squaresList = new ArrayList<Integer>();
    
      for(Integer number: numbers){
         Integer square = new Integer(number.intValue() * number.intValue());
      
         if(!squaresList.contains(square)){
            squaresList.add(square);
         }
      }
      return squaresList;
   }
  
   private static int getMax(List<Integer> numbers){
      int max = numbers.get(0);
    
      for(int i=1;i < numbers.size();i++){
    
         Integer number = numbers.get(i);
      
         if(number.intValue() > max){
            max = number.intValue();
         }
      }
      return max;
   }
  
   private static int getMin(List<Integer> numbers){
      int min = numbers.get(0);
    
      for(int i=1;i < numbers.size();i++){
         Integer number = numbers.get(i);
    
         if(number.intValue() < min){
            min = number.intValue();
         }
      }
      return min;
   }
  
   private static int getSum(List numbers){
      int sum = (int)(numbers.get(0));
    
      for(int i=1;i < numbers.size();i++){
         sum += (int)numbers.get(i);
      }
      return sum;
   }
  
   private static int getAverage(List<Integer> numbers){
      return getSum(numbers) / numbers.size();
   }
}

 

References
https://www.tutorialspoint.com/java8/java8_streams.htm
http://www.drdobbs.com/jvm/lambdas-and-streams-in-java-8-libraries/240166818