I have a main class in Android java project where all functions are defined. Then I have 2 other classes that extend the main class and implement Runnable.
- main class: All main functions
- class 2: I use all main functions and have a static variable
Xwhich I modify in file 2. - class 3: I use all main functions and have a static variable
Ywhich I modify in file 3.
In the main class, I start 2 threads: one for Class2, and one for Class3.
When I try to call Class2.X from the main class, it is always null no matter what. I have tried volatile, synchronized(thread), getvalue(), etc. but it is not working.
What should I do to read the values of Class2.X such that it is not null from the main class?
Here is the code:
Thread t = new Thread(new Functionss(mRgbImage));
t.start();
Thread t2 = new Thread(new Functionss_2(mRgbImage));
t2.start();
if(boolean_variable)
{
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Bitmap final_added =addition(mRgbImage2, mRgbImage3);
mImageView.setImageBitmap(final_added);
mRgbImage2 and mRgbImage3 are the static volatile variables.
In fact, I think it is not a problem of variables because when i use an image in the main class and modify it, and then execute mImageView.setImageBitmap(initial_image) i am still getting a black screen on my android phone.
I have noted the following in the logcat:
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@40a34d28
If I remove the threads, I don’t get this error.
Any help?
I suspect that your threads are never executing the assignment statement or are assigning a different value or something. Maybe putting some log messages or debugging your application and putting a break point at the assignment would help.
If you had something like:
and then:
Then after the assignment happens in
Class2then thevaluewill have been updated. This is obviously a simple example and I suspect theClass2thread has not actually finished in your code, but as long as the assignment has been reached thenvaluewill have been changed. Again, log messages or debugger would help here.It would be better to have something like the following pattern:
So then
MainClasscan access the value fromClass2andClass3without confusion. Notice that you still need thevolatilekeyword there because the value is being get/set from different threads.Hope something here helps. If you edit your question with more details I may be able to help more.