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();
Related
I decided to try and make my code more object oriented and avoid repetitive code in another class.
Source code for Activities :
public class EasyMode extends MainActivity {
GameActivityPVP game = new GameActivityPVP();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
game.initializeButtons();
}
}
public class GameActivityPVP extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
The second the program gets to the line where I try to call a method using game.methodName(); the program crashes. No compiling errors or anything.
I am new to programming in general so please take it easy on me and I tried to simplify my code as much as possible.
Android Monitor/logcat :
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
and
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
You can use another class's method by creating object of parent class.
See below example;
Here you want to use method from 'GameActivityPVP' class. So you need to create one object in this class only.
public class GameActivityPVP extends MainActivity {
public static GameActivityPVP mGameActivity;
public GameActivityPVP getInstance(){
return mGameActivity; // assign value in onCreate() method.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
mGameActivity = this; // Do not forget this, otherwise you'll get Exception here.
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
Now use this Object in another class 'EasyMode' like this;
if(GameActivityPVP.getInstance()!=null){
GameActivityPVP.getInstance().initializeButtons();
}
Try This:
Make one Class Utils:
In Utils:
public class Utils{
private Activity context;
Button button;
public Utils(Activity context) {
this.context=context;
}
public void inititializeButton(Activity context){
button[0]= (Button) context.findViewById(R.id.button_flasher);
}
}
And in your Class use:
public class EasyMode extends MainActivity {
Utils utils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
utils=new Utils(this);
utils.initializeButtons();
}
}
As already stated, you shouldn't use nested activities, they are not supposed to interact like this. If you want two activities to interact you have to do it through an intent. Regarding the duplicated code, you have few solution presented but my personal opinion is that the OOP rules are not followed. If I had to write that logic, I would create a BaseActivity to hold the common logic of the other two activities and use inheritance to extend them.
public class BaseActivity extends Activity {
protected List<Button> buttons = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
protected void initializeButtons() {
buttons.add((Button) findViewById(R.id.button1));
}
}
public class EasyMode extends BaseActivity {
// Add here logic that is used only in EasyMode activity
}
public class GameActivityPVP extends BaseActivity {
// Add here logic that is used only in GameActivityPVP activity
}
Note that in this way you don't have to override onCreate again to initialise the buttons and so on. Also, I saw that you used the same layout for both activities, but if you want to use different layouts you can do it as usual and then call initializeButtons.
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
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);
}
}
In my android application inside activity I am defining one interface like this :
public interface sideFilterInterface
{
public void changeFilters(int layoutId);
}
inside activity I use this interface like this
#Override
public void onCreate(Bundle savedInstanceState) {
mCallback = (sideFilterInterface) this;
mCallback.changeFilters(R.layout.filter_details);
}
I am implementing this interface in another fragment. when i tried this code it gives me error regarding casting here mCallback = (sideFilterInterface) this;
How to do this. Am I doing something wrong. Need help. Thank you.
The main thing is you are trying to cast your Activity into Listener if you are not implementing the Listener in your activity.
If you are calling the public void changeFilters(int layoutId) through the interface , the code will not execute as the method in the interface is abstract.You need to implement the listener in the activity and then do the code there . Something like :
public class YourActivity extends Activity implements sideFilterInterface{
#Override
public void onCreate(Bundle savedInstanceState) {
//some code
this.changeFilters(R.layout.filter_details);
}
#Override
public void changeFilters(int layoutId) {
//Implement here
}
}
I have a problem with closing a custom dialog. I have two classes
class 1-> AndroidHTMLActivity
class 2-> CustomizeDialog
In my AndroidHTMLActivity I use java interface which is call from javascript, in this class i call CustomizeDialog
public class AndroidHTMLActivity extends Activity {
WebView myBrowser;
setContentView(R.layout.main);
myBrowser = (WebView)findViewById(R.id.mybrowser);
myBrowser.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/mypage.html");
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void openAndroidDialog(){
CustomizeDialog customizeDialog = new CustomizeDialog(mContext);
customizeDialog.show();
}
CustomizeDialog .java
public class CustomizeDialog extends Dialog {
Context ctx ;
public CustomizeDialog(Context context) {
super(context);
ctx = context;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
MyThread downloadThread = new MyThread();
downloadThread.start();
}
public class MyThread extends Thread {
#Override
public void run() {
try {
handler.post(new MyRunnable());
}
}
}
static public class MyRunnable implements Runnable {
public void run() {
// here i want to close this customized dialog
}
}
Here i can't use finish() method, I want to close the customized dialog box via the thread. Anyone has any idea about this?
Well I know this question is asked in the past and maybe already answered but haven't shared the correct answer but I still want to share this since I also got the same problem. Well here's what I did.
1st create the base class let say and create a static declaration for dialog.
public class Dialogs {
static Dialog dialog;
}
2nd is to put your custom dialog.
public void customDialog(Context context){
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_login);
dialog.setTitle(title);
//... other parts here
dialog.show();
}
then the dialog dismiss:
public static void dismissDialog(){
dialog.dismiss();
}
and on the other class to close the currect customDialog just call
Dialogs.dismissDialog();
That's it. :) Hope it helps.
close it with outside handler like this
App.HANDLER.post(new Runnable() {
#Override
public void run() {
dismiss();
cancel();
}
});
App is a application class