Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - Android Java ViewModel First Read/Write returns null

This simple ViewModel code is working, but the first time the code read/write it returns a null and following read/write the data always one cycle behind. It looks like the it only completes the write once it switches from the timer to the main activity.

Ideally I want to update ViewModel variables from different activities and update the UI based on the observe. I thought updating the ViewModel variables from any source, would cause an update and could be read from any where. I understand .setValue and .postValue is Async but I have tried different time delay, writing and reading at different points and still the same problem.

I thought the problem could be the ViewMidel not initiated at the start, but tried to create it before use and still the same problem.

Any ideas on a fix would be highly appreciated:

MainActivity

public class MainActivity extends AppCompatActivity
{
   private Button buttonBack_activity;
   TextView textView_1;
   public static viewmodelclass model;
   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       // Get a reference to the ViewModel
       model = new ViewModelProvider(this).get(viewmodelclass.class);

    try{

        textView_1 = findViewById(R.id.textView1);
        buttonBack_activity = (Button) findViewById(R.id.button1);
        buttonBack_activity.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
                Log.d("Debug", "Button pressed");
                model.writedatatest("send text");
            }


        });

        TimerStateMachineClass mActivity= new TimerStateMachineClass();
        mActivity.starttimer();
        LiveData<String> shoppingList = model.getshoppinglist();
        model.getshoppinglist().observe(this, new Observer<String>(){
            @Override
            public void onChanged(@Nullable String s)
            {
                textView_1.setText(s);
                Log.d("Debug", "String has been updated ->"+s);
            }
        });


    }catch (Exception e)
    {
        e.printStackTrace();
    }

    }

@Nullable
@Override
public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {


    return super.onCreateView(name, context, attrs);
}
}

TimerStateMachineClass

import static com.example.viewmodellivedata_sandpit.MainActivity.model;

public class TimerStateMachineClass extends AppCompatActivity {

public Timer myTimer;
int coutner;

public void starttimer()
{
    Log.w("Debug", "Function start timer");
    myTimer = new Timer();
    coutner = 0;
    myTimer.schedule(new TimerTask() {

        public void run() {
            TimerMethod();
        }

    }, 0, 1000);
}

public void TimerMethod()
{
   // LiveData<String> shoppingList1 = model.getshoppinglist();
    coutner++;
    Log.w("Debug", "coutner ->" + coutner);
    model.writedatatest(Integer.toString(coutner));
    model.MV_int = coutner;
    Log.w("Debug", "Timer execution model.getshoppinglist( ->" + model.getshoppinglist());
    Log.w("Debug", "Timer execution model.MV_int ->" + model.MV_int);
}
}

viewmodelclass

public class viewmodelclass extends ViewModel {
private MutableLiveData<String> shoppingList = new MutableLiveData<>();

public int MV_int;

public MutableLiveData<String> getshoppinglist() {
    Log.w("Debug", "inside MutableLiveData<String> getshoppinglist()");
    if (shoppingList == null) {
        Log.w("Debug", "shoppingList == null");
       shoppingList = new MutableLiveData<>();
       /// writedatatest("test message");
    }
    if(shoppingList != null) {
        Log.w("Debug", "shoppingList != null");
        return shoppingList;
    }
    return shoppingList;
}

public void writedatatest(String incomingdata)
{
    Log.w("Debug", "Inside the get shopping list 1 -> "+shoppingList.getValue());
    shoppingList.postValue(incomingdata);
}

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...