I have commented a few lines of code out in this function as I'm not sure what their purpose is. However when I run my android application everything work perfectly... so i assume I do not need them and they serve no purpose in my project.
private void deleteRoutine() {
myDb.deleteRoutineForCurrentDay(currentDay);
Intent intent = getIntent();
//intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//finish();
//overridePendingTransition(0, 0);
startActivity(intent);
MediaPlayer mymedia = MediaPlayer.create(MondayRoutineEdit.this, R.raw.clearroutine);
mymedia.start();
}
}
public void deleteRoutineForCurrentDay(String selectedDay)
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + RoutineTable + " WHERE DayOfWeek ='" + selectedDay + "'");
}
//intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
Here's what Intent says:-
If set in an Intent passed to Context.startActivity(), this flag will
prevent the system from applying an activity transition animation to
go to the next activity state.
You may wish to have a look at this Android - How to stop animation between activity changes.
I'd suggest that in normal circumstances omitting this is not an issue. However, the decision could depend upon how you cam about coding the above. If you basically copied an App, then there is likely good reason why the codes was used. if you are copying part of the code then the it could well be best to omit.
//finish();
If you use the above it will remove the activity from the stack, which could cause you issues e.g. using the back button WILL NOT take you back to this activity (as it now doesn't exist on the stack) and could be confusing to the end user. If you basically copied the entire App then it may have been included for a good reason. If you just copied the block of code or based your code on seeing this, then you would probably want to omit this.
You may wish to have a look at finish, along with the rest of Activity.
//overridePendingTransition(0, 0); this is discussed in the Android - How to stop animation between activity changes. link above. You may also wish to have a look at overridePendingTransition.
Whether to omit or not is basically the same and perhaps dependent upon the source of the code.
Related
I'm newbie and I need help I can't resolve problem i don't know what to do. Very confusing it and need help (if you explain about it i'm very very thank you).
I watching Kotlin Project - Kotlin Android Instagram Clone using Firebase - Kotlin Instagram Clone
He using ArthurHub/Android-Image-Cropper (but it is old version right ?), I find some new version is CanHub/Android-Image-Cropper.
CropImage.activity()
.setAspectRatio(1,1)
.start(this#AccountSettingsActivity)
I can't use this code and i don't know how to resolve this problem, be utterly mystified.
Help me please Thank you very much.
Best regards.
(you can blame me, but not harsh i'm Newbie and I don't know)
I need help I can't resolve problem i don't know what to do. Very confusing it and need help
Since you said you're new I'll help you understand what the project page's example usage is showing you. I can only do this in general, I don't have time to go actually creating an example project to test it myself.
If you run into any issues, you'll have to puzzle it out - that's a big part of coding! It's rare that you'll get a nice simple solution that drops neatly into whatever you're doing, and learning how to make it work for you is an important skill to develop.
If you're ever stuck, always look at the project page (in this case the Github page) for a user guide, and they have a sample project in the repository too, so you can see how it works inside a full app. Don't be afraid to look at it, even if you don't understand it all - the more you do this the more you'll understand
Anyway, here are their examples:
Calling crop directly
class MainActivity {
private val cropImage = registerForActivityResult(CropImageContract()) { result ->
if (result.isSuccessful) {
// Use the returned uri.
val uriContent = result.uriContent
val uriFilePath = result.getUriFilePath(context) // optional usage
} else {
// An error occurred.
val exception = result.error
}
}
I'm going to break the code up here - this first bit is showing you're doing this inside an Activity. You're creating a cropImage object, which is an Activity launcher provided by registerForActivityResult - you're going to call launch on that later to start your cropping Activity.
The lambda in the curly braces is the function that's going to run when you get a result back - this is where you actually do something with the cropped image. In this case they're getting URIs to the image - I don't know what you need, but you can google "get bitmap from URI" or whatever if you need something else.
This whole getResultFromActivity thing is part of the AndroidX Activity and Fragment libraries - if you want to do it this way, you'll need those (and it's a good idea to use them on every project anyway, AndroidX stuff gives you backwards compatibility and saves you work).
Once you've set that up, you can call launch on cropImage to open your cropping Activity. It looks like they're giving you three examples, with different options (you could combine the options, but you only call launch once):
private fun startCrop() {
// Start picker to get image for cropping and then use the image in cropping activity.
cropImage.launch(
options {
setGuidelines(Guidelines.ON)
}
)
They're putting these in a startCrop() function you can call from, say, a button click listener. This one's setting some guideline options on the launched Activity - and like the comment says, it opens an image picker so the user can select an image.
// Start picker to get image for cropping from only gallery and then use the image in cropping activity.
cropImage.launch(
options {
setImagePickerContractOptions(
PickImageContractOptions(includeGallery = true, includeCamera = false)
)
}
)
This one (again, like the comment says - this stuff is there to help you) is setting some options on the picker instead, specifically limiting the choice to gallery images.
// Start cropping activity for pre-acquired image saved on the device and customize settings.
cropImage.launch(
options(uri = imageUri) {
setGuidelines(Guidelines.ON)
setOutputCompressFormat(CompressFormat.PNG)
}
)
This one does a few things: passes the URI of an image to crop (instead of opening a picker for the user to choose), adds guidelines, and sets the output format for the resulting cropped image.
Remember, these are all examples of the different ways you might use this. You can combine options, depending on how you want to configure things - you're setting options before you launch the cropping Activity.
Using CropView
This one looks like it uses a custom View you can add to a layout, which lets you crop an image:
// Add CropImageView into your activity
<!-- Image Cropper fill the remaining available height -->
<com.canhub.cropper.CropImageView
android:id="#+id/cropImageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
So you add this to your Activity's layout (might work on Fragments too, maybe with some tweaking - I'm not testing it remember!). The sizing isn't important - you can work out how to make a view as big as you want it to be. It's just a normal View in a layout.
//Set image to crop
cropImageView.setImageUriAsync(uri)
// Or prefer using uri for performance and better user experience.
cropImageView.setImageBitmap(bitmap)
In the Activity, with a reference to the CropImageView in your layout, you call this set image function with the URI of an image you want to use. Or, if you have it, you can set a Bitmap directly. Once it's set on the CropImageView, the user can adjust it
// Subscribe to async event using cropImageView.setOnCropImageCompleteListener(listener)
cropImageView.getCroppedImageAsync()
// Or.
val cropped: Bitmap = cropImageView.getCroppedImage()
Now this one's a bit trickier - to me, it's not completely obvious how you're supposed to use that first one. So let's actually look at the code in CropImageView, where we can see how it works and read the documentation.
Surprise! There is no getCroppedImageAsync() function, just a croppedImageAsync one (without the get) that looks like it does the same thing. That's fine. If you're using an IDE like Android Studio, it'll probably suggest the right function as you type, and you can read the documentation right there:
* Cropped image based on the current crop window to the given uri.
* The result will be invoked to listener set by [setOnCropImageCompleteListener].
Ok, that looks like what the example is hinting at. You call setOnCropImageCompleteListener with a function to do something with the resulting image, like this:
cropImageView.setOnCropImageCompleteListener { view, result ->
// do something with cropped result
}
and then you call croppedImageAsync (with whatever option parameters you want, check the docs) to start the crop-and-store process. When it's done, that callback function you just set will be called with the result.
And then there's the custom Activity example but that's enough for me - if you really want that, if you can follow what we've gone over so far you should be able to work out the rest.
Since you're already making an app following a tutorial, and it's using a different library (with a different way of doing things) you'll have to work out how to fit this library into your own project. Take a step back and look at what you're doing in the tutorial, what you're trying to achieve (like launching a cropping Activity), and work out how you'd achieve the same task in this library.
A lot of software development is about trying to fit different pieces together like this, and it rarely goes smoothly. Not knowing what you're doing is normal! But then you have to sit down and work it out. Hopefully that gives you an idea of an approach you can take to learning - and there is a lot to learn at first!
I'm programming an app using android studio. I want to know in which way I can do a tutorial that users will see only the first time that use the app. Tutorial like image or screenshoots
Can someone help me? Thanks
I encountered this thread while looking for a solution for running a tutorial only at the first time (as rbaleksandar suggested), so in case it will be helpful for someone someday, here's a template of a solution that works for me (using the SharedPreferences API):
#Override
protected void onResume() {
super.onResume();
String tutorialKey = "SOME_KEY";
Boolean firstTime = getPreferences(MODE_PRIVATE).getBoolean(tutorialKey, true);
if (firstTime) {
runTutorial(); // here you do what you want to do - an activity tutorial in my case
getPreferences(MODE_PRIVATE).edit().putBoolean(tutorialKey, false).apply();
}
}
EDIT - BONUS - If you're into app tutorial - I'm messing now with the ShowcaseView library (which is amazing - try it out). Apparently they have some shortcut for that issue using a method called singleShot(long) - its input is a key for the SharedPreferences, and it does the exact same thing - runs only in the first activation. Example of usage (taken from here):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_shot);
Target viewTarget = new ViewTarget(R.id.button, this);
new ShowcaseView.Builder(this)
.setTarget(viewTarget)
.setContentTitle(R.string.title_single_shot)
.setContentText(R.string.R_string_desc_single_shot)
.singleShot(42)
.build();
}
You could always code your own solution, but, let us not reinvent the wheel.
Check this Android Library:
Tour Guide Repository
It allows you to add pointers in your screen, so the user knows where is he supposed to touch next.
It's pretty easy to use, you only need to point to the element you want the user to touch.
From the doc:
Let's say you have a button like this where you want user to click on:
Button button = (Button)findViewById(R.id.button);
You can add the tutorial pointer on top of it by:
TourGuide mTourGuideHandler = TourGuide.init(this).with(TourGuide.Technique.Click)
.setPointer(new Pointer())
.setToolTip(new ToolTip().setTitle("Welcome!").setDescription("Click on Get Started to begin..."))
.setOverlay(new Overlay())
.playOn(button);
Hope this helps!
Some links to libraries for creating introduction and/or tutorial screens.
Horizontal cards like Google Now:
https://github.com/PaoloRotolo/AppIntro
Tutorial screen:
https://github.com/amlcurran/ShowcaseView
As far as I understand the question is not How do I create a tutorial? (as the people who have already posted an answer have concluded) but instead How to show a tutorial upon first launch only?. So here are my two cents on this topic:
I'm not familiar with how your Android app stores its configuration data but I will assume that it's either in a database (SQLite) or a text file (plaintext, YAML, XML - whatever). Add a configuration entry to wherever the app's settings are being stored - something like tutorial_on : false, tutorial_on : 1 etc. depending on the format the configuration is represented in.
The way configurations work is that whenever an app (or software in general) is launched it has to be loaded in the app itself. So add the following to your app (where and how is up to you and your app design):
Check tutorial_on entry
If tutorial_on is set to true/1 whatever
2.1 Display tutorial
2.2 Change tutorial_on to false/0 whatever
2.3 Store the result in your configuration
Continue using the app
By doing so the first time your app launches the flag responsible for displaying the tutorial will be toggled and afterwards every time you start the app the toggle flag will be read leading to omitting the tutorial.
Personally I would suggest that you an option similar to Don't show tutorial anymore along with a description how to re-enable it (by triggering some action in that app's menu etc.). This has two major benefits:
Improved user experience - users like to have control (especially over trivial matters such as showing or hiding a tutorial). Whenever you take the control away from them, they get pissed off.
Enable your user to re-learn forgotten things - a general rule of thumb is to create apps that should not burden the user with a lot of stuff to remember. That is why things should be self-explanatory. However sometimes you may want to do that nonetheless. By adding the possibility that the user re-launches (by simply resetting the tutorial_on flag and repeating the steps from above) the tutorial allows just that - refreshing a user's memory.
My program consists of a MainActivity and two fragment activities. I need one fragment to take a String value from the user and pass it to the second fragment.
I am trying to wrap my head around how to do this. Since I am familiar with intents, I found this answer on another post and decided to try it out. Everything looks fine until I get to step 4, when I try to use Intent i = getIntent(); in my second fragment, Studio won't let me use it and says "getIntent(java.lang.String) is deprecated".
This doesn't make sense to me since I have used getIntent() in other programs without issue, and it is letting me use it in my MainActivity (step 2 from the other post) without screaming at me.
I know this can be done without using intents, but I can't figure it out and can't find any really thorough tutorials in order to do so. So I guess my questions are:
Can I make intents work for this purpose still? What should I do to get around this deprecation issue?
Any other advice, explanations, or links to "explain it like I'm 5" tutorials would be very helpful and welcome. I have Googled and read a few, but I am still not understanding this and am becoming increasingly frustrated. It seems like this should be a relatively simple concept.
It is too late for answer but still I am providing my answer for other persons. It is happen because Intent is basically work with an activity. And fragments are not activity, but attached to activity. So simply you need to do this:
Intent intent=getActivity().getIntent();
Having the same problem while passing Object from an Activity to a Java Class.
Here is what I did
This Activity sends data
Salary newSalary = new Salary();
Intent intent = new Intent(ViewData.this,Data.class);
intent.putExtra("SalaryObj", newSalary);
It recieves data(In Data.class)
Here I tried this but Android Studio says getIntent is deprecatedIntent intent = Intent.getIntent();
So What can I use in place of getIntent(), because all the solutions I find on Internet to this problem, uses getIntent().
EDIT:
I was playing around with this and found that I was trying to receive data in Java Class(Not an Activity). But when I used it in an Activity then it works fine. But it takes me to another question that how to send data from an Activity to Java Class(which is not an Activity).
On your onCreate
val bundle = intent.extras
if (bundle != null) {
idEmployee = bundle?.getString("idEmployee", "")
idClient = bundle?.getString("idClient", "")
listAvailable = bundle?.getStringArrayList("listAvailable") as ArrayList<String>
Log.i("list:", "$listAvailable" )
}
It means, that this method could not be supported in further releases. The method is still in the API for backward compability for an unspecified amount of time. Mostly it is dangerous to use deprecated methods or there is a better way to achieve this.
Like it is described here
In this case you should rather use: parseUri(String, int) to achieve this ( according to the android developer api).
I'm getting data from a server for my app. The "getData" functions are included in the app's main Activity, in a splash thread. The problem I'm having is this:
If I quickly enter news or description after loading up the app, I notice that not all info has loaded (last 2 or 3 strings that needed to be saved are null). If, however, I allow the app a few more seconds after displaying the main menu (after completing the splash thread), the problem doesn't occur, all info is stored correctly on the phone. I tried delaying the splash screen by a few seconds but that's not really an elegant solution nor does it always work.
My question is how can I make sure that the functions have been completed before it jumps to "finally"
I'm not storing the data in any database, just in public static string arrays in another class.
You have my code below:
if(networkAvailable()){
Thread splashTread = new Thread() {
#Override
public void run() {
try {
getData.execute(description_Hyperlinks);
getNews.execute(new String[]{newsJSON_Hyperlink});
getOffers.execute(new String[]{offersJSON_Hyperlink});
for(int i = 0; i<3; i++)
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
finish();
startActivity(new Intent(FlexFormActivity.this, MainMenu.class));
stop();
}
}
};
splashTread.start();
For the purpose of making the discussion in the comments on the initial question more readable and physically visible
It would be a better idea to use the Android build-in support for asynchronous task-handling in form of the AsyncTask-class. This allows you to "hook in" the task, giving you the opportunity to react on the different stages of the progress.
The idea would be to not make getData, getNews and getOffers each extend AsyncTask, but to rather have a single task (called e.g. "LoadContents"), which loads the data, the news and the offers one after another.
It would then be possible to determine, when the whole initial work has been done, which makes it easy to react on this "completion of task", in whatever form you can imagine.
As a little code-review, It should normally never be necessary to use the Thread-class itself, as Java and Android provide many wrappers around it (in particular the Java Executor Framework), which should be favored in order to produce more clean and reliable code.
Also, as a general advice on "disabling the back-button" (which is used by #Eugen to ensure that the splash-screen stays present): Don't do it. It's not the kind of behavior a user expects when he uses an application.
Imagine someone has accedently opened an app, which takes ~10 seconds for the initial loading of contents, and this process can't be canceled. The user will have to wait the entire time, only to then leave the app without using it.
Therefore, you should not "deactivate" the back-button, but rather make your task (and therefore the initial loading of your application) "cancel-able". When using an AsyncTask, this is already implemented for you.
We are building a complex Android application consisting of many screens and workflows spread across many Activities. Our workflows are similar to what you might see on a Bank's ATM machine, for example, there is an Activity to login in that transitions to a main menu Activity which can transition to other activities based on the user's choices.
Since we have so many workflows we need to create automated tests that span multiple activities so we can test a workflow from end to end. For example, using the ATM example, we would want to enter a valid PIN, verify that sends us to the main menu, choose withdraw cash, verify that we are on the withdraw cash screen, etc., etc., and eventually find ourselves back on the main menu or "logged" out.
We've toyed with the test APIs that come with Android (e.g. ActivityInstrumentationTestCase2) and also with Positron, but neither seem capable of testing beyond the bounds of a single Activity, and while we can find some utility in these tools for some unit testing, they won't meet our needs for testing scenarios that cut across multiple Activities.
We are open to an xUnit framework, scripting, GUI recorders/playbacks, etc. and would appreciate any advice.
I feel a bit awkward about answering my own bounty question, but here it is...
I've searched high and low on this and can't believe there is no answer published anywhere. I have come very close. I can definitely run tests that span activities now, but my implementation seems to have some timing issues where the tests don't always pass reliably. This is the only example that I know of that tests across multiple activities successfully. Hopefully my extraction and anonymizing of it did not introduce errors. This is a simplistic test where I type a username and password into a login activity, and then observe a proper welcome message is shown on a different "welcome" activity:
package com.mycompany;
import android.app.*;
import android.content.*;
import android.test.*;
import android.test.suitebuilder.annotation.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import static org.hamcrest.core.Is.*;
import static org.hamcrest.core.IsNull.*;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.*;
import static com.mycompany.R.id.*;
public class LoginTests extends InstrumentationTestCase {
#MediumTest
public void testAValidUserCanLogIn() {
Instrumentation instrumentation = getInstrumentation();
// Register we are interested in the authentication activiry...
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(AuthenticateActivity.class.getName(), null, false);
// Start the authentication activity as the first activity...
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), AuthenticateActivity.class.getName());
instrumentation.startActivitySync(intent);
// Wait for it to start...
Activity currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);
assertThat(currentActivity, is(notNullValue()));
// Type into the username field...
View currentView = currentActivity.findViewById(username_field);
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(EditText.class));
TouchUtils.clickView(this, currentView);
instrumentation.sendStringSync("MyUsername");
// Type into the password field...
currentView = currentActivity.findViewById(password_field);
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(EditText.class));
TouchUtils.clickView(this, currentView);
instrumentation.sendStringSync("MyPassword");
// Register we are interested in the welcome activity...
// this has to be done before we do something that will send us to that
// activity...
instrumentation.removeMonitor(monitor);
monitor = instrumentation.addMonitor(WelcomeActivity.class.getName(), null, false);
// Click the login button...
currentView = currentActivity.findViewById(login_button;
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(Button.class));
TouchUtils.clickView(this, currentView);
// Wait for the welcome page to start...
currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);
assertThat(currentActivity, is(notNullValue()));
// Make sure we are logged in...
currentView = currentActivity.findViewById(welcome_message);
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(TextView.class));
assertThat(((TextView)currentView).getText().toString(), is("Welcome, MyUsername!"));
}
}
This code is obviously not very readable. I have actually extracted it into a simple library with an English-like API so I can just say things like this:
type("myUsername").intoThe(username_field);
click(login_button);
I've tested to a depth of about 4 activities and am satisfied that the approach works though as I said, there appears to be an occasional timing issue I have not completely figured out. I am still interested in hearing of any other ways of testing across activities.
Take a look at Robotium
'a open-source test framework created to make automatic black-box testing of Android applications significantly faster and easier than what is possible with Android instrumentation tests out-of-the-box.'
Homepage:
http://www.robotium.org/
Source:
http://github.com/jayway/robotium
Please note that the Robotium project is maintained by the company I work for
You could always use Robotium. It supports blackbox testing just like Selenium but for Android. You will find it at Robotium.org
I'm surprised no one has mentioned some of the leading automated functional testing tools. Compared with Robotium, these don't require writing Java code.
MonkeyTalk: an open-source tool backed by the company Gorilla Logic. Pros: provides recording as well as a higher-level scripting language easier for non-technical users, and is cross-platform (includes iOS). Given those benefits as requirements, we've found this to be the best solution. It also allows customization beyond what can be done in their scripting language using Javascript.
Calabash-Android: an open-source tool for Cucumber-style features. Pros: write features in the Gherkin language which is Business Readable, Domain Specific Language that lets you describe software’s behavior without detailing how that behavior is implemented. Similar but not exact support is available for iOS in cucumber-ios. Recording capabilities are not as good, as they produce a binary output.
A couple of other references:
Here are some additional comparisons between Robotium,
Monkeytalk and Calabash. It mentions TestDroid as another
possibility.
This blog mentions the above plus NativeDriver and Bot-bot.
I created a record-and-playback tool for Android and made it available on GitHub. It's easy to configure and use, requires no programming, runs against real devices (which do not have to be rooted) and automatically saves screenshots as it plays tests.
First of all, use 'ActivityInstrumentationTestCase2', not 'InstrumentationTestCase', as your base class. I use Robotium and routinely test across multiple Activities. I found that I have to specify the login activity as the generic type (and class argument to the constructor).
The 'ActivityInstrumentationTestCase2' constructor ignores the package argument and does not require it. The constructor that takes the package is deprecated.
From the Javadocs:
"ActivityInstrumentationTestCase2(String pkg, Class activityClass)
This constructor is deprecated. use ActivityInstrumentationTestCase2(Class) instead"
Using the recommended base class allows the framework to handle certain boilerplate, like starting your activity. That's done by the call to 'getActivity()', if necessary.
Found this useful with a couple of modifications.
Firstly getInstrumentation().waitForIdleSync() will cure the flakiness SingleShot speaks of
and also InstrumentationTestCase has a lauchActivity function that can replace the start activity lines.
you can do it like this to avoid the flake waiting times out of sync :
final Button btnLogin = (Button) getActivity().findViewById(R.id.button);
Instrumentation instrumentation = getInstrumentation();
// Register we are interested in the authentication activity...
Instrumentation.ActivityMonitor aMonitor =
instrumentation.addMonitor(mynextActivity.class.getName(), null, false);
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
btnLogin.performClick();
}
});
getInstrumentation().waitForIdleSync();
//check if we got at least one hit on the new activity
assertTrue(getInstrumentation().checkMonitorHit(aMonitor, 1));
I'm working on pretty much the same thing, and I'll probably go with a variation on the accepted answer to this question, but I did come across Calculuon (gitHub) during my searches for a solution.
I haven't personally used it, but ApplicationTestCase looks like it might be what you're looking for.
Will accepted approach work with different Activities from different Applications, signed by different certificates? If not, Robotium the best way to test activities within same application.
There is another way to do the multiple activity using ActivityInstrumentation Class..
Its a normal automation scenario...
First get the focus of what ever object you want and then send a key
Simple as that
sample code
button.requestFocus();
sendKeys(KeyEvent.KEYCODE_ENTER);
Only thing is understanding the every API calls will help us.
This answer is based on the accepted answer but modified to solve the timing issue which for me became consistent after adding about a half dozen tests. #pajato1 gets the credit for solving the timing issue, as cited in the accepted answer comments.
/**
* Creates a test Activity for a given fully qualified test class name.
*
* #param fullyQualifiedClassName The fully qualified name of test activity class.
*
* #return The test activity object or null if it could not be located.
*/
protected AbstractTestActivity getTestActivity(final String fullyQualifiedClassName) {
AbstractTestActivity result = null;
// Register our interest in the given activity and start it.
Log.d(TAG, String.format("Running test (%s) with main class: %s.", getName(), fullyQualifiedClassName));
instrumentation = getInstrumentation();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), fullyQualifiedClassName);
// Wait for the activity to finish starting
Activity activity = instrumentation.startActivitySync(intent);
// Perform basic sanity checks.
assertTrue("The activity is null! Aborting.", activity != null);
String format = "The test activity is of the wrong type (%s).";
assertTrue(String.format(format, activity.getClass().getName()), activity.getClass().getName().equals(fullyQualifiedClassName));
result = (AbstractTestActivity) activity;
return result;
}
Try the Monkey tool testing
Step 1:
open the android studio terminal(Tools-> open terminal)
Step 2:
In order to use monkey , open up a command prompt and just naviagte to the following directory.
export PATH=$PATH:/home/adt-bundle-linux-x86-20140702/sdk/platform-tools
Step 3:
add this monkey command into terminal and press enter..
see the magic in your emulator.
adb shell monkey -p com.example.yourpackage -v 500
500- it is the frequency count or the number of events to be sent for testing.
you can change this count..
More reference,
http://www.tutorialspoint.com/android/android_testing.htm
http://androidtesting.blogspot.in/2012/04/android-testing-with-monkey-tool.html