从android中的其他类访问TextView

时间:2016-01-15 20:01:53

标签: android textview google-cloud-endpoints

您好我是android.i的新手正在创建一个简单的google cloud appengine应用程序,使用endpoint.i正在使用本教程https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints。但问题是我想在textview中显示结果而不是在烤面包。

Layout.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:id="@+id/lay1">

    <EditText
        android:id="@+id/edt1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="Enter Number"
        android:inputType="number"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/edt2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="Enter Number"
        android:inputType="number"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="Result Will be Here"
        android:textSize="24sp" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="Add" />

    </LinearLayout>

GoogleAppEngActivity.java(主要活动)

        package com.ontech.googleappengine;

        import android.content.Context;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Pair;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;

        public class GoogleAppEngActivity extends AppCompatActivity {

            Button btnAdd;
            TextView tv1;
            //String val1,val2;
            EditText edt1,edt2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_google_app_eng);


                edt1=(EditText)findViewById(R.id.edt1);
                edt2=(EditText)findViewById(R.id.edt2);
                tv1=(TextView)findViewById(R.id.tv1);
                btnAdd =(Button)findViewById(R.id.btnAdd);
                btnAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String temp = "";
                        temp = edt1.getText().toString();
                        temp += "+";
                        temp += edt2.getText().toString();

                        new EndpointsAsyncTask().execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
                      //  tv1.setText( new EndpointsAsyncTask().);
                    }
                });

               // new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));
            }

            public TextView getTextView(){

                TextView txtView=(TextView)findViewById(R.id.tv1);
                return txtView;
            }


        }

EndpointsAsyncTask.java

    package com.ontech.googleappengine;

    //package com.ontech.googleappengine;

    import android.content.Context;
    import android.os.AsyncTask;
    import android.text.Layout;
    import android.util.Pair;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.api.client.extensions.android.http.AndroidHttp;
    import com.google.api.client.extensions.android.json.AndroidJsonFactory;
    import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
    import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
    import com.ontech.myapplication.backend.myApi.MyApi;

    import java.io.IOException;

    /**
     * Created by on 05-11-2015.
     */
    public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
        private static MyApi myApiService = null;
        private Context context;

        @Override
        protected String doInBackground(Pair<Context, String>... params) {
            if (myApiService == null) {  // Only do this once
              /*  MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                        new AndroidJsonFactory(), null)
                        // options for running against local devappserver
                        // - 10.0.2.2 is localhost's IP address in Android emulator
                        // - turn off compression when running against local devappserver
                        .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                        .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                            @Override
                            public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                                abstractGoogleClientRequest.setDisableGZipContent(true);
                            }
                        });*/

                MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                        .setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
                // end options for devappserver

                myApiService = builder.build();
            }

            context = params[0].first;
            String name = params[0].second;

            try {
                return myApiService.sayHi(name).execute().getData();
            } catch (IOException e) {
                return e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {

            Toast.makeText(context, result, Toast.LENGTH_LONG).show();
        }
    }

我的endpoint.java

package com.ontech.myapplication.backend;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;

import javax.inject.Named;

/**
 * An endpoint class we are exposing
 */
@Api(
        name = "myApi",
        version = "v1",
        namespace = @ApiNamespace(
                ownerDomain = "backend.myapplication.ontech.com",
                ownerName = "backend.myapplication.ontech.com",
                packagePath = ""
        )
)
public class MyEndpoint {

    /**
     * A simple endpoint method that takes a name and says Hi back
     */
    @ApiMethod(name = "sayHi")
    public MyBean sayHi(@Named("name") String name) {
        MyBean response = new MyBean();

        String val1, val2;
        val1 = name.substring(0, name.indexOf("+"));
        val2 = name.substring(name.indexOf("+") + 1);
        int res = Integer.parseInt(val1) + Integer.parseInt(val2);

       // response.setData("Hi, " + name);
        response.setData(Integer.toString(res));
        return response;
    }

}

MyBean.java

package com.ontech.myapplication.backend;

/**
 * The object model for the data we are sending through endpoints
 */
public class MyBean {

    private String myData;
        public String getData() {
        return myData;
    }

    public void setData(String data) {
        myData = data;
    }
}

6 个答案:

答案 0 :(得分:0)

TextView 作为参数传递给 EndpointsAsyncTask 的构造函数,并在其中显示结果,如下所示。

public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
        private static MyApi myApiService = null;
        private Context context;
        private TextView textView

public EndpointsAsyncTask(Context context,TextView mtextView) {
    // TODO Auto-generated constructor stub
            this.context=context;
            this.textView=mtextView;
}

        @Override
        protected String doInBackground(Pair<Context, String>... params) {
            if (myApiService == null) {  // Only do this once
              /*  MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                        new AndroidJsonFactory(), null)
                        // options for running against local devappserver
                        // - 10.0.2.2 is localhost's IP address in Android emulator
                        // - turn off compression when running against local devappserver
                        .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                        .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                            @Override
                            public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                                abstractGoogleClientRequest.setDisableGZipContent(true);
                            }
                        });*/

                MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                        .setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
                // end options for devappserver

                myApiService = builder.build();
            }

            context = params[0].first;
            String name = params[0].second;

            try {
                return myApiService.sayHi(name).execute().getData();
            } catch (IOException e) {
                return e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {

            Toast.makeText(context, result, Toast.LENGTH_LONG).show();
            textView.setText(result);
        }
    }

从您的Activity或Fragment

调用AsyncTask
new EndpointsAsyncTask(context,yourTextView).execute(yourParams);

答案 1 :(得分:0)

在EndpointsAsyncTask.java中替换

 @Override
    protected void onPostExecute(String result) {

        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    }

使用

 @Override
    protected void onPostExecute(String result) {

        GoogleAppEngActivity.getTextView().setText(result);
    }

答案 2 :(得分:0)

更改为:GoogleAppEngActivity类中的new EndpointsAsyncTask(tv1)

并将下一个代码添加到EndpointsAsyncTask

TextView view;
public EndpointsAsyncTask(TextView tv) {
    view = tv;
}

并替换Toast.makeText(context, result, Toast.LENGTH_LONG).show();view.setText(result);

答案 3 :(得分:0)

我建议将EndpointsAsyncTask作为您活动的内部类。在postExecute中获取对textView的引用并在那里更新它。像this

这样的东西

答案 4 :(得分:0)

理想情况下,属于活动的UI元素应该在活动本身中更改,而不是在其他位置更改。请尝试按照演示模式进行操作。

一个小例子: 1.创建一个接口 - ActivityPresenter,其方法表示使用参数作为视图更改所需的输入数据的事件。一个例子是:

void onServerResponse(ServerResponse resp);
  1. 使活动实现此接口。也就是说,您可以定义服务器响应到达时在活动中进行的UI更改。

  2. 当您从活动中调用service / asynctask为您异步执行某项任务时,请发送活动presenter参考。从您的服务/ asynctask中调用presenter.onServerResponse(response)

答案 5 :(得分:0)

为此,您可以使用回调接口:

创建公共接口:

super.onCreate(savedInstanceState);

现在覆盖回调接口的方法并定义需要执行的操作,即设置TextView值。之后将其传递给异步任务类:

addPreferencesFromResource(R.xml.preferences);

现在在异步任务类中调用Callback接口方法并传递响应String以设置编辑文本值:

public interface AsyncTaskResponse {

void asyncTaskFinish(String output);
}
相关问题