1
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,以访问上述类中的对话框并显示 toast。我该怎么做。请帮帮我

        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 异常

4

3 回答 3

1

您可以将 Activity 的实例传递给另一个类,然后从那里使用该 Activity 实例,您可以在原始 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");

}
于 2013-07-24T09:37:41.067 回答
0

那么你可以将你的ui元素的引用传递给你的java类吗?使用构造函数或设置器。

示例: up= new Upload(this, uploadButton, messageText);

然后在您的对象中进行更新

于 2013-07-24T09:32:31.487 回答
0

首先,您应该将活动上下文的实例传递给非活动类。您可以使用此上下文访问 ui 组件。然后你可以实现这个

yourContextObject.runOnUiThread(new Runnable() {
    public void run()
    {
        Toast.makeText(yourContextObject, "some text",Toast.LENGTH_LONG).show();
    }
});
于 2013-07-24T09:34:05.620 回答