I've been struggling around with this test. I want to test my created ContentProvider, using RoboGuice.
Currently the ContentProvider I have extends from RoboContentProvider.
However, I'm not being able to Make It Run.
It says there's no implementation for an Interface. However, the modules are being defined and so one.
Here's the code for the setUp Method on the AndroidTestCase.
#Override
public void setUp() {
Context context = InstrumentationRegistry.getTargetContext();
Application app = null;
try {
app = InstrumentationRegistry
.getInstrumentation()
.newApplication(Application.class.getClassLoader(), Application.class.getName(), context);
RoboGuice.setUseAnnotationDatabases(false);
RoboGuice.overrideApplicationInjector(app,
RoboGuice.newDefaultRoboModule(app),
new DatabaseModule(app)
);
mContentResolver = new MockContentResolver();
mContentProvider = new MobiModelsContentProvider();
mContentProvider.attachInfo(app, null);
mContentResolver.addProvider("com.authority.models.test", mContentProvider);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Related
I want to use Jacoco to collect code coverage for manually testing my Android apps. What I did was implement a Broadcast Receiver and ask Jacoco to collect coverage data when receiving the intent. Here is my receiver code:
public class CoverageReceiver extends BroadcastReceiver {
public static String TAG = "JacocoInstrumentation:";
private static final String DEFAULT_COVERAGE_FILE_PATH = "/sdcard/coverage.ec";
private static final boolean LOGD = true;
private String mCoverageFilePath;
#Override
public void onReceive(Context context, Intent intent) {
generateCoverageReport();
}
private void generateCoverageReport() {
if (LOGD)
Log.d(TAG, "generateCoverageReport()");
java.io.File coverageFile = new java.io.File(getCoverageFilePath());
OutputStream out = null;
// We may use this if we want to avoid refecltion and we include
// emma.jar
//RT.dumpCoverageData(coverageFile, false, false);
// Use reflection to call emma dump coverage method, to avoid
// always statically compiling against emma jar
try {
Object agent = Class.forName("org.jacoco.agent.rt.RT")
.getMethod("getAgent")
.invoke(null);
out = new FileOutputStream(coverageFile,false);
out.write((byte[]) agent.getClass().getMethod("getExecutionData", boolean.class)
.invoke(agent, false));
} catch (ClassNotFoundException e) {
reportJacocoError("Jacoco.jar not in the class path?", e);
} catch (SecurityException e) {
reportJacocoError(e);
} catch (NoSuchMethodException e) {
reportJacocoError(e);
} catch (IllegalArgumentException e) {
reportJacocoError(e);
} catch (IllegalAccessException e) {
reportJacocoError(e);
} catch (InvocationTargetException e) {
reportJacocoError(e);
} catch (FileNotFoundException e){
reportJacocoError(e);
} catch (IOException e) {
reportJacocoError(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
reportJacocoError(e);
}
}
}
}
public String getCoverageFilePath() {
if (mCoverageFilePath == null) {
return DEFAULT_COVERAGE_FILE_PATH;
} else {
return mCoverageFilePath;
}
}
public boolean setCoverageFilePath(String filePath){
if(filePath != null && filePath.length() > 0) {
mCoverageFilePath = filePath;
return true;
}
return false;
}
private void reportJacocoError(Exception e) {
reportJacocoError("", e);
}
private void reportJacocoError(String hint, Exception e) {
String msg = "Failed to generate Jacoco coverage. " + hint;
Log.e(TAG, msg, e);
}
}
I also add apply the plugin: 'jacoco' and testCoverageEnabled = true in the Gradle file.
I have seen a few people do this, so it should work. However, when I tried to broadcast the triggering intent and my receiver began to work, I got a ClassNotFoundException:
java.lang.ClassNotFoundException: org.jacoco.agent.rt.RT
...
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.jacoco.agent.rt.RT" on path:
...
Suppressed: java.lang.ClassNotFoundException: org.jacoco.agent.rt.RT
...
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
I have tried to specify the Jacoco version, or add Jacoco to the dependencies, but none of that worked. So what should I do?
I used this code it's working when i called from activity and fragment
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesAvailabilityException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
String AdId = adInfo.getId();
But when i called from pending intent like Package Removed then i want to call the web service at that time i need advertising id but i got null.if you people had done previously please suggest me.thanks in advance.
try use app context
as receivers could use activity context or app context - depends who&how started the receiver
AdvertisingIdClient.getAdvertisingIdInfo(context.getApplicationContext());
You can try this code and call the bellow method on onCreate
public void getAAID()
{
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(MyActivity.this);
String myId = adInfo != null ? adInfo.getId() : null;
Log.i("UIDMY",myId);
} catch (Exception e) {
Log.e("error", e);
}
}
});
}
Check complete post: how to get AAID programmatically
I want to create a TCP socket when a button is pressed in my first activity and then access that same socket object from any activity (not sure that closing and opening a socket in each activity is a good idea).
I tried quite a few methods having my mind set on a Singleton instance being the best solution to access an object though any activity, my problem is since this is a TCP socket I don't see AsyncTask as the smart idea (can only execute once, defies my point of having one instance of an object) and I don't see how I combine a regular Thread with a singleton.
Singleton code:
public class TCPSingleton extends Application {
private static TCPSingleton singleInstance;
String HostIP;
int tcp_port;
Socket clientSocket;
DataOutputStream outToServer;
public static TCPSingleton getInstance() {
return singleInstance;
}
#Override
public void onCreate() {
super.onCreate();
singleInstance = this;
singleInstance.initializeInstance();
}
protected void initializeInstance() {
this.HostIP = "10.0.0.6";
this.tcp_port = 9871;
try {
this.clientSocket = new Socket(this.HostIP, this.tcp_port);
this.outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send_data(String data){
try {
this.outToServer.writeBytes(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How do I merge a thread here (or what's the better idea other than singleton to do this).
I want to be able to turn off overscroll (the glowing effect when reaching the top or bottom of a page in 2.3+) however I also want my code to run in older versions of android that don't even have overscroll functionality. As per the documentation here: Android Backwards Compatibility I am using reflection in my custom webview class to call setOverScrollMode however everytime I call this on a device running 2.3.4, I get a NoSuchMethodException. Any idea why I can't retrieve this method?
Strangely, if I just call setOverScrollMode without any reflection, it works, so the method is definitely there.
public class MyWebView extends WebView{
public void compatibilitySetOverScroll(){
try {
Method mWebview_SetOverScroll = WebView.class.getMethod("setOverScrollMode", new Class[] { Integer.class } );
/* success, this is a 2.3+ */
if (mWebview_SetOverScroll != null) {
try {
mWebview_SetOverScroll.invoke(this, 2);
} catch (InvocationTargetException ite) {
throw new RuntimeException(ite.getCause());
} catch (IllegalAccessException ie) {
System.err.println("unexpected " + ie);
}
}
} catch (NoSuchMethodException nsme) {
/* failure, must be older device */
}
}
}
Try Integer.TYPE instead of Integer.class
More correct version:
public static void disableOverscroll(View view) {
Class<?> viewCls = view.getClass();
try {
Method m = viewCls.getMethod("setOverScrollMode",
new Class[] { int.class });
int OVER_SCROLL_NEVER = (Integer) viewCls.getField(
"OVER_SCROLL_NEVER").get(view);
m.invoke(view, OVER_SCROLL_NEVER);
} catch (Exception e) {
// swallow
}
}
another way :
try
{
Class<?> myTarget = Class.forName("android.widget.HorizontalScrollView");
Method myMethod = myTarget.getDeclaredMethod("setOverScrollMode", Integer.TYPE);
myMethod.invoke(scrollView, 2);
}
catch (Exception e)
{
e.printStackTrace();
}
Is it possible to retrieve the time an account was last synchronized, like the system Settings->Accounts&Sync app does? I'm using Android 2.2.
Looking at the 2.2 source for AccountSyncSettings.java, I see the status is retrieved using:
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
but SyncStatusInfo and getSyncStatus don't seem to be part of the public API (marked with #hide). Is there some other way to get at this info?
You can use reflection to achieve this purpose.Here is my code to implement this
private long getLasySyncTime() {
long result = 0;
try {
Method getSyncStatus = ContentResolver.class.getMethod(
"getSyncStatus", Account.class, String.class);
if (mAccount != null && mSyncAdapter != null) {
Object status = getSyncStatus.invoke(null, mAccount,
mSyncAdapter.authority);
Class<?> statusClass = Class
.forName("android.content.SyncStatusInfo");
boolean isStatusObject = statusClass.isInstance(status);
if (isStatusObject) {
Field successTime = statusClass.getField("lastSuccessTime");
result = successTime.getLong(status);
TLog.d(WeixinSetting.class, "get last sync time %d", result);
}
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
TLog.d(WeixinSetting.class, e.getMessage() + e.getCause().getMessage());
} catch (IllegalArgumentException e) {
} catch (ClassNotFoundException e) {
} catch (NoSuchFieldException e) {
} catch (NullPointerException e) {
}
return result;
}
The Settings app uses ContentResolver.getSyncStatus(account, authority). However, this is not part of the public API. You can use it, but it could break with any future release.