Own Events in Java not able to modify Classobjects? - java

this is My Situation:
I want to make two classes communicate with each other. So MainActivity is
making a new Object of SomeOtherstrangeClass.
public class MainActivity extends AppCompatActivity implements myEventListener {
private TextView txtHelloSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtHelloSet = (TextView) findViewById(R.id.txtHello);
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass();
}
#Override
public void someEvent(int e) {
Log.v("[Listener]", "SomeEvent triggered. Number: " + e);
txtHelloSet.setText("Event came in!");
}
}
#
public class SomeOtherStrangeClass {
public SomeOtherStrangeClass(){
EventThrower eventThrower = new EventThrower();
MainActivity mainActivity = new MainActivity();
eventThrower.addListener(mainActivity);
Log.v("[Listener]", "Throwing event");
eventThrower.someEvent(13);
}
}
interface myEventListener extends java.util.EventListener {
void someEvent(int e);
}
public class EventThrower {
private List<myEventListener> listeners = new ArrayList<myEventListener>();
public void addListener(myEventListener toAdd){
listeners.add(toAdd);
}
public void removeListener(myEventListener toRemove){
listeners.remove(toRemove);
}
public void someEvent(int e){
for(myEventListener el : listeners)
el.someEvent(e);
}
}
So this is how I'am doing it. But the Problem is, that when an event is thrown its like I'am still calling the Methode someEvent which is in MainActivity in SomeOtherStrangeClass. So I'am not able to modify any Objects in MainActivity. It's like they are not existing. I'am getting a NPE:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Why this is so?
Is there any solution for that?

MainActivity mainActivity = new MainActivity();
You are doing something wrong here. It is not supposed to create Activity objects like this. You should rethink about your application logic.

You need to reference the instance of MainActivity that is currently in foreground in order to recognize any callbacks in it.
Try changing the constructor for SomeOtherStrangeClass like this:
public SomeOtherStrangeClass(myEventListener listener) {
EventThrower eventThrower = new EventThrower();
eventThrower.addListener(listener);
Log.v("[Listener]", "Throwing event");
eventThrower.someEvent(13);
}
Then, in onCreate() of your activity,
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass(this);

Related

how to send data from one activity to another activity in android

I have created an volley list in this i have problem to get data from adapter to activity and this activity to another activity. I have received error cannot cast activity.java to anotherActivity.java below is my code. Please help me anyone thanks.
My Interface itemclick in Adapter class
private OnItemClickGetPlaylist mListener;
public interface OnItemClickGetPlaylist{
public void OnPlaylistItemClick(String playlistName,int numOfItems,String imageViewForPlaylist);
}
public void setOnClickListenerOnPlaylist(OnItemClickGetPlaylist listener)
{
mListener = listener;
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = playlist.getId_playlist_identify();
String PlaylistName = playlist.getTitile_of_playlist();
String imageOfPlaylist = playlist.getImage_of_playlist();
int numOfPlaylistSongs = getItemCount();
SendIdToDatabase(id);
if (mListener != null)
{
mListener.OnPlaylistItemClick(PlaylistName,numOfPlaylistSongs,imageOfPlaylist);
}
else {
Toast.makeText(context, "mListeren is null" + mListener, Toast.LENGTH_SHORT).show();
}
}
});
After get data handle OnPlaylistItemClick click in Activity below Codes
public void OnItemClickHandleInPlaylistActivity(String playlistName,int numOfItems,String imageViewForPlaylist)
{
//here is the adapter item click in activity now i want to send that data to another activity without any intent please help me.
// i have implement below code but it give me cannot cast activity to another activity error.
((anotherActivity) getApplicationContext()).OnItemClickInMusicActivity(playlistName,numOfItems,imageViewForPlaylist);
}
See the solution at https://stackoverflow.com/a/47637313/2413303
public class MyApplication extends Application {
private static MyApplication INSTANCE;
DataRepository dataRepository; // this is YOUR class
#Override
public void onCreate() {
super.onCreate();
INSTANCE = this;
dataRepository = new DataRepository();
}
public static MyApplication get() {
return INSTANCE;
}
}
The DataRepository should expose LiveData:
public class DataRepository {
private final MutableLiveData<MyData> data = new MutableLiveData<>();
public LiveData<MyData> getMyData() {
return data;
}
public void updateText(String text) {
MyData newData = data.getValue()
.toBuilder() // immutable new copy
.setText(text)
.build();
data.setValue(newData);
}
}
Where the Activity subscribes to this:
public class MyActivity extends AppCompatActivity {
DataRepository dataRepository;
TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication app = (MyApplication)getApplicationContext();
dataRepository = app.getDataRepository();
setContentView(R.layout.main_activity);
textView = findViewById(R.id.textview);
dataRepository.getMyData().observe(this, new Observer() {
#Override
public void onChange(MyObject myObject) {
textView.setText(myObject.getText());
}
}
}
So to update this text, you need to get the DataRepository class, and call updateText on it:
DataRepository dataRepository = MyApplication.get().dataRepository();
dataRepository.updateText("my new text");
Make sure that the data in DataRepository is properly persisted somewhere, or at least can be obtained again after process death. You might want to use a database for example (but not shared preferences).
If you don't want to use Intents, maybe you can use a publish/subscribe architecture. There is a library called eventbus (org.greenrobot:eventbus) very easy to use which could achieve what you want.
Use an Application Class instead.
public class MyApplicationClass extends Application{
#Override
public void onCreate() {
super.onCreate();
///do something on create
}
getterMethods(){...}
setterMethods(){...}
}
then add android:name=".MyApplicationClass" to manifest file
Now you can access the methods in class by
MyApplicationClass applicationClass = (MyApplicationClass)getApplicationContext();
int id = applicationClass .getterMethod().getID;
String playListName = applicationClass .getterMethod().getPlayListName();
and vice versa for Setter();
after that you can use it for data getting and setting Data throughout the application.
Hope it helps :)
References:
https://guides.codepath.com/android/Understanding-the-Android-Application-Class
I find the best to use callbacks.
in ClassA:
Create interface
MyCallback callback;
viod setCallback(MyCallback callback){
this.callback = callback;
}
viod onStop(){
callback = null;
}
interface MyCallback{
void doSomething(Params params);
}
in ClassB:
implement MyCallback
public class ClassB **implements ClassA.MyCallback**
set reference in onCreate
ClassA classA = new ClassA();
classA.setCallback(this);
// override method doSomething
#override
void doSomething(Params params){
//do your thing with the params…
}
when the job is done inside class A call:
callback.doSomething(params);
destroy reference inside class B in onStop()
classA.onStop();

Call public void from class that extends MainActivity

I am trying to extend Main Activity in another class so that i can use objects already created in the Main Activity.
if i have a main activity:
public class MainActivity extends AppCompatActivity {
public ImageView jani;
public Context main;
public classextended janitest = new classextended();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jani = findViewById(R.id.jani);
main=this;
janitest.janiaha();
Log.d("jani","FAK");
}
}
enter code here
And then a new class that extends MainActivitiy:
enter code here
public class classextended extends MainActivity {
public void janiaha(){
jani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main, "YES YOU KNOW YOUR JAVA!!!", Toast.LENGTH_SHORT).show();
}
});
}
}
How can i acces the public void janiaha() ? Or am i doing it all wrong : ) ?
Al i get is crashes--- yes i could use static classes but as far as i know memory leaks would be a reall problem.
You can't call methods of a subclass that aren't defined on the main class. If you mean to have multiple classes descended from MainActivity, make it a protected function on MainActivity that's either abstract or has a default implementation, then override it in the subclass. If you aren't planning on having multiple child classes, then I question the value of even having one.
U cant call a method from child class to a parent class. If u want to have a function do similar work like it then, U can create a normal class to do it. or u can do this in this class. u just have to make the method 'static'..
public static void janiaha(ImageView jani){
jani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main, "YES YOU KNOW YOUR JAVA!!!", Toast.LENGTH_SHORT).show();
}
});
}

Setting context on custom listener in a dialog

I created a very simple listener interface that looks like this:
public interface ReportDialogListener {
void shouldRemoveBlockedUser();
}
Now, in my ReportDialog class which is defined like this:
public class ReportDialog extends Dialog implements View.OnClickListener {}
I want to implement this listener and send callback for a certain action. However, when I do send callback after a certain action... my mDialogListener variable is null.
Where do I set the context?
This is what I tried:
private ReportDialogListener mDialogListener;
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
try {
mDialogListener = (ReportDialogListener) getContext();
} catch (ClassCastException e) {
}
}
#Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mDialogListener = null;
}
But when I call mDialogListener.shouldRemoveBlockedUser();, mDialogListener is null...
Also- I made sure my main activity was implementing ReportDialogListener... thanks
Implement Listener in MainActivity
Public class MainActivity implements ReportDialogListener {
ReportDialogListener reportDialogListener ;
public void onCreate(Bundle saveInstanceState){
reportDialogListener =this;
}
#override
public void shouldRemoveBlockedUser(){
}
}
Pass reportDialogListener object to other class or activity and call the listener method reportDialogListener.shouldRemoveBlockedUser();
If this main activity implements the interface, do not use the activity context. Use this instead. mDialogListener = this;
Also i do not see where you implement the interface,only the View onClick interface you have actually implemented.
public class ReportDialog extends Dialog implements View.OnClickListener
to
public class ReportDialog extends Dialog implements View.OnClickListener,ReportDialogListener
To implement the interface in another, either you define it in the constructor of the calling program, or devise a method that does it.
Since my main activity was actually sending this when creating an instance of ReportDialog :
if (mReportDialog == null) {
mReportDialog = new ReportDialog(this);
}
I was able to assign it to a variable in the constructor of ReportDialog
public ReportDialog(Activity activity) {
super(activity);
mActivity = activity;
init();
}
Then, use it like this:
mDialogListener = (ReportDialogListener) mActivity;
Works perfectly.

Passing string from class to main activity

I'm trying to pass something from one class to my MainActivity, but it doesn't seem to work, I don't understand why.
I have my GPS Tracker on another class (not the MainActivity) in order to reuse it.
When the location changes, I want my other class to call a method from within the MainActivity to update my UI.
I summarized my code like that :
My MAIN ACTIVITY :
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
EditText et;
Button btun;
int arg0;
int stuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
btun = (Button) findViewById(R.id.btun);
btun.setOnClickListener(this);
}
private void setter(int stuff) {
tv.setText(stuff);
}
public void setText(int _stuff) {
_stuff = stuff;
setter(_stuff);
}
#Override
public void onClick(View v) {
Getter get = new Getter();
get.getInfo(Integer.parseInt(et.getText().toString()));
}
The other Class :
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I end up having a NullPointerException in my LogCat
at :
- tv.setText(stuff);
- setter(_stuff);
- main.setText(_getString);
- get.getInfo(Integer.parseInt(et.getText().toString()));
and I don't really know why, and above all, how to fix it.
I'll appreciate any help !
(PS : My GPS tracker thingy is working fine, it's just about invoking my setter() method.
Instantiaing an Object of MainActivity doesn't automatically call onCreate method but this method is called when you start an activity using Intent; And using the same intent you can pass extra values. For example:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", value);
context.startActivity(intent);
and then in your main activity onCreate method:
String value = getIntent.getStringExtra("key");
Edit:
In your case why don't you change your void getInfo(int getString) to return a String value i.e.
public class Getter {
...
...
public String getInfo(int getString) {
_getString = getString * 8;
return Integer.toString(_getString);
}
}
and then in onClick event of MainActivity bind this returned text to TextView
It's maybe because the MainActivity's onCreate()-Method hasn't been called. Therefore the tv is still null causing the NullPointerException
One problem is here. main is an Activity, but it should be the MainActivity calling this object.
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I cannot really make out what you are trying to achieve in the Getter class, but either:
1: Pass the Activity instance to the object
public class Getter {
int _getString;
MainActivity _main = null;
public Getter(MainActivity main) {
_main = main;
}
public void getInfo(int getString) {
_getString = getString * 8;
_main.setText(_getString);
}
}
#Override
public void onClick(View v) {
Getter get = new Getter(this);
get.getInfo(Integer.parseInt(et.getText().toString()));
}
or
2: set the text in the Activity and only get the value from the Getter (My choice)
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
return getString * 8;
}
}
#Override
public void onClick(View v) {
Getter get = new Getter();
int info = get.getInfo(Integer.parseInt(et.getText().toString()));
setText(Integer.toString(info));
}
Use Application Class or create a separate Class and declare a static variable in it. Use getter & setter methods to get the value. To update the Textview in mainacivity from other class pass the texview reference variable from main activity and put null check condition in other class if textview is not null then update the value.

passing reference of class to another class android error

I recently asked the precursor to this question and had a great reply. However, when i was working this into my android application i am getting an unexpected error and was wondering if everyone could take a look at my code and help me see what i am doing wrong.
Link to the initial question: passing reference of class to another class
My ERROR: "The constructor ConnectDevice(new View.OnClickListener(){}) is undefined"
The above is an error detected by eclipse.
Thanks in advance!
Below are My code snippets:
public class SmartApp extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton);
connectDeviceButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
Thread cThread = new Thread(new ConnectDevice(this));
cThread.start();
}
});
}
}
public class ConnectDevice implements Runnable {
private boolean connected;
private SmartApp smartAppRef;
private ObjectInputStream ois;
public ConnectDevice(SmartApp smartAppRef) {
this.smartAppRef = smartAppRef;
}
}
That's because you are passing an OnClickListener object, but the constructor of the ConnectDevice class expects a SmartApp object. Why? you are doing this:
new ConnectDevice(this);
In that case, this references the OnClickListener. Change it to:
new ConnectDevice(SmartApp.this);

Categories