ParseUI activity code is not working - android

I am trying to get ParseUI to work with my app.
I have imported the libs, sync with gradle and everything is workign fine. Till when I actually put the code for the activity to be initiated, I get error saying 'cannot resolve symbol build'.
public class Login_activity extends FragmentActivity //implements Validator.ValidationListener
{
ParseLoginBuilder builder = new ParseLoginBuilder(Login_activity.this);
Login_activity(builder.build(), 0);
Actual code that I am supposed to use according to Parse docs
ParseLoginBuilder builder = new ParseLoginBuilder(MyActivity.this);
startActivityForResult(builder.build(), 0);
EDIT:
This is the updated code
#Override
protected void onCreate(Bundle savedInstanceState) {
//
//super.onCreate(savedInstanceState);
ParseLoginBuilder builder = new ParseLoginBuilder(Login_activity.this);
startActivityForResult(builder.build(), 0);
}

This line
Login_activity(builder.build(), 0);
is not valid Java. Your are trying to call the name of the class as if it was a method. I am not sure what you are trying to do (invoke the constructor? - which would not make sense for an Activity), but this code is incorrect. If you meant to call startActivityForResult, then do so, instead of substituting startActivityForResult with your class name, because doing so makes no sense.
EDIT:
Furthermore, you are adding lines of code to be executed directly in the class body, as opposed to inside a method. In Java, a class body can only contain declarations (which may include statements as part of an assignment) or static blocks of code, all other code must be part of a method.
class MyClass {
... you can only have declarations and assignments here
public void someMethod() {
... actual code statements here
}
}

Related

How do I mock a class with expresso in android?

Hello I am struggling with a task that seems very simple. I need to write an expresso unit test but I need the activity to use a mocked class instead of the one it uses during the normal run.
the, the closest solution I saw was here:
Nullifying or overriding API calls made in an Activity under an Espresso test
But this requires getters and setters at the application level and only deals with constants.
Here is a simple example of want to do:
Activity:
public class MainActivity2 extends AppCompatActivity {
// how do I mock this without using any branches
// just have expresso replace with MainActivity2CustomClass with a mock?
private MainActivity2CustomClass mainActivity2CustomClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mainActivity2CustomClass = new MainActivity2CustomClass();
mainActivity2CustomClass.foo();
}
}
the class I want to mock
// Need expresso to replace this class with a mock
public class MainActivity2CustomClass {
void foo() {
}
}
To clarify I need to do this with a large application with several classes. So using branches is NOT the solution I seek. For instance this will not work for my application
// I DO ***NOT** WANT THIS solution since it will explode in many branches in my application
Intent intent = new Intent(targetContext, PatientActivity.class);
intent.putExtra("istestrunning", 2);
// etc...
// Not acceptable solution for my problem, creates too many branches and messy code
if (getIntent().getIntExtra("istestrunning", 0) == 2) {
mainActivity2CustomClass = new MainActivity2CustomClass();
mainActivity2CustomClass.foo();
} else {
mainActivity2CustomClass2 = new MyMock();
mainActivity2CustomClass2.foo();
}
I want to know if it possible to have expresso simply replace that class at testing time. Can it be done?
Any help or leads is appreciated.
thank you.

How do I abstract away dependencies in Android library code?

Here is my scenario.
I have an android activity in which I want to abstract my I/O dependencies. The dependencies are represented by this interface (edited for brevity and simplicity):
public interface ITimeDataServer {
TimeRecord[] get(int userID);
void save(TimeRecord record);
}
What I want is for my activity to be able to call these interface methods, and leave the implementation to be supplied by the calling code. (Pretty standard, I think).
ITimeDataServer myServer;
int myUserID;
void loadRecords() {
TimeRecord[] records = myServer.get(myUserID);
// etc...
}
My difficulty is, how can I ensure that myServer gets set?
This seems like a common problem, but I can't find a clean solution.
My first thought would be that myServer would be passed in through the constructor, but Android activities aren't really instantiated with constructors.
I've come up with several solutions, but they're all icky in some way:
Icky Solution 1
Create a static method to launch the activity class which takes an ITimeDataServer parameter and stores it in a static variable from which the activity can access it:
private static ITimeDataSource theDataSource;
public static void launch(Activity currentActivity, ITimeDataSource dataSource) {
theDataSource = dataSource;
Intent intent = new Intent(currentActivity, MainActivity.class);
currentActivity.startActivity(intent);
}
This is icky because (a) the data source is static and not actually associated with the instance, and (b) a consumer could initiate the activity by the standard activity API rather than this static method, which will cause NullPointerException.
Icky Solution 2
I can create a Provider class which provides a singleton instance of ITimeDataSource, which needs to be initialized by the calling library before use:
public class TimeDataSourceProvider {
private static ITimeDataSource myDataSource = null;
public void initialize(ITimeDataSource dataSource) {
myDataSource = dataSource;
}
public ITimeDataSource get() {
if (myDataSource == null)
throw new NullPointerException("TimeDataSourceProvider.initialize() must be called before .get() can be used.");
else
return myDataSource;
}
}
This seems a little less icky, but it's still a little icky because the activity's dependency is not obvious, and since there may be many paths to launch it, it's highly possible that some of them would forget to call TimeDataSourceProvider.initialize().
Icky solution 3
As a variation on #2, create a static IODependencyProvider class which must be initialized with ALL dependencies on app startup.
public class IODependencyProvider {
static ITimeDataSource myTimeData;
static IScheduleDataSource myScheduleData; // etc
public static void initialize(ITimeDataSource timeData, IScheduleDataSource scheduleData /* etc */) {
myTimeData = timeData;
myScheduleData = scheduleData;
//etc
}
public static ITimeDataSource getTimeData() {
if (myTimeData == null)
throw new NullPointerException("IODependencyProvider.initialize() must be called before the getX() methods can be used.");
else
return myTimeData;
}
// getScheduleData(), etc
}
This seems superior to #1 and #2 since a failure to initialize would be much harder to sneak by, but it also creates interdependencies among the data types that otherwise need not exist.
...and other icky variations on that theme.
The common themes that make these solutions crappy:
the need to use static fields to pass non-serializable information to an activity
the lack of ability to enforce initialization of those static fields (and subsequent haphazardness)
inability to clearly identify an activity's dependencies (due to reliance on statics)
What's a nooby Android developer to do?
As long as these dependencies implement Parcelable correctly, you should be able to add them to your intent, then unparcel them as ITimeDataServer and get the correct class.
I found a nice solution here, in the least-loved answer.
I define the library activity as abstract and with no default constructor, but a constructor that takes an interface, like so:
public abstract class TimeActivity extends AppCompatActivity {
private ITimeDataSource myTimeDataSource;
public TimeActivity(#NonNull ITimeDataSource dataSource) {
myTimeDataSource = dataSource;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
// do stuff with myTimeDataSource!
}
}
Then, the calling code can create a concrete subclass with its chosen implementation that does have a parameterless constructor. No static members, easy-peasy!
This allows you to abstract and inject all sorts of crazy behaviours! Woooo!
(Note that the concrete subclass activity needs to be manually added to AndroidManifest.xml, like all activities, or the app will crash when it tries to launch.)

What is the data type of 'MyActivity.this' - Android

well my question is that there aren't pointers in JAVA ...
but when we have to start another activity we do like this :
Intent in = new Intent(MyActivity.this, NewActivity.class);
startAcitivity(in);
So my question is that what is the data type of MyActivity.this ??
In java pointers are not explicitly allowed,
However passing by reference(object) in Java is something which is implicitly based on pointer concept.
In your case, you are passing the context of parent class to child class,
which is actually passing by reference concept.
Hope this helps.
Writing MyActivity.this is the same as writing this, if you are in a non-nested class, or to top-level class.
See this example:
public class TopLevel{
public static void main(String[] args){
new TopLevel().printClass();
}
public TopLevel(){
new LowerLevel().printClass();
}
public void printClass(){
System.out.println("Outer Class: ");
// Will print something like "TopLevel.class"
System.out.println(this.getClass());
}
public class LowerLevel{
// This is a Nested-Class.
public void printClass(){
System.out.println("Nested Class: ");
// Will print "TopLevel$LowerLevel.class"
System.out.println(this.getClass());
// Will print "TopLevel.class" again
System.out.println(TopLevel.this.getClass());
}
}
}
Some using this in the nested-class does not reference to the same instance as when using it in the top-level class. Therefor, to get the "context" of the outer class in your nested class, you also specify the class you want the this-context from.

call static void

How do I call my function?
public static void dial(Activity call)
{
Intent intent = new Intent(Intent.ACTION_DIAL);
call.startActivity(intent);
}
Obviously not with:
dial(); /*Something should be within the brackets*/
You should try
ClassName.dial();
The reason is that static methods belong the class itself, not to an individual instance of it. The call to instance.dial() is legal, but discouraged.
you should use your ClassName.StaticMethod.... to call a static method of a class
You can't pass null. You have to send a context object.
Where is your function located? If it's inside an Activity or the such, simply pass "this" as the parameter.
If it's inside an BroadcastListener, or a Service, just change the parameter to Context and pass "this".
What exaclty is the Problem?
If you've got a class like
public class Test {
public void nonStaticFct() {
staticFct();
}
public static void staticFct() {
//do something
}
}
Works perfectly (even if you should call static functions always by Classname.FctName (Test.staticFct())
I guess the problem here is the missing argument.
[Edit] Obviously I am wrong, according to the Java Code Conventions you may use a Classmethod by simply calling it, without using the classname (even if it seems odd, since I would expect an implicit this.staticFct() - but possibly the Java compiler is smart enough)

Noob question about "Hello World" Android tutorial

Just getting started with Android development and Java. So, here's the code I'm working with:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
What is the purpose of declaring the onCreate() method here:
public void onCreate(Bundle savedInstanceState) {
Then using super to call the onCreate() method here:
super.onCreate(savedInstanceState);
Doesn't this mean that you are calling the onCreate() method from the Activity class rather than the HelloAndroidActivity class? If so, what is the point of declaring a method with the same name in the HelloAndroidActivity class?
Thanks for any clarification.
In your example, HelloAndroidActivity is a class that inherits from Activity. You are then overriding the base class (Activity)'s onCreate method. Overriding occurs when you define a method in a derived class with the same signature as an existing method in the base class. This means that when I call onCreate on an instance of HelloAndroidActivity, I will execute the HelloAndroidActivity version, and not the base class (Activity)'s version.
The instruction super.OnCreate(savedInstanceState) in the overridden version is explicitly calling the base class's version of the method. What this means is you want HelloAndroidActivity.onCreate to first execute the base class's implementation, then run some more code.
Take the following examples to illustrate this behavior (assume the method Output just outputs something to the screen):
1.
class A
{
public void DoSomething()
{
Output("A");
}
}
In this case, calling A.DoSomething() will output "A".
2.
Assume we still have the class A defined as above, and the following:
class B extends A
{
}
In this case, calling B.DoSomething() will also output "A".
3.
Assume we still have the class A defined as above, and the following instead:
class B extends A
{
#Override
public void DoSomething()
{
Output("B");
}
}
Now, calling B.DoSomething() will output "B".
4.
Assume we still have the class A defined as above, and now this instead:
class B extends A
{
#Override
public void DoSomething()
{
super.DoSomething();
Output("B");
}
}
Now, calling B.DoSomething() will output "A" and then "B".
You are creating a class that inherits from Activity; but you have to define its behaviour, so you tell your class, when created, to call base class to complete all the things that must be done (super.onCreate()), then you set your layout to show your screen/app (setContentView()).
One thing more: take a look at #Override defined right before public void onCreate(Bundle savedInstanceState): override means that you're extending base method to let your derived class do all the work of the base one, including (after) your logic.
Question: What is the purpose of declaring the onCreate() method here?
Answer: The oncreate() method is analogous to main(String args[]) in ususal JAVA. The oncreate activity is called when your Activity starts. So all the initialisations should be done in this method.
You write: public class HelloAndroidActivity extends Activity
This means that you are creating a class - "HelloAndroidClass" that inherits from class = "Activity".
You write: super.onCreate(savedInstanceState);
Java uses the keyword "super" to call constructors from parent class. You are using the concept of overriding here. When you run your code, the oncreate method of base class "HelloAndroidActivity" is executed and not that of parent class - "Activity class".
So you code will first run the base class implementation of oncreate() method(super.oncreate(...)) and then the implementation of derived class.
Question: What is the point of declaring a method with the same name in the HelloAndroidActivity class?
Answer: The super keyword is being used to initialize the objects. The point in redeclaring the same method and using overiding is that you are saved from rewriting the code of base class.
onCreate is sort of your main(String[] args) function in normal Java. It is where you setup your code.
From documentation for onCreate method:
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
See more here for activity methods, lifecycle etc.

Categories

Resources