Autore Topic: Google Cloud Endpoints + App Engine  (Letto 352 volte)

Offline Caco85

  • Nuovo arrivato
  • *
  • Post: 15
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Motorola moto g
  • Sistema operativo:
    Windows 7
Google Cloud Endpoints + App Engine
« il: 07 Settembre 2014, 09:45:11 CEST »
0
Ciao ragazzi ho un problema con la mia app che utilizza app engine e google cloud endpoints. Il codice non da errore ma quando faccio service.register non succede nulla al mio backend che invece dovrebbe salvare il gcm id. Non ho idea di quale sia il mio errore, quindi spero che mi potrete aiutare.
Questa è la mia activity principale:
Codice (Java): [Seleziona]
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.appspot.atomic_box_656.sand.*;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;


import java.io.IOException;
import java.util.Collection;

import it.caco.sandproject.androidclient.MainApplication;
import it.caco.sandproject.androidclient.R;
import it.caco.sandproject.androidclient.adapters.ViewPagerAdapter;
import it.caco.sandproject.androidclient.gcm.RegIdManager;


public class MainActivity extends SherlockFragmentActivity  {


    private ActionBar actionBar;
    private ViewPager viewPager;
    private MenuItem add_contact_button;
    private Boolean logged = false;
    private MenuItem edit_contacts;
    private MenuItem ok_button;
    private MenuItem cancel_button;

    private static final int REQUEST_ACCOUNT_PICKER = 2;

    private Boolean rememberToRegister;
    private static MainApplication sInstance;
    public static Boolean doINeedToRegister= false;

    private GoogleCloudMessaging gcm= null;
    private final String SENDER_ID = "5*********6";
    RegIdManager regIdManager = new RegIdManager();

    private RegisterGcmId registerGcmId;
    private String TAG = "MAIN APPLICATION GCM";
    public static Sand.Builder builder;
    public static Sand service;
    private final String APP_NAME = "Sand";
    public static SharedPreferences settings;
    public static GoogleAccountCredential credential;
    private final String SHARED_PREF_ACCOUNT = "ACCOUNT_PREF";
    private final String ACCOUNT_NAME = "ACCOUNT_NAME";
    static final String WEB_CLIENT_ID = "6**************************com";
    private String accountName;





    Context context;
    ProgressDialog dialog;

    public String reg_id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (TextUtils.isEmpty(reg_id)){




        builder = new Sand.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), null).setApplicationName(APP_NAME);
        service = builder.build();

        credential = GoogleAccountCredential.usingAudience(this,
                "server:client_id:" + WEB_CLIENT_ID);
        settings = getSharedPreferences(SHARED_PREF_ACCOUNT,MODE_PRIVATE);

        setAccountName(settings.getString(ACCOUNT_NAME, null));
        if (credential.getSelectedAccountName() != null) {
            // Already signed in, begin app!
            Toast.makeText(this, "Logged in with : " + credential.getSelectedAccountName(), Toast.LENGTH_SHORT).show();
            //Toast.makeText(getBaseContext(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()),Toast.LENGTH_SHORT).show();
        }
            else
        {
            chooseAccount();
        }
            RegIdManager.storeRegistrationId(this,"");
            reg_id = RegIdManager.getRegistrationId(this);
            Log.d(TAG,"REG ID: "+reg_id);

            if (TextUtils.isEmpty(reg_id)){
                registerGcmId = new RegisterGcmId();
                Log.d(TAG,"Progress Dialog");
                dialog = ProgressDialog.show(this, "", "Getting GCM id...", false, true);
                context = this;
                registerGcmId.execute((Void) null);
            }

        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.activity_main, (Menu) menu);
        actionBar = getSupportActionBar();
        //actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        ok_button = (MenuItem) menu.findItem(R.id.ok_button);
        edit_contacts = (MenuItem)menu.findItem(R.id.edit_contacts);
        add_contact_button = (MenuItem) menu.findItem(R.id.add_contact);
        cancel_button = (MenuItem) menu.findItem(R.id.cancel_button);
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setOnPageChangeListener(onPageChangeListener);
        viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
        addActionBarTabs();


        return super.onCreateOptionsMenu(menu);
    }

    private ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            actionBar.setSelectedNavigationItem(position);
        }
    };

    private void addActionBarTabs() {
        actionBar = getSupportActionBar();
        String[] tabs = {"Chats", "Contacts"};
        for (String tabTitle : tabs) {
            ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
                    .setTabListener(tabListener);
            actionBar.addTab(tab);

        }

        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }


    private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
           viewPager.setCurrentItem(tab.getPosition());
           switch (tab.getPosition()) {
                case 0:
                    add_contact_button.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                    edit_contacts.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                    break;

                case 1:
                    add_contact_button.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                    edit_contacts.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                    break;

            }


        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

            switch (tab.getPosition()) {
                case 0:
                    break;

                case 1:

                    //ok_button.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                    //cancel_button.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                    break;

            }
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
           switch (tab.getPosition()) {
                case 0:
                    edit_contacts.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                    add_contact_button.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                    break;
                case 1:
                    add_contact_button.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                    edit_contacts.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                    break;


            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_contact:
                onClickAddContact();
                return true;
            case R.id.edit_contacts:
                onClickEditContacts();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }


   private void onClickAddContact(){
       Intent i = new Intent(this,AddContactActivity.class);
       startActivity(i);
   }

    private void onClickEditContacts(){
        Intent i = new Intent(this,EditContactsActivity.class);
        startActivity(i);
    }


    private void setAccountName(String accountName) {
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("ACCOUNT_NAME", accountName);
        editor.commit();
        credential.setSelectedAccountName(accountName);
        this.accountName = accountName;
    }


    void chooseAccount() {
        try
        {
            startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
        }
        catch (ActivityNotFoundException e)
        {

            Toast.makeText(this, "ActivityNotFoundException in method chooseaccount() ", Toast.LENGTH_LONG).show();

            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ACCOUNT_PICKER:
                if (data != null && data.getExtras() != null) {
                    String accountName =
                            data.getExtras().getString(
                                    AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        setAccountName(accountName);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(ACCOUNT_NAME, accountName);
                        editor.commit();
                        // User is authorized.
                    }
                }
                break;
        }
    }


    class RegisterGcmId  extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                    Log.i("GCM","gcm.toString(): "+gcm.toString());
                }
                reg_id = gcm.register(SENDER_ID);
                Log.i("GCM","Reg Id: "+reg_id);
                service.register(reg_id);   // QUI C'è QUALCOSA CHE NON VA
                regIdManager.storeRegistrationId(context, reg_id);
                dialog.dismiss();


            } catch (IOException ex) {
                Log.e("GCM","Error :" + ex.getMessage());
                dialog.dismiss();
            }
            catch (NullPointerException ne){
                Log.e("GCM","Error null pointer :" );
                ne.printStackTrace();
                dialog.dismiss();
            }


            return null;
        }
    }


    }

E questo è il mio metodo register caricato su app engine:
Codice (Java): [Seleziona]
@ApiMethod(name = "register", path = "register", httpMethod = HttpMethod.POST)
    public WrappedBoolean register(@Named("user")User user, @Named("gcm_id")String gcm_id) throws UnauthorizedException, NullPointerException
        {
                if (user==null)
                        throw new UnauthorizedException("You are not logged in.");
                if (gcm_id==null)
                        throw new NullPointerException("GCM id is null.");
               
        SandUser sandUser = ofy().load().key(Key.create(SandUser.class,user.getUserId())).now();
       
        if (sandUser==null || sandUser.getGcm_id()!= gcm_id){
                sandUser = new SandUser(user,gcm_id);
                ofy().save().entity(sandUser).now();
        }
       
        return new WrappedBoolean(true);
    }
« Ultima modifica: 08 Settembre 2014, 10:56:53 CEST da Caco85 »