Accessing view through activity - java

i cannot access my view script through my activity. what i want to do it:
Activity:
protected void callViewScriptFunction()
{
GameView.somefunction();
}
GameView:
protected void somefunction();
{
// do something
}

You have to first create an instance of GameView to access it:
GameView myView = new GameView();
myView.somefunction();
or you can make a static method in GameView
protected static void somefunction(){
//do something
}
then access it anywhere statically GameView.somefunction()

Related

How to call a Main activity method in another non activity class

Below is My Main activity with ColorChange method.I want to call this Colorchange method in ImageColor Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ColorChange() { // <----- Want to call this method in below class
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
And this is my class where i want to call the ColorChange method of Mainactivity.
public class ImageColor {
public void Imager() {
// Want to call my ColorChange method here
MainActivity obj = new MainActivity();
obj.ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
I have already tried using Mainactivity as object it crashes my app.I also cannot declare my ColorChange method static because it uses findViewbyid.Please let me know if there is any way to call Color change method in this Image Color Class.
Try this way. It will help you.
public class ImageColor {
public void Imager(Activity activity) {
// Want to call my ColorChange method here
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method
class MainActivity {
interface mInterface = new interface() {
public void colorChange(){
}
}
}
pass mInterface to non activity class and call colorChange of interface when you want ..
You have to pass activity as a parameter in ImageColor class
Then call your ColorChange() method by refference of Activity.
Like This-
public class ImageColor {
Activity activity;
public ImageColor(Activity activity)
{
this.activity = activity;
}
public void Imager()
{
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange();
}
}
Activity classes are created by Android. So the above method is not correct.
You have 2 ways to access the method in activity.
1 . using a static method
public static void ColorChange() {
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
Using a callback mechanism
public interface ImageLoadedcallback{
void onColorChanged(int color);
}
And update
public class ImageColor {
public void Imager(ImageLoadedcallback callback) {
callback.onColorChanged(color)
}
}
And In activity
public void ColorChange() {
new ImageLoader().Imager(new ImageLoadedcallback{
#Override
public void onImageLoaded(Color color){
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
});
}
To make it clear, make an Activity as a static variable can lead to Activity leak, so we must avoid doing that.
I suppose if the Activity where you create ImageColor object is MainActivity, you can pass MainActivity directly to achieve what you want.
public class ImageColor {
public void Imager(MainActivity activity) {
activity.ColorChange();
}
}
If you called it from other class(not from MainActivity), you can always passing MainActivity to that other class object to be used for ImageColor object.
PS: Check about java naming convention too, it will help you to write a better code

Android - accessing var in class in class

I am making a module to include with all my applications. In this module, onCreate is overridden to perform code I like doing in all my apps, like using SupportActionBar. In all my applications, I have stuck to keeping my toolbar element id toolbar. I want the overridden function to access this, without actually giving it the id. I don't want to have to do super.onCreate(savedInstanceState, R.id.toolbar) but super.onCreate(savedInstanceState, R.class) or related, and get the function to get the variable on its own, like:
// In custom parent class
protected void onCreate(Bundle savedInstanceState, Class r) {
super.onCreate(savedInstanceState);
Toolbar t = findViewById(r.getClass("id").getInt("toolbar"));
setSupportActionBar(t);
}
// Main func
// Extends class in which above function resides
#Override
protected void onCreate(Bundle b) {
super.onCreate(b, R.class);
}
In parameter should be object of Resources class. So:
// In custom parent class ( extends android.support.v7.app.AppCompatActivity )
public void doStuff(Resources r) {
Toolbar t = findViewById(r.getClass("id").getInt("toolbar"))
setSupportActionBar(t);
}
// Main func
// Extends class in which above function resides
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
doStuff(getResources()); //we have Resources
}
but i do not undestand what is purpose of sending R as method parameter. It can be done this way:
// In custom parent class
public void doStuff() {
Toolbar t = findViewById(getResources().getClass("id").getInt("toolbar"))
setSupportActionBar(t);
}
// Main func
// Extends class in which above function resides
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
doStuff();
}

Android: call a function only on child activity from parent activity

My ParentActivity.java is like this
public class ParentActivity extends Activity{
public void childOnlyMethod(){
Log.d(TAG,"child only method triggered in parent activity");
}
public void startChildActivtityButton(){
startActivity(new Intent(this, ChildActivity.class));
}
public void childOnlyMethodButton(){
childOnlyMethod();
}
}
And my ChildActivity.java is like this
public class ChildActivity extends ParentActivity{
#Override
public void childOnlyMethod(){
Log.d(TAG,"child only method triggered in child activity");
}
}
The problem is when I press childOnlyMethodButton, childOnlyMethod() in both parent and child activity gets invoked I want it to be invoked on child only how can I achieve that?
#Override annotation does nothing, it is only used to tell the compiler and IDE that this method overrides its super class. Non-static methods are associated to objects, not classes. Overriding means completely replace the method in its super class. So if you invoke childOnlyMethod on ChildActivity, only child version will be invoked.
I'm guessing you were actually clicking on the parent activity instance. I don't really get the point why you want to invoke a child method on parent reference. If you can post the real code, I can give you more precise answer.
However, you can try the following code. This example will only invoke child version childOnlyMethod on ChildActivity instance. But it will still invoke parent's childOnlyMethod if you click the button on ParentActivity.
public class ParentActivity extends Activity implements View.OnClickListener {
private static final String TAG = "ParentActivity";
private Button mStartChileButton;
private Button mButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStartChileButton = (Button) findViewById(R.id.startChileButton);
mButton = (Button) findViewById(R.id.button);
mStartChileButton.setOnClickListener(this);
mButton.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.R.id.startChileButton:
startActivity(new Intent(this, ChildActivity.class));
break;
case R.id.R.id.button:
default:
childOnlyMethod();
break;
}
}
public void childOnlyMethod() {
Log.d(TAG, "Called from ParentActivity");
}
}
public class ChildActivity extends ParentActivity {
private static final String TAG = "ChildActivity";
#Override
public void childOnlyMethod() {
Log.d(TAG, "Called from ChildActivity");
}
}
If you are extending a parent class, all the methods in the parent class are passed down somewhat to the child class, if you don't want the method in the parent class to be implemented, first start by removing that #Override annotation in the child class above the method. Then use this snipped below, all it does is make the Method in the parent class either private or protected so that it can't be accessed in the child class.
public class ParentActivity extends Activity {
private void childOnlyMethod(){
Log.d(TAG,"child only method triggered in parent activity");
}
//OR
protected void childOnlyMethod(){
Log.d(TAG,"child only method triggered in parent activity");
}
}

calling an activity method from custom onClickListener class

i trying to call a method that stays in my MainActivity class from custom onClickListener object. And there is something wrong with variable scope.
so in my MainActivity i have:
Button resetButton = (Button) findViewById(R.id.ResetButton);
View.OnClickListener myListener = new MyListener(GameBoard, width);
resetButton.setOnClickListener(myListener);
this is what my myListener class look like:
public class MyListener implements View.OnClickListener
{
private static MainActivity mainActivity;
public MyListener(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public void onClick(View v) {
mainActivity.myMethod();
}
}
and method also in MainActivity that uses some MainActivity instance variables:
public void myMethod()
{
InstanceVariable++; // for example
}
Then when calling that myMethod on mainActivity object that i passing to myListener constructor by clicking resetButton i getting an error something about MainActivity InstanceVariable scope. I`m very beginner to android programming, so i cant fully understand where its coming from.
And this error disappears when i pass this InstanceVariable to constructor of myListener object. I think there should be an easier way to do that.
Change to:
public void myMethod() {
mainActivity.instanceVariable++; // for example
}
instancevariable is not visible in your MyListener class, you have to point that it ts in the mainActivity object.
If your instanceVariable is private, create getter function in mainActivity:
public void getInstanceVariable() {
return this.instanceVariable
}
and use it this way:
public void myMethod() {
mainActivity.setInstanceVariable(mainActivity.getInstanceVariable()+1); // for example
}
make InstanceVariable to
public static int InstanceVariable;
and use this
#Override
public void onClick(View v) {
MainActivity.InstanceVariable++;
}
don't make methods for function that has less than 8 lines
Try this :
Make your listener an inner class of your activity, then :
class MyListener implements View.OnClickListener {
public MyListener() {
}
#Override
public void onClick(View v) {
MainActivity.this.myMethod();
}
}

Android acessing MainActivity from AsyncTask

My application crashes after click the button, but the code executes properly.
public void makeLead(View v) throws Exception {
try {
RegisterTimer rt = new RegisterTimer();
rt.ma = this;
rt.execute(null);
} catch (Exception e) {
e.printStackTrace();
}
}
public void log(String msg)
{
final TextView tv = (TextView)findViewById(R.id.editText);
tv.append(msg);
}
private class RegisterTimer extends AsyncTask {
public MainActivity ma;
#Override
protected Object doInBackground(Object[] objects) {
ma.log("ausd");
return null;
}
}
makeLead is onClick event. Method ma.log generates an error but works properly (msg added to textEdit). When I delete ma.log, app doesn't crash. I have no logs in my AndroidStudio so I can't see error message. What's wrong ?
You can not touch the Views in a non UI Thread.
and you are appending text to TextView in a background Thread which is not allowed.
and I hope there is no problem with the initialization of MainActivity inside RegisterTimer as you are not creating the instance of Activity manually. You are in correct way with the initialization rt.ma = this. and why do you need AsyncTask just for changing the text of a TextView?
You cannot update ui from a doInbackground. Initializing ma is not required
Make AsyncTask an inner class of Activity and update ui in onPostExecute
or use interface as a callback to the activity
Edit:
To make it clear
Make asynctaks an inner class of activity. Declare textview as a instance variable. Return result in doInbackground
In Activity
TextView tv;
#Override
public void onCreate(Bundle savedInstancestate)
super.onCreate(savedInstancestate);
setContentView(R.layout.yourlayout);
tv = (TextView)findViewById(R.id.editText);
Then
#Override
protected String doInBackground(Void objects) {
// some background computation
return "ausd";
}
In onpostExecute
#Override
protected void onPostExecute(String result)
{
super.onPostExecute();
tv.append(result);
}
Also you need
private class RegisterTimer extends AsyncTask<Void,Void,String> { // args missing
As described by #Raghunandan you have not initialized ma.
next is you cannot access view in background thread.
if your thread class is inside of MainActivity class then you can use
runOnUiThread(new Runnable() {
#Override
public void run() {
ma.log("ausd");
}
});
inside doInBackground method to update view.
Your method log is public, you don't need to make an object of the MainActivity class to access it, instead you can call it directly. Also you need to add some template after your ASYNC task, if you want to pass some input to your background process, you are using ASYNC task in a wrong way.

Categories

Resources