我创建了一个全局变量idprof,然后将其设置为id(您可以在protected void doinbackground中找到它)。我想把它的值放在公共String getCourseFromDB方法的namevaluepairs中,但它不起作用。你能帮助我吗,我有时会在方法之间传递变量时感到困惑(你可以在我的代码中看到我的评论)
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
}
}
答案 0 :(得分:0)
试着猜测你的代码。请找到以下说明
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
因为它现在是类变量,因此共享给该类的所有实例。
请检查此说明,您可能会对您的问题有所了解。