Wednesday, 22 March 2017

WebView Dynamic Loading

public class PrintAct extends AppCompatActivity {

    private WebView myWebView;
    String mailReceivedTime;
    String mailPreview;
    String mailSubject;
    String folderPath;
    String mailFromName;
    int uid;
    public static int count = 5;
    static StringBuffer sb;


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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Count();



     

        WebView webView = new WebView(this);
        webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view,
                                                    String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                createWebPrintJob(view);
                myWebView = null;
            }
        });

        Log.i("from ", mailFromName);

        String htmlDocument =
                "<html><body><h1> From:" + mailFromName + "</h1>" + "</br>" + "<h1> To:" + mailFromName + "</h1></br>" + "<h1>Subject:" + mailSubject + "</h1></br>" + "<h2>" + mailReceivedTime + "</h2></br>" +
                        "<h3><p>" + mailPreview + "</p></h3>" + "<h1>" + sb.toString() + "</h1>" +
                        "</body></html>";

        webView.loadDataWithBaseURL(null, htmlDocument,
                "text/HTML", "UTF-8", null);

        myWebView = webView;
    }


    private void createWebPrintJob(WebView webView) {

        PrintManager printManager = (PrintManager) this
                .getSystemService(Context.PRINT_SERVICE);

        PrintDocumentAdapter printAdapter =
                null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            printAdapter = webView.createPrintDocumentAdapter();
        }

        String jobName = getString(R.string.app_name) + " Print Test";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            printManager.print(jobName, printAdapter,
                    new PrintAttributes.Builder().build());
        }
    }





    private static void Count() {
        sb = new StringBuffer();
        for (int j = 0; j <= 5; j++) {
            sb.append("<img src=file:///android_res/drawable/other_large_icon_thumbnail.png />" + "</br></br>");

        }
    }

}



http://www.androidsnippets.com/webview-with-custom-html-and-local-images.html

Utilmethod to convert SP to PX

private static float sDensity = Float.MAX_VALUE;
private static float sDensity4Fonts = Float.MAX_VALUE;


public static int convertSpToPx(int spSize) {
    return Math.round((float) spSize / getDisplayDensity4Fonts());
}

private static DisplayMetrics getDisplayMetrics() {
    Display display = ((WindowManager) API.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    return metrics;
}

private static float getDisplayDensity4Fonts() {
    synchronized (Helper.class) {
        if (sDensity4Fonts == Float.MAX_VALUE) {
            sDensity4Fonts = getDisplayMetrics().density * getFontScale();
        }
        return sDensity4Fonts;
    }
}

Thursday, 16 March 2017

Android Volley

 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                url, null,
                new Response.Listener<JSONObject>() {

                    @Override                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        listener.notifyResponse(response.toString(), 200);

                    }
                }, new Response.ErrorListener() {

            @Override            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());

            }
        }) {

            /**             * Passing some request headers             * */            @Override            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");
                headers.put("apiKey", "xxxxxxxxxxxxxxx");
                headers.put("Cookie", sam);
                return headers;
            }

        };

// Adding request to request queue        App.getInstance().addToRequestQueue(jsonObjReq);


    }


UseFul Links



Wednesday, 15 March 2017

Android Espresso

Build.gradle


//In default config
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

//In dependencies
androidTestCompile 'com.android.support.test:runner:0.5'androidTestCompile 'com.android.support.test:rules:0.5'
//Espresso coreandroidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.0') {
exclude group: 'com.android.support', module: 'appcompat' exclude group: 'com.android.support', module: 'support-v4' exclude module: 'support-annotations' exclude module: 'recyclerview-v7'}

Sample Example of UI test using espresso


import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;



import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withHint;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

public class ActivityTest {
Context appContext;
@Rule
public ActivityTestRule<Activity> mActivityTestRule =
new ActivityTestRule<Activity>(Activity.class);
@Before
public void setUP() {
appContext = InstrumentationRegistry.getTargetContext();
}

@Test
public void firstTest() {
// Context of the app under test.

String toEmail = "sonuash@gmail.com";
String toTextView = appContext.getResources().getString(R.string.sample);
String toSubView = appContext.getResources().getString(R.string.samplestr);


//Type text in edittext through espresso
onView(ViewMatchers.withId(R.id.toAddrFieldView)).perform(typeText(toEmail));
//match text displayed in textview
onView(withId(R.id.toAddrTextView)).check(matches(allOf(withText(toTextView), isDisplayed())));
//match hint displayed in edittes
onView(withId(R.id.subjectFieldView)).check(matches(withHint(toSubView)));
//click on any button / edittext
onView(ViewMatchers.withId(R.id.toolbar)).perform(click());

}
}

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...