Where can I find a simple, working and easy code example for testing on Android with the ProviderTestCase2?
Best would be an OpenSource project actually using it - on the other hand, in the complexity of a real project it can become hard to realize the actual functionality, so any good example is welcome. The Google Android docs are not very specific and contain no proper example.
In this example I'm testing a ContentProvider named 'DataLayer' which exists in the app being tested; below, I've begun testing the ContentProvider interface to a table called 'ActiveUser'.
If anyone knows how to use newResolverWithContentProviderFromSql
please enlighten me!
package com.example.android.app.test;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.test.ProviderTestCase2;
import android.test.mock.MockContentResolver;
import android.util.Log;
import com.example.android.app.Constants;
import com.example.android.app.DataLayer;
import com.example.android.app.provider.contract.ActiveUserContract;
public class DataLayerTests extends ProviderTestCase2<DataLayer> {
private static final String TAG = DataLayerTests.class.getSimpleName();
MockContentResolver mMockResolver;
public DataLayerTests() {
super(DataLayer.class, Constants.DATA_LAYER_AUTHORITY);
}
#Override
protected void setUp() throws Exception {
super.setUp();
Log.d(TAG, "setUp: ");
mMockResolver = getMockContentResolver();
}
#Override
protected void tearDown() throws Exception {
super.tearDown();
Log.d(TAG, "tearDown:");
}
public void testActiveUserInsert__inserts_a_valid_record() {
Uri uri = mMockResolver.insert(ActiveUserContract.CONTENT_URI, getFullActiveUserContentValues());
assertEquals(1L, ContentUris.parseId(uri));
}
public void testActiveUserInsert__cursor_contains_valid_data() {
mMockResolver.insert(ActiveUserContract.CONTENT_URI, getFullActiveUserContentValues());
Cursor cursor = mMockResolver.query(ActiveUserContract.CONTENT_URI, null, null, new String[] {}, null);
assertNotNull(cursor);
assertEquals(1, cursor.getCount());
assertTrue(cursor.moveToFirst());
assertEquals(VALID_USERNAME, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.USERNAME)));
assertEquals(VALID_COMPANY_CODE, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.COMPANY_CODE)));
assertEquals(VALID_COMPANY_LETTER, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.COMPANY_LETTER)));
assertEquals(VALID_DRIVER_CODE, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.DRIVER_CODE)));
assertEquals(VALID_SITE_NUMBER, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.SITE_NUMBER)));
assertEquals(VALID_FIRST_NAME, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.FIRST_NAME)));
assertEquals(VALID_SURNAME, cursor.getString(cursor.getColumnIndex(ActiveUserContract.Columns.SURNAME)));
}
public void testActiveUserInsert__throws_SQLiteConstraintException_when_NOT_NULL_constraint_not_met() {
try {
mMockResolver.insert(ActiveUserContract.CONTENT_URI, getActiveUserContentValuesWithNullCompanyCode());
fail("SQLiteConstraintException should have been thrown!");
} catch (SQLiteConstraintException e) {
assertEquals("active_user.comp_code may not be NULL (code 19)", e.getMessage());
}
}
/** #return a ContentValues object with a value set for each ActiveUser column */
public static ContentValues getFullActiveUserContentValues() {
ContentValues v = new ContentValues(7);
v.put(ActiveUserContract.Columns.USERNAME, VALID_USERNAME);
v.put(ActiveUserContract.Columns.COMPANY_CODE, VALID_COMPANY_CODE);
v.put(ActiveUserContract.Columns.COMPANY_LETTER, VALID_COMPANY_LETTER);
v.put(ActiveUserContract.Columns.DRIVER_CODE, VALID_DRIVER_CODE);
v.put(ActiveUserContract.Columns.SITE_NUMBER, VALID_SITE_NUMBER);
v.put(ActiveUserContract.Columns.FIRST_NAME, VALID_FIRST_NAME);
v.put(ActiveUserContract.Columns.SURNAME, VALID_SURNAME);
return v;
}
public static ContentValues getActiveUserContentValuesWithNullCompanyCode() {
ContentValues v = new ContentValues(7);
v.put(ActiveUserContract.Columns.USERNAME, VALID_USERNAME);
v.putNull(ActiveUserContract.Columns.COMPANY_CODE);
v.put(ActiveUserContract.Columns.COMPANY_LETTER, VALID_COMPANY_LETTER);
v.put(ActiveUserContract.Columns.DRIVER_CODE, VALID_DRIVER_CODE);
v.put(ActiveUserContract.Columns.SITE_NUMBER, VALID_SITE_NUMBER);
v.put(ActiveUserContract.Columns.FIRST_NAME, VALID_FIRST_NAME);
v.put(ActiveUserContract.Columns.SURNAME, VALID_SURNAME);
return v;
}
private static final String VALID_SURNAME = "Brin";
private static final String VALID_FIRST_NAME = "Sergey";
private static final String VALID_SITE_NUMBER = "9";
private static final String VALID_DRIVER_CODE = "SergB201";
private static final String VALID_COMPANY_LETTER = "G";
private static final String VALID_COMPANY_CODE = "GOOGLE!";
private static final String VALID_USERNAME = "123456";
}
Android uses it internally to test its providers. For examples see here and here.
Google Code Search is great for this stuff :)
There is a pretty good example in the Android SDK Notepad sample project. Specifically NotePadProviderTest. Just make sure you have the samples installed via the SDK mamanger and you're good to go.
Related
I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.
Here is my code, any help would be appreciated.
`package com.example.vishal.connectiontest;
import java.sql.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button B1 = (Button)findViewById(R.id.button);
final TextView e1 = (TextView) findViewById(R.id.HelloWorld);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String result = main();
e1.setText(result.toString());
}
catch(java.lang.Exception e){
System.out.println("Exception");
}
}
});
}
}
class DemoClass
{
public static String main()throws Exception
{
String url = "jdbc:mysql://125.10.10.214/demo" ;
String uname = "root";
String pass = "";
String ip = "";
String query = "Select UserName from user_info where Id = '90000515'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("UserName");
return (name);
}
}`
Easiest way of integrating Database to your Android Application is using Firebase.
It's really easy to use and other than Database, it has File Storage Services, Cloud Messaging, Analytics and many more.
I would recommend use of firebase database.
Here have a look at it's Documentation:
https://firebase.google.com/docs/database/
Is there a way to block ads in an Android WebView? I am building app that lets users browse web pages, but need to block ads. Its basically a custom browser, but I need to get rid of ads.
What is my best option?
Based on: https://github.com/adblockplus/adblockplusandroid
saw this:
https://gist.github.com/rjeschke/eb1bb76128c5e9a9e7bc
import java.io.File;
import java.util.regex.Pattern;
import org.adblockplus.android.ABPEngine;
import org.adblockplus.libadblockplus.FilterEngine.ContentType;
import android.content.Context;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class BlockingWebViewClient extends WebViewClient
{
private ABPEngine engine;
private static final Pattern RE_JS = Pattern.compile("\\.js$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_CSS = Pattern.compile("\\.css$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_IMAGE = Pattern.compile("\\.(?:gif|png|jpe?g|bmp|ico)$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_FONT = Pattern.compile("\\.(?:ttf|woff)$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_HTML = Pattern.compile("\\.html?$", Pattern.CASE_INSENSITIVE);
public void start(Context context)
{
final File basePath = context.getFilesDir();
this.engine = ABPEngine.create(context, ABPEngine.generateAppInfo(context),
basePath.getAbsolutePath());
// Additional steps may be required here, i.e. :
// - subscription selection or updating
// - maybe also setting other options (like AcceptableAds)
// It might also be a good idea to delay the first calls until
// everything is loaded, have a look at AndroidFilterChangeCallback
// and ABPEngine.create()
}
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
// Determine the content
ContentType contentType = null;
if (RE_JS.matcher(url).find())
{
contentType = ContentType.SCRIPT;
}
else if (RE_CSS.matcher(url).find())
{
contentType = ContentType.STYLESHEET;
}
else if (RE_IMAGE.matcher(url).find())
{
contentType = ContentType.IMAGE;
}
else if (RE_FONT.matcher(url).find())
{
contentType = ContentType.FONT;
}
else if (RE_HTML.matcher(url).find())
{
contentType = ContentType.SUBDOCUMENT;
}
else
{
contentType = ContentType.OTHER;
}
// Check if we should block ... we sadly do not have the referrer chain here,
// might also be hard to get as we do not have HTTP headers here
if (engine.matches(url, contentType, new String[0]))
{
// If we should block, return empty response which results in a 404
return new WebResourceResponse("text/plain", "UTF-8", null);
}
// Otherwise, continue by returning null
return null;
}
}
It is done already:
https://github.com/adblockplus/libadblockplus-android
You can put it at xml:
<org.adblockplus.libadblockplus.android.webview.AdblockWebView
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
I am trying to use Android Browser.BOOKMARKS_URI to CRUD device bookmarks from within my app ( https://play.google.com/store/apps/details?id=com.elementique.web )
It's working fine on most of the devices, but does not work on some :-(
On those devices, trying to use bookmarks leads to
java.lang.IllegalArgumentException: Unknown URL content://browser/bookmarks
I now understand that Boookmark Uri can be different than the AOSP default value (i.e. "content://browser/bookmarks").
Question:
How can I get the correct Bookmark Uri for a given device?
I already 'collected' the following URI
private static final Uri BOKKMARKS_DEFAULT = Browser.BOOKMARKS_URI; // = Uri.parse("content://browser/bookmarks")
private static final Uri BOKKMARKS_URI_CHROME = Uri.parse("content://com.android.chrome.browser/bookmarks");
private static final Uri BOKKMARKS_URI_SAMSUNG_S_ = Uri.parse("content://com.sec.android.app.sbrowser.browser/bookmarks");
Is it a way to 'list' all available content URI (content://...) on a devices?
If yes, I could list them and search for occurrence of "/bookmarks" string and give a try with this URI.
Note:
I am currently in the process of creating a fallback mechanism if the app is not able to get a 'working' bookmark URI (i.e. my own Bookmark DB since I do need a bookmark feature in my app)
Is there a way to 'list' all available content URI (content://...) on a devices?
There's an opensource APP called "Content Provider Helper" in Play Store that can list all available content:// URI on the device. It uses PackageManager.GET_PROVIDER
Here's the respective class that searches all available content provider:
SearchProviderTask.java
package com.jensdriller.contentproviderhelper.task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.net.Uri;
public class SearchProvidersTask extends DialogAsyncTask<Uri, Void, List<String>> {
public SearchProvidersTask(Context context) {
super(context);
}
#Override
protected List<String> doInBackground(Uri... params) {
List<String> contentProviders = new ArrayList<String>();
try {
PackageManager pm = mContext.getPackageManager();
for (PackageInfo pack : pm.getInstalledPackages(PackageManager.GET_PROVIDERS)) {
ProviderInfo[] providers = pack.providers;
if (providers != null) {
for (ProviderInfo provider : providers) {
contentProviders.add("content://" + provider.authority);
}
}
}
} catch (Exception e) {
// PackageManager has died?
mException = e;
}
// Sort alphabetically and ignore case sensitivity
Collections.sort(contentProviders, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
return lowerCase(lhs).compareTo(lowerCase(rhs));
}
private String lowerCase(String s) {
return s.toLowerCase(Locale.getDefault());
}
});
return contentProviders;
}
}
Github: https://github.com/jenzz/ContentProviderHelper
This is the query to search the bookmarks;
cursor = mContentResolver.query(Browser.BOOKMARKS_URI, BOOKMARKS_PROJECTION,
Browser.BookmarkColumns.BOOKMARK + " == 1" +
" AND LOWER(" + Browser.BookmarkColumns.TITLE + ") LIKE ?",
new String[] { searchText + "%" },
Browser.BookmarkColumns.TITLE + " ASC");
I have a text file that has this information
Casino Canberra;21 Binara Street, Canberra ACT, 2601;Canberra Casino is a casino located in Civic in the central part of the Australian capital city of Canberra. The Casino is relatively small compared with other casinos in Australia.;(02) 6257 7074;www.canberracasino.com.au
National Museum of Canberra;Parkes Place, Canberra ACT, 2601;The National Museum of Australia explores the land, nation and people of Australia. Open 9am - 5pm every day except Christmas Day. General admission free.;(02) 6240 6411;www.nga.gov.au
which is stored in the sdcard
after this i retrieve the values using this method
package au.edu.canberra.g30813706;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Environment;
public class FileReader extends Activity{{
ArrayList<read> sInfo = new ArrayList<read>();
ArrayList<String> sLines = new ArrayList<String>();
String line;
String[] saLineElements;
String txtName = "AccomodationTxt.txt";
File root = Environment.getExternalStorageDirectory();
File path = new File(root, "CanberraTourism/" + txtName);
try {
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream(path)));
while ((line = br.readLine()) != null)
{
sLines.add(line);
//The information is split into segments and stored into the array
saLineElements = line.split(";");
//for (int i = 0; i < saLineElements.length; i++)
// sInfo.add(new read(saLineElements[i]));
sInfo.add(new read(saLineElements[0], saLineElements[1], saLineElements[3], saLineElements[4], saLineElements[5]));
}
br.close();
}
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
But i also have and object class to store each individual item into
package au.edu.canberra.g30813706;
public class read {
public String name;
public String address;
public String info;
public String phone;
public String www;
public read (String name, String address, String info, String phone, String www)
{
this.name = name;
this.address = address;
this.info = info;
this.phone = phone;
this.www = www;
}
}
The only issue im having is trying to display the information in a text view which i have no idea how to call the values i need
This is where im trying to insert it
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
}}
You should probably look into using the Application class. You can think of Application as a GUI-less activity which works like the model in a program following the MVC pattern. You can put all of your read objects into a data structure in your Application and then access them with accessors and mutators of your own design.
Take a look at this official doc.
As your code stands, you can only access your instances of read by obtaining a reference to your FileReader class, but your two activities are separate entities. You'd have to do something like this:
// This is the main activity and should be launched first
// Check your manifest to make sure it launches with this activity
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity
{
// Declare the file reader so you'll have a reference
FileReader reader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
// Instantiate the file reader
reader = new FileReader();
// Now you can access the array inside FileReader
// obviously, you need to have a text view called my_textView defined in the
// layout file associated with this activity
TextView myTextView = (TextView)findViewById(R.id.my_textView);
// displays the first element in FileReader's array list
myTextView.setText((String)reader.get(0));
}}
At the moment, you might be in a bit deep for your current understanding of Android and/or Java. I would encourage you to follow as many code examples as possible, get comfortable with Android and then go back to your project when you have a little more experience.
I am working on an Android application, where some of the functions that users should input: register, locate hospital location, search for messages (sent via sms to registered users) and can schedule and make appointments.
So far, all the activities are done. However, I need to know how to connect to the database in order to read and store this data. I am using Android 2.1, Mac OS X, and the SQLite Firefox extension.
This is the code I have to connect to the SQLite database, what am I doing wrong?
package com.bitnuts.imom;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbManager extends SQLiteOpenHelper {
private static final String DB_NAME = "iMom.sqlite";
private static final String DB_PATH = "/data/data/com.bitnuts.imom/databases/";
private static final Integer DB_VERSION = 1;
private static final String TAG = "DbManager";
private final Context context;
private SQLiteDatabase db;
private DbManager dbManager;
public DbManager(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
public DbManager open() {
dbManager = new DbManager(context);
db = dbManager.getWritableDatabase();
return this;
}
#Override
public void onCreate(SQLiteDatabase arg0) {
createNewDatabase();
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void createNewDatabase() {
InputStream assetsDB = null;
try {
assetsDB = context.getAssets().open(DB_NAME);
OutputStream dbOut = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = assetsDB.read(buffer)) > 0) {
dbOut.write(buffer, 0, length);
}
dbOut.flush();
dbOut.close();
assetsDB.close();
}
catch (IOException e) {
}
}
}
You cannot use the SQLite database directly in your application. You need to make some modifications. Such as the android_metadata table, etc. The blog post Using your own SQLite database in Android applications will help you.
There is no JDBC driver on Android, so you can not connect to databases on the network (SQLite or other): Android - Access to online Database SQlite
Android comes with an embedded SQLite database, but this is available only within the device.
Also, read why direct connection to databases from mobile devices is not recommended.
If you need to store/share some data on the network, then the usual way is to create a web service on the server that all devices can connect to. A very popular type of web service is REST, which is quite easy to set up in Java.
I suggest to use ORMLite for Android. The implementation becomes a lot simpler with it. Here's the getting started documentation.