cant connect to facebook with a network thread - java

I need to connect to facebook so I use a Tread when using the network. but I have a problem:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
FacebookConnectTask task = new FacebookConnectTask("facebookId", "token", "email", facebookGender,0, 0);
task.setOnPreExecuteListener(this);
task.setOnDoneListener(this);
task.execute();
}
});
t.start();
}
I cant do
task.setOnPreExecuteListener(this);
task.setOnDoneListener(this);
eclipse gives me this error: "The method setOnDoneListener(Task.OnDoneListener) in the type Task is not applicable for the arguments (new Runnable(){})"
How can i fix this?
Thanks!

You've changed context's by being in a Thread your in an Annoyomous class, this is now your annonomous class and not the outer class.
Try this (pun intended):
task.setOnPreExecuteListener(YourOuterClass.this);
task.setOnDoneListener(YourOuterClass.this);
i.e.
public class YourClass implements OnDoneListener {
public doFacebook(){
new Thread(new Runnable(){
#Override
public void run(){
task.setOnDoneListener(YourClass.this);
}
}.start();
}
#Override
public void onDone(){
}
}
or alternatively pull your Threaded class out:
public class DoSomething implements Runnable {
private final OnDoneListener listener;
public DoSomething(OnDoneListener listener){
this.listener = listener;
}
#Override
public void run(){
FacebookConnectTask task = ... ;
task.setOnDoneListener(listener);
}
}
public class YourActivity extends Activity implements OnDoneListener {
public void onCreate(Bundle b){
new Thread(new DoSomething(this)).start();
}
#Override
public void onDone(){
// Tada
}
}
A further step if you wanted to be cooler is create your own interface and keep all the Facebook stuff in the runnable class:
public class DoSomething implements Runnable, OnDoneListener {
public interface OnFacebookFinished {
void onFacebookFinished();
}
private final OnFacebookFinished listener;
public DoSomething(OnFacebookFinished listener){
this.listener = listener;
}
#Override
public void run(){
FacebookConnectTask task = ... ;
task.setOnDoneListener(this);
}
#Override
public void onDone(){
if(listener != null){
listener.onFacebookFinished();
}
}
}
public class YourActivity extends Activity implements OnFacebookFinished {
#Override
public void onCreate(Bundle b){
new Thread(new DoSomething(this)).start();
}
#Override
public void onFacebookFinished(){
// Tada
}
}

Related

How to notify when a method has finished

How can i notify and execute instantly a method from the MainActivity class when a method from a non-activity class has finished?
MainActivity class:
public class MainActivity extends AppCompatActivity {
private ExpandableListViewAdapter mExpandableListViewAdapter;
PreselectionAplicationUseCases preselectionAplicationUseCases;
public void Preselection(){
if(preselectionAplicationUseCases.isMsg100PreselectionAplication()) {
mExpandableListViewAdapter.setSelectedChild(-1);
}
}
Non-activity class:
public class MSG0100 implements PreselectionAplicationUseCases {
msg100PreselectionAplication=true;
}
public boolean isMsg100PreselectionAplication() {
return msg100PreselectionAplication;
}
public void setMsg100PreselectionAplication(boolean msg100PreselectionAplication) {
this.msg100PreselectionAplication = msg100PreselectionAplication;
}
And the interface:
public interface PreselectionAplicationUseCases {
boolean isMsg100PreselectionAplication();
void setMsg100PreselectionAplication(boolean msg100PreselectionAplication);
}
So how can I execute the method Preselection automatically when this happens
msg100PreselectionAplication=true; in the non-activity class.
I was thinking that i can use a thread with wait and notify, but i think that can give some problems to the UI thread.
Couldn't you just use Observer pattern?
public class MSG0100 implements PreselectionAplicationUseCases {
private OnMsg100PreselectionChanged listener = null;
public void setOnMsgPreselectionChanged(OnMsg100PreselectionChanged listener) {
this.listener = listener;
}
public void setMsg100PreselectionAplication(boolean msg100PreselectionAplication) {
if(listener != null) {
listener.onPreselectionChanged(msg100PreselectionAplication);
}
}
}
interface OnMsg100PreselectionChanged {
void onPreselectionChanged(boolean isChanged);
}
public class MainActivity extends AppCompatActivity {
private ExpandableListViewAdapter mExpandableListViewAdapter;
PreselectionAplicationUseCases preselectionAplicationUseCases;
public void Preselection(){
preselectionApplicationUseCases.setOnMsgPreselectionChanged(new OnMsg100PreselectionChanged {
#Override
void onPreselectionChanged(boolean isChanged) {
//do something with changed boolean
}
});
}
}
You can create inteface like this and implement it in your activity class:
public interface OnMethodFinishedListener {
void onMethodFinish();
}
then make method call in your non-activity class:
public class MSG0100 implements PreselectionAplicationUseCases {
msg100PreselectionAplication=true;
}
private OnMethodFinishedListener mListener
public MSG0100 (OnMethodFinishedListener listner){
mListener = listener;
}
public boolean isMsg100PreselectionAplication() {
return msg100PreselectionAplication;
}
public void setMsg100PreselectionAplication(boolean msg100PreselectionAplication) {
this.msg100PreselectionAplication = msg100PreselectionAplication;
//here for example. or anywhere you need
mListener.onMethodFinish
}
And that is it - your activity will get call in overrided onMethodFinished method
This could be done also using while
while(msg100PreselectionAplication=true){
//do something to notify after that we set preselection again to false
msg100PreselectionAplication=false;
}

Android: Listener for Boolean change

I know that there is a lot of examples, but I can't still make it work.
I need to monitor Boolean value, which change to True, when phone is connected to proper wifi.
Wifi connection and check is done in second thread. Maybe there is problem? I've tried many solutions, and can't get it done.
Wrapper class for variable:
import java.util.ArrayList;
import java.util.List;
public class ConnectivityStatus {
private Boolean status = Boolean.FALSE;
private ConnectivityListener listener;
public Boolean getStatus(){
return status;
}
public void setStatus(Boolean status){
this.status = status;
if(status) {
listener.onChange();
}
}
public void addConnectivityListener(ConnectivityListener l) {
this.listener = l;
}
interface ConnectivityListener{
void onChange();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
...
private ConnectivityStatus mConnectionStatus;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mConnectionStatus = new ConnectivityStatus();
...
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startLoadingScreen();
connectToCamera(mWifiManager);
new Thread(new Runnable() {
public void run() {
long startTime = System.currentTimeMillis();
for(int i = 0; i<=6; i++) {
mConnectionStatus.setStatus(checkWifiSsid(mWifiManager, startTime));
if(mConnectionStatus.getStatus()) {
break;
}
}
}
});
}
});
mConnectionStatus.addConnectivityListener(new ConnectivityStatus.ConnectivityListener() {
#Override
public void onChange(){
openWebView();
}
});
}
I didn't notice earlier but, yes, you're missing something from your threading. You're creating a new thread but you're not telling it to start:
new Thread(new Runnable(){
public void run(){
// Optionally, you can also use log messages for debugging
Log.d("MY_LOG_TAG", "Some message to look for in the log.");
// ...
}
}).start(); // Make sure to tell it to start

Android HandlerThread update UI without UiHandler

this code works fine and update my "TextView" and also show "Toast"
and that is my Headache as I have tried to to pass A Runnable obj Without including my UiHandler on it as it suppose to be the bridge to update my UI Thread but my activity got updated with no single Error ?????
This not suppose to be as CustomHandlerThread should be A different thread
why this happen ?
My Activity
public class TestActivity extends BaseActivity {
Runnable task;
#BindView(R.id.send_test_message)
Button send_test_message;
private Handler mUiHandler = new Handler();
private MyWorkerThread mWorkerThread;
#Override
public void initViews() {
}
#Override
public void attachViewsListeners() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
ButterKnife.bind(this);
task = new Runnable() { ///this is normally work I have no problem with
///that
#Override
public void run() {
mUiHandler.post(new Runnable() {
#Override
public void run() {
send_test_message.setText("Change--->1");
}
});
}
};
}
#Override
protected void onStart() {
super.onStart();
mWorkerThread = new MyWorkerThread("myWorkerThread");
mWorkerThread.start();
mWorkerThread.prepareHandler();
mWorkerThread.postTask(task);
mWorkerThread.postTask(new Runnable() { /// why this task work with no
///error ?
#Override
public void run() {
send_test_message.setText("Change--->2");
}
});
}
#Override
protected void onDestroy() {
mWorkerThread.quit();
super.onDestroy();
}
my HandlerThread
//MyWorkerThread.java
public class MyWorkerThread extends HandlerThread {
Handler mWorkerHandler;
public MyWorkerThread(String name) {
super(name);
}
public void postTask(Runnable task) {
mWorkerHandler.post(task);
}
public void prepareHandler() {
mWorkerHandler = new Handler(getLooper());
Log.e("MyWorkerThread--->",Looper.myLooper().getThread().getName()); //-->main
Log.e("MyWorkerThread--->",getLooper().getThread().getName());//-->//myWorkerThread
Log.e("MyWorkerThread--->",Thread.currentThread().getName()); //-->main
}
}
I followed this link as A Referance
is My thread running on the MainThread or getLooper() intialize my
HandlerThread with MainThread Looper ,is those log message are true
please illuminate me
After fill day of debugging i Found out That if i post A Runnable to my
mWorkerThread with sleep() as here i got " Only the original thread that created a view hierarchy can touch its views."
as should be.. but until I know why it not works without it
I wish it would help some one.
try {
TimeUnit.SECONDS.sleep(2);
send_test_message.setText("Change--->");
} catch (Exception e) {
e.printStackTrace();
}

Calling Method w/ Argument on Main Thread from Secondary Thread

Like the title suggest I have an android project with a MainActivity class that has a TextView that I want to set the text of after receiving a message. I also have a class that runs a ServerSocket on a separate thread that receives the string message I want to display.
Part of my MainActivity looks like this,
private Handler UIHandler = new Handler();
private RemoteControlServer remoteConnection;
public static final int controlPort = 9090;
public class MainActivity extends Activity implements SensorEventListener
{
...
remoteConnection = new RemoteControlServer(controlPort, UIHandler);
...
private class RemoteControlServer extends RemoteControl
{
RemoteControlServer(int port, Handler ui)
{
super(port, ui);
}
#Override
public void onReceive(String[] msg)
{
//updates messages textview
}
#Override
public void onNotify(String[] msg)
{
//updates notification textview
}
}
}
The RemoteControlServer implementation of code that calls the onReceive(String[] msg) and also handles receiving messages on the different thread looks like this,
...
public abstract void onReceive(String[] msg);
public abstract void onNotify(String[] msg);
...
controlListener = new Thread(new Runnable()
{
boolean running = true;
public void run()
{
String line = null;
while(running)
{
try
{
//Handle incoming messages
...
onReceive(messages);
}
catch (final Exception e)
{
UIHandler.post(new Runnable()
{
public void run()
{
onNotify("Wifi Receive Failed " + e.toString() + "\n");
}
});
}
}
}
});
...
I'm getting the error "Only the original thread that created a view hierarchy can touch its views." when onReceive() is called and throws the exception and calls onNotify() with the exception description. Why does the onNotify() work but the otherone does not? How can I correctly call the listener to the the TextView and update its text? Thanks
private class RemoteControlServer extends RemoteControl
{
...
public class BridgeThread implements Runnable
{
String[] msgArray = null;
public BridgeThread(String[] msg)
{
msgArray = msg;
}
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
TextView zValue = (TextView) findViewById(R.id.connectionStatus);
zValue.setText(msgArray[0]);
}
});
}
}
#Override
public void onReceive(String[] msg)
{
BridgeThread bridgeTest = new BridgeThread(msg);
bridgeTest.run();
}
...
}

Why aren't all my listeners registered?

public interface DownloadListener {
public void onDownloaded();
}
public class DownloadManager {
private static DownloadManager instance;
private DownloadListener mDownloadListener;
public static synchronized DownloadManager getInstance(){
if(instance == null)
instance = new DownloadManager();
return instance;
}
private DownloadManager() {
myHandler.sendEmptyMessageDelayed(29, 3 * 1000);
}
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}
Handler myHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == 29) {
mDownloadListener.onDownloaded();
return true;
}
return false;
}
});
}
public class I implements DownloadListener {
public I() {
DownloadManager.getInstance().registerDownloadListener(this);
}
#Override
public void onDownloaded() {
Log.e("TAG", "I onDownloaded");
}
}
public class You implements DownloadListener {
public You() {
DownloadManager.getInstance().registerDownloadListener(this);
}
#Override
public void onDownloaded() {
Log.e("TAG", "You onDownloaded");
}
}
public class PATTERNSActivity extends Activity implements DownloadListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new I();
new You();
DownloadManager.getInstance().registerDownloadListener(this);
}
#Override
public void onDownloaded() {
Log.e("TAG","PATTERNSActivity onDownloaded");
}
}
I am expecting to get:
I onDownloaded
You onDownloaded
PATTERNSActivity onDownloaded
But I am getting only:
PATTERNSActivity onDownloaded
What could it be the problem?
You keep registered downloaders in a single instance property:
// Last call's downloadListener wins.
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}
The last one registered is the activity's:
new I(); // First set singleton's property to an instance of I...
new You(); // ...then to an instance of You...
// ...then to the current instance.
DownloadManager.getInstance().registerDownloadListener(this);
Edit based on your comment.
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListeners.add(downloadListener);
}
...
public boolean handleMessage(Message msg) {
if (msg.what != 29) {
return false;
}
for (DownloadListener listener : mDownloadListeners) {
listener.onDownloaded();
}
return true;
}
In your code, this gets executed by calling mDownloadListener.onDownloaded(); in the DownloadManager class.
#Override
public void onDownloaded() {
Log.e("TAG","PATTERNSActivity onDownloaded");
}
In don't see why the onDownloaded methods of the I and YOU class should be executed, they're never called. Only the OnDownloaded method of your Listener is called.
For starters, I think you are not using a list. You just override the value so you will always get the last one:
public void registerDownloadListener(DownloadListener downloadListener) {
mDownloadListener = downloadListener;
}

Categories

Resources