0
我非常難以將非靜態處理程序轉換爲靜態處理程序。 我嘗試了各種方法,但每次我最終都在做一些雜亂的事情。 在提供的代碼中,請糾正我如何實現這一點。我曾經嘗試過一個例子,我不得不將大部分變量和函數都改成靜態的,這些靜態變量是從處理程序引用的。但仍然有額外的錯誤。如何將非靜態處理程序轉換爲靜態處理程序
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();
}
}
實際上,這是不可能的,因爲OP調用匿名內部類中的非靜態方法,比如'showTuples()'。 –
他也應該對活動上下文使用弱引用。 – Raghunandan
這不是必要的。因爲位於此活動內的處理程序的引用,並且最終活動將被此引用處理程序銷燬。 – IronBCC