【问题标题】:How to pass value from protected method to a public method?如何将值从受保护的方法传递给公共方法?
【发布时间】:2018-04-19 20:05:06
【问题描述】:

我创建了一个全局变量 idprof,然后将其设置为一个 id(您可以在受保护的 void doinbackground 中找到它)。我想将它的值放在公共 String getCourseFromDB 方法中的 namevaluepairs 中,但它不起作用。你能帮我吗,我有时在方法之间传递变量时感到困惑(你可以在我的代码中看到我的 cmets)

public class BackgroundWorker extends AsyncTask<String,String,Void>{
Context context; 
String command;

String idprof=""; // this is the global variable 

BackgroundWorker (Context ctx,String command){ 

    context = ctx;
    this.command = command;
}

@Override
protected Void doInBackground(String... arg0) {
    // TODO Auto-generated method stub


        intent = new Intent(context, MainActivity.class);
        extras.putString("id", id.trim());

        idprof=id.trim(); //this is the value i want to get

        intent.putExtras(extras);
        context.startActivity(intent);
        }

}
return null;
}
public String getCourseFromDB() {
    try {
        List<NameValuePair> nameValuePairs2;
        nameValuePairs2 = new ArrayList<NameValuePair>(2);
        nameValuePairs2.add(new BasicNameValuePair("id",idprof)); // this is where i want to pass it


}
}

【问题讨论】:

标签: java android eclipse


【解决方案1】:

只是试图猜测您的代码。请看下面的解释

public class Main {
    String str = null;
    public static void main(String[] args) {
        Main m1 = new Main();
        m1.setTheValueHere();
        m1.getTheValueHere("called by m1");

        Main m2 = new Main();
        m2.getTheValueHere("called by m2");
    }

    protected void setTheValueHere(){
        str = "hello";
    }

    public void getTheValueHere(String objName) {
        System.out.println(objName +" --- "+str);
    }
}

O/P:

called by m1 --- hello
called by m2 --- null

这里的String str 是一个实例变量。对于对象m1,打印了hello,因为set 和get 方法都被同一个对象m1 调用。 m1 设置的值不适用于对象 m2,因为它是不同的对象实例,因此打印了 m2 null

如果您将String str 更改为static 变量为static String str = null;,输出将是

called by m1 --- hello
called by m2 --- hello

因为它现在是类变量,因此共享给该类的所有实例。

请查看此说明,您可能会对您的问题有所了解。

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2016-03-19
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多