I have a simple app with 2 activities: MainActivity (with 2 Fragments) and GameActivity.
In one of the Fragments "FragmentHome" I have a FloatingButton which upon press launches my GameActivity.
When the game ends I show an AlertDialog with a button which upon click does: GameActivity.this.onBackPressed(); which returns the user back to FragmentHome where he can launch the game again.
The problematic scenario is: the user launches the game (from the FragmentHome FloatingButton), plays it, the game is over in few seconds and user is directed back to FragmentHome where he launches the game again; if to repeat this 7-8 times then at some point the FloatingButton click will just terminate the application without a logcat error thrown. The only weird 'hint' in logcat I can see is D/StrictMode: StrictMode policy violation: android.os.strictmode.DiskReadViolation which does not really say much about the app termination.
I monitored the App memory usage (from the Android device itself): it is normal, between 53MB and 66MB.
My FloatingButton on click:
myView.findViewById(R.id.btnStartGame).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!AppController.appOnline) {
Snackbar.make(lstLuckyUsers, getString(R.string.txt_no_internet), 2000).show();
return;
}
Intent gameIntent = new Intent(FragmentHome.this.context, GameActivity.class);
FragmentHome.this.context.startActivity(gameIntent);
}
});
My GameActivity AlertDialog button click:
MaterialButton btnOK = dialogView.findViewById(R.id.btnOK);
if (btnOK != null)
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// close dialog and game Activity
gameOverDialog.dismiss();
GameActivity.this.onBackPressed();
}
});
Could you please advise where shall I look for the problem? It feels like the Garbage Collector is not doing its job as expected or there is a Framework I use and this brings the troubles.
The dependencies are plain standard:
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.mygame.mygame"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.navigation:navigation-fragment:2.3.3'
implementation 'androidx.navigation:navigation-ui:2.3.3'
// volley lib
implementation 'com.android.volley:volley:1.1.1'
// FAN Ad
implementation 'com.facebook.android:audience-network-sdk:6.0.0'
// Google In-App Review
implementation 'com.google.android.play:core:1.9.1'
}
Related
I'm developing an android application where I'm using a JsonObjectRequest and Android's Volley.
My app seems to runs perfectly fine on Android's Pixel XL API 30(printing out the desired output), but doesn't work with Android's Pixel 2 API 29, even though I've defined minSdkVersion 16 in build.gradle
This is my build.gradle:
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.krish.parsedata"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.android.volley:volley:1.2.0'
}
This is my MainActivity.java:
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
String url = "https://www.google.com";
String apiUrl = "https://jsonplaceholder.typicode.com/todos";
String getApiUrl = "https://jsonplaceholder.typicode.com/todos/1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
getApiUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("url", "onCreate: " + response.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("url2", "There was an error");
}
});
queue.add(jsonObjectRequest);
}
}
Thank you!
Update: This keeps on showing up:
Android Studio is using the following JDK location when running Gradle:
/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home
Using different JDK locations on different processes might cause Gradle to
spawn multiple daemons, for example, by executing Gradle tasks from a terminal
while using Android Studio.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.krish.parsedata">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<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/Theme.ParseData">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
UPDATE: It works on all API 30 level devices, but not on anything lower, I've tryed changing min sdk version, complie sdk version, and build sdk version, no luck. Not sure what to do. Help would be appreciated a lot. Thank you.
I have found out the error. The problem had nothing to do with my code or build configuration, it was the emulator itself. I deleted/re-installed the emulator, and things are working normal.
Hope this helps anyone struggling with the same problem.
i'm trying to display Facebook ads on Android. I have included the Audience Network .jar on my Android Studio Project. Also added the activity to the Android Manifest.
This is the build.gradle:
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
testOptions {
unitTests.returnDefaultValues = true
}
defaultConfig {
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable false
}
debug {
debuggable true
jniDebuggable true
minifyEnabled false
shrinkResources false
}
}
}
dependencies {
// Required -- JUnit 4 framework
testCompile 'junit:junit:4.12'
// Optional -- Mockito framework
testCompile 'org.mockito:mockito-core:1.10.19'
compile 'com.google.android.gms:play-services:10.2.0'
compile files('libs/AudenceNetwork-4.24.0.jar')
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:recyclerview-v7:25.0.0'
}
This is a snippet on how i load and show interstitials and rewarded:
com.facebook.ads.InterstitialAd interstitial;
com.facebook.ads.RewardedVideoAd rewarded
public void loadInterstitial() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (interstitial == null) {
interstitial = new com.facebook.ads.InterstitialAd(activity, interstitialAd.getCode());
CustomFacebookInterstitialAdListener interestitialListener = new CustomFacebookInterstitialAdListener(AudienceNetworkAdProvider.this);
interstitial.setAdListener(interestitialListener);
}
interstitial.loadAd();
}
});
}
public void showInterstitial() {
if (isInterstitialAvailable()) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
interstitial.show();
}
});
}
}
public void loadRewardedAd() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (rewarded == null) {
rewarded = new com.facebook.ads.RewardedVideoAd(activity, rewardedAd.getCode());
CustomFacebookRewardedAdListener rewardedListener = new CustomFacebookRewardedAdListener(AudienceNetworkAdProvider.this);
rewarded.setAdListener(rewardedListener);
}
rewarded.loadAd();
}
});
}
public void showRewardedAd() {
if (isRewardedAdAvailable()) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
rewarded.show();
}
});
}
}
The code works fine on a Android native test app.
I'm making an adaptation to Unity, so i can show ads on a game. However, every time i want to display an ad it randomly crashes the app. Most of the times it let me see one interstitial or rewarded, but after that crashes.
This is how my Plugins/Android folder looks like:
AndroidManifest.xml
appcompat-v7-24.0.0
myaudiencenetworkadapter.aar
play-services-10.0.1.aar
play-services-auth-10.0.1
play-services-auth-base-10.0.1
play-services-basement-10.0.1
play-services-drive-10.0.1
play-services-tasks-10.0.1
recyclerview-v7-24.0.0
support-v4-24.0.0
It crashes when com.facebook.ads.RewardedVideoAd.show() method is invoked.
This is the log of the crash:
08-07 16:51:30.861 16820-16820/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.somepackage.test, PID: 16820
java.lang.Error: FATAL EXCEPTION [main]
Unity version : 5.5.3f1
Device model : samsung SM-G925I
Device fingerprint: samsung/zeroltedv/zerolte:6.0.1/MMB29K/G925IDVS3EQF1:user/release-keys
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.ads.internal.DisplayAdController.c()' on a null object reference
at com.facebook.ads.RewardedVideoAd.show(Unknown Source)
at com.boxit.ads.facebook.AudienceNetworkAdProvider$3.run(AudienceNetworkAdProvider.java:168)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Any ideas?
You shouldn't be messing with Java and the Facebook jar in Android Studio while there is an official Unity Facebook plugin. See this link for instructions on how to set it up and here to get the actual SDK.
When you download the plugin you will find InterstitialAdScene, RewardedVideoAdScene and NativeAdScene scenes that contains sample codes for you should load InterstitialAdScene scene since that's what you are looking for.
Below is C# Interstitial Ad example from the InterstitialAdTest.cs file in the AudienceNetwork\Samples\Interstitial folder.
public class InterstitialAdTest : MonoBehaviour
{
private InterstitialAd interstitialAd;
private bool isLoaded;
// UI elements in scene
public Text statusLabel;
// Load button
public void LoadInterstitial ()
{
this.statusLabel.text = "Loading interstitial ad...";
// Create the interstitial unit with a placement ID (generate your own on the Facebook app settings).
// Use different ID for each ad placement in your app.
InterstitialAd interstitialAd = new InterstitialAd ("YOUR_PLACEMENT_ID");
this.interstitialAd = interstitialAd;
this.interstitialAd.Register (this.gameObject);
// Set delegates to get notified on changes or when the user interacts with the ad.
this.interstitialAd.InterstitialAdDidLoad = (delegate() {
Debug.Log ("Interstitial ad loaded.");
this.isLoaded = true;
this.statusLabel.text = "Ad loaded. Click show to present!";
});
interstitialAd.InterstitialAdDidFailWithError = (delegate(string error) {
Debug.Log ("Interstitial ad failed to load with error: " + error);
this.statusLabel.text = "Interstitial ad failed to load. Check console for details.";
});
interstitialAd.InterstitialAdWillLogImpression = (delegate() {
Debug.Log ("Interstitial ad logged impression.");
});
interstitialAd.InterstitialAdDidClick = (delegate() {
Debug.Log ("Interstitial ad clicked.");
});
// Initiate the request to load the ad.
this.interstitialAd.LoadAd ();
}
// Show button
public void ShowInterstitial ()
{
if (this.isLoaded) {
this.interstitialAd.Show ();
this.isLoaded = false;
this.statusLabel.text = "";
} else {
this.statusLabel.text = "Ad not loaded. Click load to request an ad.";
}
}
void OnDestroy ()
{
// Dispose of interstitial ad when the scene is destroyed
if (this.interstitialAd != null) {
this.interstitialAd.Dispose ();
}
Debug.Log ("InterstitialAdTest was destroyed!");
}
// Next button
public void NextScene ()
{
SceneManager.LoadScene ("AdViewScene");
}
}
I finally solved the issue.
I was destroying Audience Network ads on the onPause event from my Unity activity. Every time an ad is displayed, onPause event is called so it was a mess.
I create app named "onlineContact" that save your contact in cloud and you can access your contacts from any Android phone using login. This app is working fine when I test it. I connect my mobile with computer and run it from android studio it's good. So, I upload this app on Google Play Store but When I download and install app from play store it's not worked. What's the problem with this.
Here is my app link on Play store onlineContact
Install it click on any link like login, create account or forget password.
When you clicked any of them it's crashed.
I tried it again from android studio and install it and it's working fine. Now how can I checked what the problem with this. I'm not able to place all code of my app here. Please help me about this what i can do.
UPDATE
Bulid.gradil(Modual:app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.azeem.onlinecontact"
minSdkVersion 11
targetSdkVersion 24
versionCode 3
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services-ads:10.0.1'
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
protected void login(View view){
EditText etxtPhoneNumber = (EditText) findViewById(R.id.etxtPhoneNumber);
EditText etxtPassword = (EditText) findViewById(R.id.etxtPassword);
String phoneNumber = etxtPhoneNumber.getText().toString();
String password = etxtPassword.getText().toString();
String action = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(action, phoneNumber, password);
}
protected void forgetPassActivity(View view){
startActivity(new Intent(this, ForgetPassword.class));
}
protected void createAccount(View view){
Intent loginIntent = new Intent(this, CreateAccount.class);
startActivity(loginIntent);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
}
This activity open fine when I run app But it not work any further when I clicked on any button it will crashed.
I've been working on an application that is running on multiple different AR headsets that all run different versions of Android. I have several different build flavors for the different versions:
rej {
compileSdkVersion 'Recon Instruments:Recon Instruments SDK Add-On:16'
applicationId "edu.cnu.nasa.hud.reconjet"
versionName "1.0-rej"
minSdkVersion 16
}
gls {
compileSdkVersion 23
applicationId "edu.cnu.nasa.hud.glass"
versionName "1.0-gls"
minSdkVersion 19
}
vuz_100 {
compileSdkVersion 23
applicationId "edu.cnu.nasa.hud.vuzix_100"
versionName "1.0-vzx_100"
minSdkVersion 15
}
The issue I'm having is that the application crashes when GDK specific classes are used. The GestureDetector causes java.lang.ExceptionInInitializerError to be thrown when running on any device that's not Glass. I can't understand why, since I'm only initializing and using it when the build flavor name contains "gls".
private void addGesturesForGlass(){
if(BUILD_FLAVOR.contains("gls")) {
gestureDetector = new GestureDetector(this);
gestureDetector.setBaseListener(new GestureDetector.BaseListener() {
#Override
public boolean onGesture(Gesture gesture) {
switch (gesture) {
case SWIPE_RIGHT:
//This is a forward swipe
advanceColorShift();
return true;
case SWIPE_LEFT:
//This is a back swipe
return true;
}
return false;
}
});
} else {
gestureDetector = null;
}
}
According to Logcat, the exception that ultimately raises the error originates from the switch(gesture) line, but that line is never reached on any device besides glass. Is there a way to have this code present in all flavors without causing the error?
I want to set up a project in Android Studio. However, I don't want an Android App, just the test project.
Following the lastest release of UiAutomator, I was trying to set a class extending ActivityInstrumentationTestCase2 and start my tests from there.
However, I've stumbled in one thing: I can't figure out how to create the project without making it an app.
The options for creating a new project are:
Start a new Android Studio Project
Open existing projects
Import projects
I did:
Start a new project, give it a name, set minSDK and choose "No activity"
Open build.gradle (under app) and add the dependencies and instrumentation information mentioned in the end of Testing Support Library
Opened androidTest under src and changed the main file: changed to ActivityInstrumentationTestCase2, added setUp and tearDown; defined RunWith Junit4 (as indicated in Testing Support Library)
I build the project (build successful) - Press the green arrow next to build in the "action bar"
My problems are:
How do I install this in the device?
How do I run it in the device?
Do I need to do anything in the AndroidManifest?
Am I editing in the right place? Should I do anything under src/main?
I'd appreciate that the install and run instructions would be both for how to do it through Android Studio and using the command line (if you only know one of them post it anyway please).
Note: this is the first time I'm using Android Studio
Thanks in advance.
EDIT:
Right now I can build and run but it tells me I have no tests to run (empty test suite). Here are my graddle and my code.
My build.graddle is as follows:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "androidexp.com.ceninhas"
minSdkVersion 21
targetSdkVersion 22
versionCode 1
versionName "1.0"
testInstrumentationRunner="android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0'
}
My source code (under src/androidTest/java/package) is:
#RunWith(AndroidJUnit4.class)
public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> {
public final static String ACTIVITY_NAME = "com.calculator.Main";
public final static Class<?> autActivityClass;
static {
try {
autActivityClass = Class.forName(ACTIVITY_NAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public ApplicationTest(){
super((Class<Activity>)autActivityClass);
}
#Before
public void setUp() throws Exception{
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
}
#After
public void tearDown() throws Exception{
super.tearDown();
}
#Test
public void cenas(){
assertTrue(true);
}
}
The run log on the console was:
Testing started at 18:06 ...
Waiting for device.
Target device: lge-nexus_5-08e506c10ddef123
Uploading file
local path: C:\Users\Ines\workspace\Ceninhas\app\build\outputs\apk\app-debug.apk
remote path: /data/local/tmp/androidexp.com.ceninhas
No apk changes detected. Skipping file upload, force stopping package instead.
DEVICE SHELL COMMAND: am force-stop androidexp.com.ceninhas
Uploading file
local path: C:\Users\Ines\workspace\Ceninhas\app\build\outputs\apk\app-debug-androidTest-unaligned.apk
remote path: /data/local/tmp/androidexp.com.ceninhas.test
No apk changes detected. Skipping file upload, force stopping package instead.
DEVICE SHELL COMMAND: am force-stop androidexp.com.ceninhas.test
Running tests
Test running startedFinish
Empty test suite.
What am I doing wrong?
I am also using uiautomator 2.0 from AndroidStudio. Here are some answers to your questions.
How do I install this in the device?
How do I run it in the device?
Make sure your device is connected using
adb devices
if not, you must connect it using
adb kill-server
adb connect xxx.xxx.xxx.xxx
Then from AndroidStudio, right click on your test class and click on "Run YourTestCase".
Do I need to do anything in the AndroidManifest?
I have nothing special in my manifest, but be sure you add
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
in your build.gradle
Am I editing in the right place? Should I do anything under src/main?
Yes, you are editing at the right place. But you can move your code to src/main. To do so, you will need to change androidTestCompile to compile in your build.gradle file.
I did not try to run test from command line yet, but you can see AndroidStudio commands, maybe it can help.
I hope it helped you.
EDIT 1
I use this code
build.gradle (projectRoot)
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.0"
lintOptions {
abortOnError false
}
packagingOptions {
exclude 'NOTICE'
exclude 'LICENSE.txt'
}
defaultConfig {
minSdkVersion 19
targetSdkVersion 22
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.android.support.test:testing-support-lib:0.1'
compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0'
compile project(':aiccore')
}
LoginTestCase (projectRoot/src/main/LoginTestCase.java)
public class LoginTestCase extends InstrumentationTestCase {
protected UiDevice device = null;
protected String appName;
public LoginTestCase() {
this("YourAppName")
}
public LoginTestCase(String appName) {
this.appName = appName;
}
public void runApp(String appName) throws UiObjectNotFoundException, RemoteException {
device = UiDevice.getInstance(getInstrumentation());
device.pressHome();
device.waitForWindowUpdate("", 2000);
UiObject2 allAppsButton = device.findObject(By.desc("Apps"));
allAppsButton.click();
device.waitForWindowUpdate("", 2000);
UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true));
appViews.setAsHorizontalList();
UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName);
settingsApp.clickAndWaitForNewWindow();
assertTrue("Unable to detect app", settingsApp != null);
}
#Override
public void setUp() throws RemoteException, UiObjectNotFoundException {
this.runApp(appName);
}
#Override
public void tearDown() throws RemoteException, UiObjectNotFoundException {
//Empty for the moment
}
public void testUS1() {
UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username"));
assertTrue("Username label not found", usernameLabel != null);
}
Well, actually, you should not write test code that way. Just keep your code under the src/androidTest folder, and write test code like this:
#RunWith(AndroidJUnit4.class)
#SdkSuppress(minSdkVersion = 18)
public class ChangeTextBehaviorTest {
private static final String BASIC_SAMPLE_PACKAGE
= "com.example.android.testing.uiautomator.BasicSample";
private static final int LAUNCH_TIMEOUT = 5000;
private static final String STRING_TO_BE_TYPED = "UiAutomator";
private UiDevice mDevice;
#Before
public void startMainActivityFromHomeScreen() {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Start from the home screen
mDevice.pressHome();
// Wait for launcher
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
// Launch the app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
// Clear out any previous instances
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
// Wait for the app to appear
mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
LAUNCH_TIMEOUT);
}
#Test
public void checkPreconditions() {
assertThat(mDevice, notNullValue());
}
#Test
public void testChangeText_sameActivity() {
// Type text and then press the button.
mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput"))
.setText(STRING_TO_BE_TYPED);
mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt"))
.click();
// Verify the test is displayed in the Ui
UiObject2 changedText = mDevice
.wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")),
500 /* wait 500ms */);
assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED)));
}
}
For detail please look out: UIAutomator Test sample