简体   繁体   English

如何从一个方法更改静态类变量的值,然后从另一个方法获取它呢?

[英]How can I change the value of a static class variable from a method, then get it from an other method?

My problem is that I cannot convert from void to String. 我的问题是我无法从void转换为String。 I can't use a return in my method onResponse , so I decided to use a global variable, I change it's value from ReadToken method, then I call this method in onResponse , and get the new value of global token_value variable. 我不能在方法onResponse中使用return,所以我决定使用全局变量,我从ReadToken方法更改了它的值,然后在onResponse中调用了此方法,并获得了全局token_value变量的新值。 But I always get null value ! 但是我总是得到空值!

public class TestPagerAdapter extends PagerAdapter {

 static String token_value;

Context context;
List<PagerModel> pagerArr;
LayoutInflater inflater;

public TestPagerAdapter(Context context, List<PagerModel> pagerArr) {
    this.context = context;
    this.pagerArr = pagerArr;
    inflater = ((Activity)context).getLayoutInflater(); }


@Override
public int getCount() {
    return pagerArr.size();
}


@Override
public Object instantiateItem(ViewGroup container, int position) {
    View view= inflater.inflate(R.layout.pop_up,container,false);

     TextView text_task=view.findViewById(R.id.textView8);
    TextView text_child_parent=view.findViewById(R.id.textView9);
     TextView edit_child_parent=view.findViewById(R.id.textView10);
    TextView text_deadline=view.findViewById(R.id.textView12);
     TextView text_avancement=view.findViewById(R.id.textView14);
     Button button=view.findViewById(R.id.button3);
      final Spinner s = view.findViewById(R.id.spinner2);
    ImageView rl=view.findViewById(R.id.imm11);



    view.setTag(position);
    ((ViewPager)container).addView(view);
    final PagerModel model=pagerArr.get(position);
    text_task.setText(model.getText_task());
    text_avancement.setText(model.getText_avancement());
    text_deadline.setText(model.getText_deadline());
    text_child_parent.setText(model.getText_child_parent());
    edit_child_parent.setText(model.getEdit_child_parent());
    button.setText(model.getButton());


    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context,R.array.avancement,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(adapter);



    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String d= model.getText_deadline();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(context.getResources().getString(R.string.BaseUrl))
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            final MyInterface myInterface=retrofit.create(MyInterface.class);

             final String st=s.getSelectedItem().toString();
                Call<Success> call22= myInterface.UpdateTask(model.getId(),st);
                call22.enqueue(new Callback<Success>() {
                    @Override
                    public void onResponse(Call<Success> call, Response<Success> response) {
                        Success success = response.body();
                        int s=success.getCode();
                        if(s==0)  Toasty.error(context,"Error", Toast.LENGTH_SHORT).show();

                        else {
                            Toasty.success(context,"Success update",Toast.LENGTH_SHORT).show();

                            String date = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
                            ReadToken(model.getEdit_child_parent());

                            Toast.makeText(context, token_value,Toast.LENGTH_SHORT).show();

                            context.startActivity(new Intent(context, MainActivity.class));
                        }
                    }

                    @Override
                    public void onFailure(Call<Success> call, Throwable t) {
                        Toast.makeText(context,"failure",Toast.LENGTH_SHORT).show();

                    }
                });


        }
    });

    return view;
}


@Override
public boolean isViewFromObject(View view, Object object) {
    return view==((View)object);
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager)container).removeView((View)object);
}




public void ReadToken(String uid){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(context.getResources().getString(R.string.BaseUrl))
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    final MyInterface myInterface=retrofit.create(MyInterface.class);

    Call<List<User>> call55 = myInterface.readToken(uid);
    call55.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(Call<List<User>> call, Response<List<User>> response) {

            List<User> users = response.body();
            String token=users.get(0).getToken();
             token_value =token;
            Toast.makeText(context,"Token ok",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<List<User>> call, Throwable t) {
            Toast.makeText(context,"Token failure",Toast.LENGTH_SHORT).show();

        }
    });
}

} }

You read your token in another thread because Retrofit.enqueue() works asynchronously. 您在另一个线程中读取令牌,因为Retrofit.enqueue()是异步工作的。 So, you need to do all the logic with your token inside onResponse() which is inside method ReadToken() . 因此,您需要在方法ReadToken()内的onResponse()对令牌进行所有逻辑处理。

Store the response in the shared preferences. 将响应存储在共享首选项中。 And use it wherever you want. 随时随地使用它。

SharedPreferences sharedPref = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit(); 
preferencesHelper.editor.putString(“response”, response.toString()).commit();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从另一个类的静态方法更改静态变量的值 - how to change the value of a static variable from a static method of another class 如何从方法内部更改变量的值? - How can I change the value of a variable from inside a method? 如何从匿名内部类更改侧方法中变量的值? - How can I change value of variable in side method from anonymous inner class? 如何从一个方法,另一个类的变量数据中读取公共静态变量并获取更新的数据 - How do I read in a public static, with variable data from a method, from another class and get updated data 从其他类调用静态方法时,如何更改对象的值? - How would I change an object's value when calling a static method from a different class? 如何从另一个类的静态方法获取抽象类的子类的实例? - How can I get an instance of a subclass of abstract class from a static method of another class? Android-如何将mainActivity中的方法与另一个类的静态布尔变量同步? - Android - How can i sync a method in mainActivity with a static boolean variable from another class? 使用其他类的公共静态HashTable的同步方法。 如何使该方法线程安全? - synchronized method that use a public static HashTable from other class. How can I make this method thread safe? 如何从子类的静态方法获取类? - How do I get the class from a static method of a subclass? 如果我设置一个具有从另一个类定义的2个参数的类方法,我如何获得在另一个类上定义的值? - If I set up a class method with 2 parameters defined from the other class, how can I get the values defined on the other class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM