Hello, tell me how to correctly transfer the values ​​of a variable, here is the code

public class MainActivity extends WorkService { public int buy; public class TextRequestListener implements RequestListener<String> { @Override public void onRequestFailure(SpiceException spiceException) { //Toast.makeText(MainActivity.this, "failure", Toast.LENGTH_SHORT).show(); Log.d(TAG,"failure"); } @Override public void onRequestSuccess(final String result) { //Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show(); Log.d(TAG,"success"); Log.d(TAG,result); //парсинг ответа, JSON try { dataJsonObj = new JSONObject(result); JSONObject sys = dataJsonObj.getJSONObject("query"); JSONObject sys1 = sys.getJSONObject("results"); JSONObject sys2 = sys1.getJSONObject("rate"); buy = sys2.getInt("Ask"); } catch (JSONException e) { e.printStackTrace(); } Log.d(TAG,"buy = " + buy); } } public int getBuy(){ return buy; }` 

The TextRequestListener class is nested in the MainActivity class. I need to pass this line to buy = sys2.getInt ("Ask"); to another class. Tried to do so, but it does not work.

 MainActivity a = new MainActivity(); MainActivity.TextRequestListener b = a.new TextRequestListener(); int buy = b.buy; Log.d(TAG, "buy= " + buy); 

or

 MainActivity main = (MainActivity)getActivity(); int s = main.getBuy(); 

in two cases I get zero.

  • “to another class” is another activation / service, or is it just another object in the same activation? - zRrr 1:01 pm
  • in fragment, onCreateView method - Timur_St

2 answers 2

There is a special getActivity(); method in the getActivity(); which returns to you the activity that this fragment is attached to. You have many ways to get the variable you need, for example, by creating a getter:

 public int getBuy(){ return buy; } 

And call like this: int buy = getActivity().getBuy(); // pseudocode, did not check, but this thought.

ps Never create an instance of activation - you will not succeed.

MainActivity a = new MainActivity(); - this is never necessary.

  • does not work, in MainActivity created public int getBuy () {return buy; } - Timur_St 3:51 pm
  • then in the fragment it called MainActivity main = (MainActivity) getActivity (); int s = main.getBuy (); I also get 0. I posted the full code, what am I doing wrong ??? - Timur_St pm
  • By the way, did the JSON coming to you be checked? Maybe there is 0 for you and it comes? - Silento
  • checked, in the class TextRequestListener, the line Log.d (TAG, "buy =" + buy); comes the number 337 - Timur_St

Try this: Activate:

  Bundle bundle = new Bundle(); bundle.putString("название", переменная); фрагмент.setArguments(bundle); 

In the fragment:

  Bundle bundle = this.getArguments(); перменная в фрагменте = bundle.getString("название");