无法从类访问字符串

时间:2017-01-26 15:13:38

标签: java android json api

我想在MainActivity中显示来自另一个字符串的字符串,但字符串将在控制台中打印出来。这是我的代码:

 public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Customer obj, string save, string cancel)
        {
            if (!string.IsNullOrEmpty(save))
            {
                ViewBag.Message = "Customer saved successfully!";
            }
            if (!string.IsNullOrEmpty(cancel))
            {
                ViewBag.Message = "The operation was cancelled!";
            }
            return View("Result", obj);
        }
        public ActionResult Result()
        {
            return View();
        }

上课:

public class MainActivity extends AppCompatActivity {

    Button start;
    public TextView showText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showText=  (TextView)findViewById(R.id.textView);


        start = (Button)findViewById(R.id.button);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               RetrieveFeedTask click1 = new RetrieveFeedTask();

                click1.execute();
                showText.setText(click1.getString());
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

在填充数据之前,您需要finalString。 onPostExecutedoInBackground之后执行,因此您应该将文字视图传递给您的任务,并在onPostExecute

中设置它的值
    public TextView showText;
    public RetrieveFeedTask(TextView showText) { this.showText = showText; }
    protected void onPostExecute(String response) {
        if(response == null) {
            response = "THERE WAS AN ERROR";
        }
        try {
            JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
             finalString = object.getString("text");

             showText.setText(finalString ); // add this
            Log.i("Here",finalString);

        } catch (JSONException e) {

        }

}

答案 1 :(得分:0)

问题在于,var MyComponent = React.createClass({ search: search, // <-- attach global search to your component, // now you can use this.search in renderForm because it is a method of your component renderForm() { ... } }); 您的活动的调用时间早于任务的showText.setText(click1.getString());

<强>解决方案:

创建一个界面:

finalString = object.getString("text");

并在您的活动中实施:

public interface DataCallback {
  void onNewData(String data);
}

创建时将界面传递给asynctask:

public class MainActivity extends ... implements DataCallback

public void onNewData(String data) {
  showText.setText(data);
}

调用RetrieveFeedTask click1 = new RetrieveFeedTask(this); 中任务内的界面,通知活动有新数据:

onPostExecute()