How to refactor code?

I am learning Android and I have problem with repeated code.

MainActivity:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //others operations...
        TextView title = (TextView) findViewById(R.id.title);
        title.setText(myClass.title); 

        TextView author = (TextView) findViewById(R.id.title);
        author.setText(myClass.author); 

        TextView body = (TextView) findViewById(R.id.title);
        body.setText(myClass.body ); 

        //others operations...

    }
}

CustomActivity:

public class CustomActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //others operations...
        TextView title = (TextView) findViewById(R.id.title);
        title.setText(myClass.title); 

        TextView author = (TextView) findViewById(R.id.title);
        author.setText(myClass.author); 

        TextView body = (TextView) findViewById(R.id.title);
        body.setText(myClass.body ); 

        //others operations...

    }
}

SimpleFragment:

public class SimpleFragment extends Fragment {

    public SimpleFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

            //others operations...
            TextView title = (TextView) getView().findViewById(R.id.title);
            title.setText(myClass.title); 

            TextView author = (TextView) getView().findViewById(R.id.title);
            author.setText(myClass.author); 

            TextView body = (TextView) getView().findViewById(R.id.title);
            body.setText(myClass.body ); 

            //others operations...
    }
}

For activities I can create custom activity with this code and CustomActivity and CustomActivity will be inherit from CustomActivity, but how can I add for it Fragment? Fragment can’t inherit from Activity.

I can create custom class with this, but to use findViewById I would have to pass whole Activity… This is good idea?

Maybe in Android I can use traits?

This code works fine, but they will come up with similar and will change, so fixing in a few places is tiring.

Java track sample from stream

A have a stream of integer samples that are produced at high frequency (at the order of a few 1000s per second). I want to be able to track the minimum sample in the stream using sliding window approach. Basically I want to be able to tack the minimum sample over last N-seconds or last M-samples.

Only one of these conditions is required at a time, both N and M are known at compilation time and do not change at runtime. Samples beyond N or older than M can be discarded.

I was looking at IntStream but I am not sure how I could limit the stream either by the size or time of sample insertion.

Could you suggest an algorithm or a library that has either (or both) of these functionalities?

Thanks!

Schema Conversion in JAXB

Let’s assume, i have a sample class foo with an attribute bar. I have set annotations for JAXB, so I can export it to XML and reimport it again.

@XmlRootElement
public class foo {
    private int bar;

    @XmlElement()
    public int getBar() {
        return bar;
    }

    public void setBar(int bar) {
        this.bar = bar;
    }
}

The XML file should look somewhat like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bar>5</bar>
</foo>

Now I have learned, I can also make bar an attribute. Using @XmlAttribute instead would make it look like <foo bar="5"/>, which I would prefer.

I already have a lot of files using the old schema. Changing them by hand would be very cumbersome, so I’d like to do it automagically.

Does JAXB offer a convenient way to convert the files? Maybe different annotations for unmarshalling and marshalling? What else could I do to achieve this without too much effort?

Deep linking opens the app but does not open the exact url

I have made a WebView app and deep linking works on it. Whenever someone clicks a link to my website (on any other app) then my app opens but, the homepage loads up instead of the URL clicked. I want the exact URL of my website to open whenever the link is clicked instead of the homepage.

MainActivity.java

package com.yoalfaaz.yoalfaaz;

        import android.content.Intent;
        import android.os.Bundle;
        import android.support.design.widget.FloatingActionButton;
        import android.support.design.widget.Snackbar;
        import android.support.v4.widget.SwipeRefreshLayout;
        import android.support.v7.app.AppCompatActivity;
        import android.support.v7.widget.ShareActionProvider;
        import android.support.v7.widget.Toolbar;
        import android.view.View;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.webkit.WebSettings;
        import android.webkit.WebView;
        import android.webkit.WebViewClient;
        import android.support.v4.view.MenuItemCompat;

public class MainActivity extends AppCompatActivity {
    private WebView YoWeb;
    private ShareActionProvider mShareActionProvider;

    SwipeRefreshLayout swipe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        YoWeb = (WebView)findViewById(R.id.webview); // Move your declaration up here
        swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb(YoWeb.getUrl());  // Pass in the current url to refresh
            }
        });

        LoadWeb("https://www.yoalfaaz.com");  // load the home page only once
    }

    public void LoadWeb(String url) // Pass in URL you want to load
    {

        WebSettings webSettings = YoWeb.getSettings();
        webSettings.setJavaScriptEnabled(true);
        YoWeb.loadUrl(url);  // Load the URL passed into the method
        swipe.setRefreshing(true);
        YoWeb.setWebViewClient(new WebViewClient() {

            //onPageFinished Method
            public void onPageFinished(WebView view, String url) {
                //Hide the SwipeRefreshLayout
                swipe.setRefreshing(false);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (YoWeb.canGoBack()) {
            YoWeb.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @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.
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate menu resource file.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // Locate MenuItem with ShareActionProvider
        MenuItem item = menu.findItem(R.id.menu_item_share);

        // Fetch and store ShareActionProvider
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

        // Return true to display menu
        return true;
    }

    // Call to update the share intent
    private void setShareIntent(Intent shareIntent) {
        if (mShareActionProvider != null) {
            mShareActionProvider.setShareIntent(shareIntent);
        }
    }

    //private Intent setShareIntent() {
    //    Intent shareIntent = new Intent();
    //    shareIntent.setAction(Intent.ACTION_SEND);
    //    shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    //    shareIntent.setType("text/plain");
    //    startActivity(shareIntent);
    //    return shareIntent;
    //}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yoalfaaz.yoalfaaz">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter >
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:host="www.yoalfaaz.com" android:scheme="https"/>
            </intent-filter>
        </activity>
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

How to make it work as it works with most other apps? Like if we click on a YouTube link in WhatsApp then that particular video opens in YouTube app instead of YouTube homepage.

Display List of Items returned through query on a JSP

I am currently working on the Netbeans IDE with a Hibernate Framework project to retrieve values from the database and display it in a table structure. I have created the mapping with the database tables and the controller method to retrieve the values.

I am quite new to the hibernate framework and am not quite sure how to display the list of roles passed from the RoleController.java in my Role.jsp view. Any suggestions in this regard will be highly appreciated.

RoleController.java

package management;

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
 *
 * @author Taro
 */

@Named(value = "roleController")
@ManagedBean
@SessionScoped
public class RoleController implements Serializable {

    int employeeId;
    DataModel roleTitles;
    String roleTitle;
    RoleHelper helper;

    public RoleController() {
        helper = new RoleHelper();
    }

    public DataModel getRoleTitles() {
        if (roleTitles == null) {
            System.out.println("Successful");
            roleTitles = new ListDataModel(helper.getRoleTitles());
        }
        return roleTitles;
    }
}

Roles.jsp

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="header">
                        <h4 class="title">Available Roles</h4>
                        <p class="category">A list of Role Titles</p>
                    </div>
                    <div class="content">
                        <!--Display table of roles with an edit button against each role-->
                    </div>
                </div>
            </div>
        ...

RoleHelper.java

public class RoleHelper {

    Session session = null;

    public RoleHelper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    /*
    * Method : getRoleTitles
    * @description Retrieve all the unique role titles
    */
    public List getRoleTitles() {
    List<Role> roleList = null;
    try {
        org.hibernate.Transaction tx = session.beginTransaction();
        Query q = session.createQuery ("select distinct role.title from Role as role");
        roleList = (List<Role>) q.list();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return roleList;
    }
...

Role.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 21, 2017 1:12:44 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="management.Role" table="ROLE" schema="APP" optimistic-lock="version">
        <id name="roleid" type="int">
            <column name="ROLEID" />
            <generator class="assigned" />
        </id>
        <property name="employeeid" type="java.lang.Integer">
            <column name="EMPLOYEEID" />
        </property>
        <property name="title" type="string">
            <column name="TITLE" length="40" />
        </property>
    </class>
</hibernate-mapping>

Role.java

public class Role  implements java.io.Serializable {
    private int roleid;
    private Integer employeeid;
    private String title;

    public Role() {
    }

    public Role(int roleid) {
        this.roleid = roleid;
    }
    public Role(int roleid, Integer employeeid, String title) {
       this.roleid = roleid;
       this.employeeid = employeeid;
       this.title = title;
    }

    public int getRoleid() {
        return this.roleid;
    }

    public void setRoleid(int roleid) {
        this.roleid = roleid;
    }
    public Integer getEmployeeid() {
        return this.employeeid;
    }

    public void setEmployeeid(Integer employeeid) {
        this.employeeid = employeeid;
    }
    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Save JSON request as Item in dynamoDb

I have a request of the following JSON format:

{
 "profile": {
             "created": 1505202655,
             "createdBy": "abc",
             "updated": 1505202655,
             "updatedBy": "xyz"
            },
"likesId": [
            "0010127916"
           ],
"icon": null,
"Attributes": {
               "backgroundColor": "#FFFFFF",
               "logo": "images/Logos/P0010127916.jpg",
               "textColor": "#000000"
              },
"profileId": "PACYG0010916",
"restrictions": {
                 "clients": [
                             "Android",
                             "SmartTv"
                            ],
                 "UserTypes": [
                               "user1",
                               "user2"
                            ],
                 "periodEnd": 1512978849,
                 "periodStart": 1505202849
               },

}

I am trying to save the above JSON request Object in the dynamoDb table using putItem. However I am stuck in some issues which are as follows:

  1. Can I store this whole JSON request as-is(without escaping double quotes) in the form of item in dynamodb table?
  2. In case of likesId and Attributes I am storing them as a List and Map with the help of .withList and .withMap methods respectively, but in case of profile I have taken it as a POJO which has 4 states, how can I save this object with the putItem as I did not find any method for saving objects like this, as we have methods for string, numbers and other datatypes, how can I save my own object?

Any kind of guidance will be highly appreciated as I am new to dynamoDb and learning it by doing POC.

Java Swing – Overriding getPreferredSize() does not work

I’m in the middle of learning java and the following code does not change my window size although I have overrided getPreferredSize() function. Should it be placed somewhere else or am I doing it wrong? No matter what value I will asssign to DEFAULT_WIDTH or HEIGHT it always shows the same.

    package mouse;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;

/**
 * A component with mouse operations for adding and removing squares.
 */
public class MouseComponent extends JComponent
{
   private static final int DEFAULT_WIDTH = 1200;
   private static final int DEFAULT_HEIGHT = 1200;

   private static final int SIDELENGTH = 10;
   private ArrayList<Rectangle2D> squares;
   private Rectangle2D current; // the square containing the mouse cursor

   public MouseComponent()
   {
      squares = new ArrayList<>();
      current = null;

      addMouseListener(new MouseHandler());
      addMouseMotionListener(new MouseMotionHandler());
   }

   @Override
   public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }   

   public void paintComponent(Graphics g)
   {
      Graphics2D g2 = (Graphics2D) g;

      // draw all squares
      for (Rectangle2D r : squares)
      {
          g2.setColor(Color.RED);
          g2.fill(r);
      }
   }

Here is class which adds component:

package mouse;

import javax.swing.*;

/**
 * A frame containing a panel for testing mouse operations
 */
public class MouseFrame extends JFrame
{
   public MouseFrame()
   {
      add(new MouseComponent());
   }
}

Get the App Version

I want to get the app version and want to compare it with the value i have added to my database . So i want to know how can i get the app version in my app . (Must be in int)

I tried this but not works 🙁

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private int Appid;
//blah blah codes

private void GetAppID(){

try {
        PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
        String version = pInfo.versionName;
        int verCode = pInfo.versionCode;
          Appid = verCode ;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}

}

Why can I not import Appium if it’s in my Gradle dependencies?

I am using Intellij Community Edition with Gradle for the build.

here is my build.gradle deps:

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.+'
    testCompile 'info.cukes:cucumber-java:1.2.4', 'info.cukes:cucumber-junit:1.2.4'
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.amazonaws:aws-devicefarm-gradle-plugin:1.2'
    compile 'io.appium:java-client:4.0.0'
    classpath "io.qameta.allure:allure-gradle:<latest>"
}

When I try to do import any of the appium stuff from io. Intellij says it isn’t there. Even stranger in wy External Libraries there are numerous Gradle: libraries, but no Library for Appium.

I suppose Appium isn’t a library, but I have tried both complie and testCompile and with neither one can I import any appium namespaces.

import io.appium.java_client.functions.AppiumFunction;
import org.openqa.selenium.support.ui.ExpectedCondition;

these come up as not found in both my src and test folders. On the other hand I can import cucumber no problem.

import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

the 2 above work and intellij will compile with them.

Java – making a variable specific to a loop

So, I’m fairly new to Java and programming in general and haven’t really found a solution to my problem.

I’m writing a program which contains a for loop within a for loop, and in the first loop I am using the variable i and I wanted to use the same letter, but technically a different variable for the for loop within it.

for(int i = 0; i<=numofdoors.length; i+=modifier){
    for(int i = 0; i <= (numofdoors.length - numofdoors.length%modifier)/modifier; i+=1){
    // ....
    }
}

omitting details on what the program actually is doing, I was just wondering if there was a way to make the 1int i1 work only in each for loop, so I can use i as my variable in any for loop I use. If anyone can tell me how to do this and if it is even possible I’d appreciate it. If some other method is better practice I will also appreciate it.