I am having great difficulty to convert a non static handler into a static handler. I have tried various approaches but every time I end up in doing something messy. In the provided code please correct me how to achieve this. I did tried one example and I had to change most of my variables and functions into static which were referenced from the handler. But still i got additional errors.
public class MainActivity extends Activity implements Runnable {
private TextView textView;
boolean connectionToTupleSpace=false;
private TupleSpace ts = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myText);
textView.setText("it is testing");
findViewById(R.id.login_button).setOnClickListener(buttonLogin);
}
public final Button.OnClickListener buttonLogin = new Button.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(MainActivity.this);
thread.start();
}
};
@Override
public void run() {
Looper.prepare();
try {
ts = new TupleSpace("192.168.1.100",2525,"Orientation");
connectionToTupleSpace = true;
}catch (TupleSpaceException e) {
connectionToTupleSpace = false;
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
private Looper myLooper;
@Override
public void handleMessage(Message msg) {
if(connectionToTupleSpace == true)
{
Toast.makeText(getBaseContext(), " Tuple Space Server is Connected", Toast.LENGTH_SHORT).show();
showTuples();
}
else
{
/*Toast.makeText(getBaseContext(), " No connection to Tuple Space Server", Toast.LENGTH_SHORT).show();*/
showDialog("Connection", "there is no connection");
}
myLooper = Looper.myLooper();
Looper.loop();
myLooper.quit();
}
};
public void showTuples()
{
Tuple template = new Tuple(String.class, Integer.class);
Tuple[] returnTuple = null;
try {
returnTuple = ts.readAll(template);
} catch (TupleSpaceException e) {
e.printStackTrace();
}
int num = returnTuple.length;
if (num == 0)
System.out.print("No tuples in the space");
else
for(int i=0;i<num;i++)
{
System.out.print("\nTotal tuples are" + num+"\nYou found " + returnTuple[i]);
showDialog(returnTuple[i].getField(0).toString(),returnTuple[i].getField(1).toString());
}
}
private void showDialog(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", null);
builder.show();
}
}