0

Hello i am new to android.i was creating a simple google cloud appengine app with endpoint.i was using using this tutorial https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints .but the thing is i want to show the result in a textview not in a toast.


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 (main activity)


        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();
        }
    }

My 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;
    }
}
Mrinmoy
  • 13
  • 4

6 Answers6

0

Pass TextView as parameter to Constructor of EndpointsAsyncTask in which you want to show result as done below.

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);
        }
    }

call AsyncTask from you Activity or Fragment

new EndpointsAsyncTask(context,yourTextView).execute(yourParams);
Chintan Bawa
  • 1,376
  • 11
  • 15
0

In EndpointsAsyncTask.java replace

 @Override
    protected void onPostExecute(String result) {

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

With

 @Override
    protected void onPostExecute(String result) {

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

change to:new EndpointsAsyncTask(tv1) in GoogleAppEngActivity class

and add next code to EndpointsAsyncTask class

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

and replace Toast.makeText(context, result, Toast.LENGTH_LONG).show(); to view.setText(result);

adrbtk
  • 4,470
  • 1
  • 12
  • 11
0

I'll suggest making EndpointsAsyncTask an inner class of your activity. Get a reference to textView in postExecute and update it there. Something like this

Community
  • 1
  • 1
prashant
  • 3,570
  • 7
  • 40
  • 50
0

Ideally, the UI elements belonging to an activity should be changed in the activity itself, and no where else. Try following the presentation pattern.

A small example: 1. Create an interface - ActivityPresenter with methods signifying events with parameters as the input data required for the views to change. An example would be:

void onServerResponse(ServerResponse resp);
  1. Make the activity implement this interface. That is, you define what UI changes to make in the activity when the server response arrives.

  2. When you call a service / asynctask from the activity to do some task asynchronously for you, send the activity presenter reference. Call the presenter.onServerResponse(response) from your service / asynctask.

shiladitya
  • 2,290
  • 1
  • 23
  • 36
0

For this purpose you can use callback interface:

Create a public interface:

public interface AsyncTaskResponse {

void asyncTaskFinish(String output);
}

Now override the method of callback interface and define the action need to do i.e set the TextView value. After that pass it to async task class:

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;
        final 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(new AsyncTaskResponse() {
        @Override
        public void asyncTaskFinish(String response) {
            tv1.setText(response);
        }
    };).execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
                  //  tv1.setText( new EndpointsAsyncTask().);
                }
            });

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

        public TextView getTextView(){

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


    }

Now in async task class call the Callback interface method and pass response String to set edit text value:

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;
    private AsyncTaskResponse asyncCallback;
    public EndpointsAsyncTask(AsyncTaskResponse asyncTaskResponse){
          asyncCallback = asyncTaskResponse;
    }
    @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();
           asyncCallback.asyncTaskFinish(result); // call the method of callback interface
    }
}
Rohit Sharma
  • 2,017
  • 1
  • 20
  • 22