public class UploadToServer extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
up= new Upload(this);
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
up.uploadFile(uploadFilePath);
}
}).start();
}
});
我需要从另一个名为UPLOAD.ineed的类访问此类ui,以访问上述类中的对话框并显示吐司。我怎么能这样做.plz帮帮我
public class Upload {
public Upload(UploadToServer context) {
context=context;}
context.runOnUiThread(new Runnable() {public void run() {
String msg = "yes";
context.messageText.setText(msg);
Toast.makeText(context, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
}); }
这就是我尝试过的。是的,我想要做的就是打印一个Toast。但当我知道这个时我得到了NULPOINT异常
答案 0 :(得分:1)
您可以将Activity的实例传递给另一个类,并从那里使用该活动实例,您可以在原始活动中调用showMyToast()方法。
class MyActivity extends Activity{
// activity methods etc..
public void showMyToast(String message){
runOnUiThread(new Runnable() {
@Override
public void run() {
// write code to show toast
Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG).show();
}
});
}
class MyOtherClass{
MyActivity myActivity;
MyOtherClass(MyActivity myActivity){
this.myActivity=myActivity;
}
// To call the showMyToast() of Activiy do like this:
// myActivity.showMyToast("This is a toast");
}
答案 1 :(得分:0)
然后你可以将你的ui元素的引用传递给你的java类?使用构造函数或使用setter。
例子:up = new Upload(this,uploadButton,messageText);
然后在对象中进行更新
答案 2 :(得分:0)
首先,您应该将活动上下文的实例传递给非活动类。您可以使用此上下文访问ui组件。然后你可以实现这个
yourContextObject.runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(yourContextObject, "some text",Toast.LENGTH_LONG).show();
}
});