I have a class which extends Activity.
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id,someactivitylayout);
new Game(getApplicationContext());
}
My Game class looks like
public class Game{
Game(final Context context){
cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* here i need to call runOnUIThread*/
}
}
}
My code does not have any syntax errors, so it compiles fine.
In the place where i have to call runOnUIThread, i have tried
Thread t = new Thread() {
public void run() {
while (progressBar.getProgress() < 100) {
((Activity) context).runOnUiThread(new unnable() {
public void run() {
}
});
}
};
t.start();
But when i try to cast context to Activity it gives an exception
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
Why is it not possible to cast context to Activity??
I have tried many ways but did not find anyway to get Activity in my Game class.
Is there any way to do that??
You are sending ApplicationContext to the Game class. Just replace the getApplicationContext() with this to pass the Activity Context. It will work.
It should be new Game(this)
try with
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id,someactivitylayout);
new Game(this);
}
}
Related
Im interested if i can to set some common listeners inside main activity class? For my project i use FirebaseAuth, so i would like to init it in MainActivity onCreate(), setup needed listeners in onStart() and onStop(), and then inherit that class in every other activity class.
Some code to please you :]
MainActivity class [parent]:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
protected FirebaseAuthentication firebaseAuthentication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firebaseAuthentication = new FirebaseAuthentication(FirebaseAuth.getInstance(), FirebaseDatabase.getInstance());
}
#Override
protected void onStart() {
super.onStart();
firebaseAuthentication.addAuthStateListener();
}
#Override
public void onStop() {
super.onStop();
firebaseAuthentication.removeAuthStateListener();
}
}
AuthActivity class [child]:
public class AuthActivity extends MainActivity implements FirebaseAuthentication.OnUserAuthListener {
#BindView(R.id.viewPager) LockableViewPager viewPager;
private String userUID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_market);
ButterKnife.bind(this);
firebaseAuthentication.setOnUserAuthListener(this);
firebaseAuthentication.isSingedIn(); // check if user is singed in
}
#Override
// response for firebaseAuthentication.isSingedIn() above
public void onAuthSuccess(String userUID) {
this.userUID = userUID;
}
#Override
// response for firebaseAuthentication.isSingedIn() above
public void onAuthFailure(String message) {
snackbar(message);
Intent intent = new Intent(this, AuthActivity.class);
startActivity(intent);
finish(); // TODO mb should to delete it
}
}
Can this implementations bring me errors (maybe NullPointerExeption or what unexpectedly in future)?
Would be great if you provide me some sources to read/watch.
Thank you.
Perfect example of abstraction, but not really a question.
You will not get any nullpointers or other errors by implementing it like this.
I am using Espresso and Mockito for testing an Activity. Is it possible to mock a method before an activity is created.
public class MyActivity extends Activity {
public int i;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callSomeMethod();
callAnotherMethod();
}
protected void callSomeMethod() {
//do some work
}
protected void callAnotherMethod() {
//do some work
}
}
My test class looks like
public class ActivityTest{
#Rule
public MyActivityRule testRule = new MyActivityRule(MyActivity.class);
public void test_preconditions(){
assertNotNull(testRule.getActivity())
}
}
But i need to mock callSomeMethod() and callAnotherMethod() method. Thanks in advance.
Like my title says, i'm looking for an equivalent of getActivity() in my ActionBarActivity class in my Android project.
I want to pass an Activity parameter in AsyncTask declaration object, because i'm using an Activity object in my custom AsyncTask extended class
Here an example simplest code of my project
public class EventCreator extends ActionBarActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_even_creator);
View v = getLayoutInflater().inflate(R.layout.activity_even_creator,null);
this.context = this.getBaseContext();
final Button createButton = (Button)findViewById(R.id.createEventButton);
createButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTask<Void,Void,Boolean> eventCreatorSend = new SendEvents(/* here need activity object */);
eventCreatorSend.execute();
}
});
}
class SendEvents extends AsyncTask<Void,Void,Boolean> {
public Activity act;
SendEvents(Activity a) {
this.act = a;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Void... params) {
SystemClock.sleep(5000);
return true;
}
#Override
protected void onPostExecute(Boolean params) {
if (params){
((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.GONE);
act.finish();
}
else {
((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.VISIBLE);
Toast.makeText(act,"Fail to send event",Toast.LENGTH_SHORT).show();
}
}
};
}
In a time, i thought use getParent() from ActionBarActivity class, but it return a null object.
So how to get the Activity object i want in ActionBarActivity class ?
Try nameofactivity.this instead getActivity()
I always use getActivity() in Fragments Activities and .this in any other kind of Activity.
Oh damn !
I just found a solution just after posting my ask.
I use MyClass.this, and it's done. Like this :
AsyncTask<Void,Void,Boolean> eventCreatorSend = new SendEvents(EventCreator.this);
eventCreatorSend.execute();
Hope that's can help someone !
The easiest way is an Activity variable
// in your fragment
Activity myActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//fragment shouts "i know my father!!!"
myActivity = activity; //
}
now your activity instance(The father) can be represented anywhere
In my app i am showing a custom dialog from a non-activity class. it works but rarely crashed with the following reason:
android.view.windowmanager Bad TokenException:unable to add window-
token android.os.binderproxy#2afac69d8 is not valid;is your activity running?
my coding structure:
MainActivity.java(Activity class)
public class MainActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
........
UpdateClass obj = new UpdateClass(MainActivity.this);
obj.checkUpdate();
}
}
UpdateClass.java (Non Activity class)
public class UpdateClass{
UpdateClass(MainActivity mainActivity ){
this.context = mainActivity;
}
checkUpdate(){
dialog_Update = new Dialog(context);
...
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
....
}
});
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog_Update.dismiss();
}
});
dialog_Update.show();
......
}
}
Just try to implement as below :
public class MainActivity extends TabActivity {
#Override
private Context context;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
........
context=MainActivity.this;
UpdateClass obj = new UpdateClass(context);
obj.checkUpdate();
}
}
Do the changes as below in your UpdateClass.
Instead of passing the MainActivity in constructor pass the Activity as below:
public class UpdateClass{
pdateClass(Activity mainActivity ){ <----Pass the activity here.
this.context = mainActivity;
}
......
}
}
I have an activity that roughly follows this structure:
public class myActivity extends Activity implements myCallback{
//Code
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
new myAsyncTask(myActivity.this).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(context,"Hello",Toast.LENGTH_SHORT).show();
}
}
And myAsyncTask has the myCallback() interface defined and it calls it eventually. No matter what I do, whatever UI element I try to show, be it a Toast or a ProgressDialog, it won't show. Nor do I get any exceptions. The rest of the callback code gets perfectly executed. Why is this?
Try using:
public class myActivity extends Activity implements myCallback{
//Code
Context mContext;
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
mContext = this;
new myAsyncTask(getApplicationContext()).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(mContext,"Hello",Toast.LENGTH_SHORT).show();
}
}
Instead of using context , use getApplicationContext... i hope it will show toast... like this
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();