【问题标题】:passing values from one class to another android将值从一个类传递到另一个 android
【发布时间】:2015-01-02 15:33:20
【问题描述】:

我试图将值从一个类传递到另一个类。我不能使用意图,因为该类扩展了一个自定义库,并且我不能使用包和东西(如果我是对的)。这是我尝试过的。

我有 2 个类 callhelper.java 用于监控传入和传出调用。当触发操作时,它会从 DB 填充数据并将其发送到另一个类,并在其中显示一个弹出窗口。

呼叫助手类

public void onReceive(Context context, Intent intent) {
             String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                String out = null;

            String query = "select * from ReminderTable" ;
            Cursor c2=   enter.selectQuery(query);
             //GetData and place it in out

    //Instance of 2nd class PopUpDisplay set = new PopUpDisplay();
    //passing out to function   set.setData(out);
    // calling 2nd class to display popup //  StandOutWindow.show(context, PopUpDisplay.class, StandOutWindow.DISREGARD_ID);
                     Toast.makeText(ctx, out, Toast.LENGTH_LONG).show();
             enter.close();

在 popupdisplay 类中,我有一个全局变量和一个方法setData(),它将值设置为变量。

@Override
public void createAndAttachView(int id, FrameLayout frame) {
        // create a new layout from body.xml
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
     view = inflater.inflate(R.layout.simple, frame, true);
     tv1 = (TextView)view.findViewById(R.id.tvdisplaypoptitle);
        tv = (TextView) view.findViewById(R.id.tvdisplaypopnote);

        tv.setText(note);
        tv1.setText("Title");
    btn1 = (Button) view.findViewById(R.id.btn3);
    btn1.setOnClickListener(this);

}

public void setData(String a){
        note = a;
}

createAndAttachView 是我想要设置 textview 以显示从上一个类传递的消息的方法。该方法设置弹出窗口的布局。弹出窗口在 CallHelper 类中通过StandOutWindow.show() 方法调用。

所以,问题是,每当它显示弹出窗口时,它都会显示null。我怎样才能让它显示我的消息而不是 null。应该添加哪些额外的代码?请帮助解决这个问题。提前致谢。

【问题讨论】:

  • 如何使用全局常量变量?或共享偏好?你试过吗?
  • 我没有尝试共享首选项,我是 android 新手,你能指导我吗? @diva

标签: java android


【解决方案1】:

由于这是运行时数据,因此不建议使用 sharedpreference。创建一个名为 RunTimeData.java 的类。在这里将所有必需的变量声明为静态。每当您需要保存数据时,请将其保存到这些变量中。使用其他类中的数据后,请确保将变量设置为空。

示例。

public class RunTimeData{
public static String name=null;

}

在分配数据时,请按如下方式使用。

RuntimeData.name="yyyyy";

使用数据时使用如下。

TextView tv=new TextView(); tv.setText(RunTimeData.name);

RunTimeData.name=null;

当您确定不会在某处再次使用该值时释放该变量。

【讨论】:

    【解决方案2】:

    创建一个SharedPrefencesHelper类,让它拥有你想在你的各个类中使用的所有全局变量,然后你可以通过简单的getter方法在你的应用程序的任何地方使用这些变量。查找SharedPreferences,它非常容易使用。

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2018-10-09
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多