Go back to another Activity and pass parameters

Asked

Viewed 667 times

0

I’m having a problem adding items to a ListView, have a activity main calling another to add the met

package com.example.jonathan.agendaonline;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Profile;
import com.facebook.login.LoginManager;

import java.io.Serializable;
import java.util.ArrayList;

import static android.R.layout.simple_list_item_1;

public class TodosEventos extends AppCompatActivity {

    Button novoevento;
    TextView textoNome;
    ListView listaeventos;
    Button sair;
    ArrayList<String> eventos;
    ArrayAdapter<String> adapter;
    String usuarioUsado = null;
    String idUsuario = null;
    String usuarioUsado2 = null;
    Bundle extras;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_todos_eventos);
        novoevento = (Button) findViewById(R.id.Novo);
        textoNome = (TextView) findViewById(R.id.textViewNome);
        sair = (Button) findViewById(R.id.sairTodosEventos);
        listaeventos = (ListView) findViewById(R.id.listaEventos);
        eventos = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,eventos);
        listaeventos.setAdapter(adapter);

         extras = getIntent().getExtras();
         if(extras != null && extras.containsKey("usuario")) {
            usuarioUsado = (String) extras.getSerializable("usuario");
            idUsuario = (String) extras.getSerializable("IdFacebook");
            textoNome.setText(usuarioUsado);
        }


        String nomeEvento = null;
        if(extras != null && extras.containsKey("NomeEvento")) {
            nomeEvento = (String) extras.getSerializable("NomeEvento");
            usuarioUsado2 = (String) extras.getSerializable("usuario2");
            textoNome.setText(usuarioUsado2);
            Toast.makeText(TodosEventos.this, "Evento"+" "+nomeEvento+" "+"Criado com sucesso", Toast.LENGTH_SHORT).show();
            eventos.add(nomeEvento);
            adapter.notifyDataSetChanged();

        }

        listaeventos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(TodosEventos.this,Eventos.class);
                startActivity(intent);
            }
        });


        sair.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TodosEventos.this, LoginActivity.class);
                LoginManager.getInstance().logOut();
                startActivity(intent);
                finish();
            }
        });

        final String finalIdUsuario = idUsuario;
        novoevento.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(TodosEventos.this, CriacaoDeEventos.class);
                intent.putExtra("IdFacebook", finalIdUsuario);
                startActivity(intent);


            }
        });


    }

    @Override
    protected void onResume() {

        String nomeEvento = null;
        if(extras != null && extras.containsKey("NomeEvento")) {
            nomeEvento = (String) extras.getSerializable("NomeEvento");
            Toast.makeText(TodosEventos.this, "Evento"+" "+nomeEvento+" "+"Criado com sucesso", Toast.LENGTH_SHORT).show();
            eventos.add(nomeEvento);
            adapter.notifyDataSetChanged();

        }
        super.onResume();

    }  
}

This is what should take the data and add the items in the list, but the intent is not passing:

package com.example.jonathan.agendaonline;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.util.ArrayList;

import static android.R.layout.simple_list_item_1;

public class CriacaoDeEventos extends AppCompatActivity {

    Button criar;
    EditText nome,dataInicio,dataFim,hora,horaAlerta;
    public String nomeString;
    String dataInString;
    String dataFimString;
    String horaString;
    String horaAlertString;




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

        nome = (EditText) findViewById(R.id.nomeEvento);
        dataInicio = (EditText) findViewById(R.id.dataInicio);
        dataFim = (EditText) findViewById(R.id.dataFim);
        hora = (EditText) findViewById(R.id.hora);
        horaAlerta = (EditText) findViewById(R.id.horaAlerta);


        criar = (Button) findViewById(R.id.Criar);
        criar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                nomeString = nome.getText().toString();
                dataInString = dataInicio.getText().toString();
                dataFimString = dataFim.getText().toString();
                horaString = hora.getText().toString();
                horaAlertString = horaAlerta.getText().toString();

                Bundle extras = getIntent().getExtras();
                String idUsuario = null;
                String nomeUsuario = null;
                if(extras != null && extras.containsKey("idFacebook")) {
                    idUsuario = (String) extras.getSerializable("idFacebook");

                }

                RadioGroup reg = (RadioGroup) findViewById(R.id.rgopcoes);
                int op = reg.getCheckedRadioButtonId();

                if(op == R.id.diario){
                    Evento evento = new Evento(nomeString,dataInString,dataFimString,horaString,horaAlertString,1,idUsuario);

                }else{

                    Evento evento = new Evento(nomeString,dataInString,null,horaString,horaAlertString,1,idUsuario);

                }
                Intent intent = new Intent(CriacaoDeEventos.this, TodosEventos.class);
                intent.putExtra("NomeEvento",nomeString);
                intent.putExtra("usuario2",nomeUsuario);
                onBackPressed();

            }

        });




    }




}
  • try first-hand to format your question accordingly, because as it is no one can understand well what you need.

  • I believe that the Intent can only be received at the time of the creation of Activity, and not within the Click button. Try to catch the Intent on onCreate and not inside setOnClickListener

  • What I need is that when I return to the main activity pass the name of the event but without creating another activity .

  • And it is only passing the name of the event when I start a new Activity, if there is another way other than by Intent also server kk

  • I was able to resolve this by using http://answall.com/questions/55177/usar-uma-vari%C3%A1vel-em-uma-Activity-declarado-em-outra-Activity thank you for your reply

2 answers

1


The problem is in this section:

if(extras != null && extras.containsKey("idFacebook")) {
    idUsuario = (String) extras.getSerializable("idFacebook");
}

You use the string "idFacebook" when fetching the key on intent, but in time to pass the Intent you call the key to "IdFacebook".

Replace the "idFacebook" for "Idfacebook" that will solve your problem.

Consider declaring a constant in your Activity CriacaoDeEventos to avoid this kind of problem.

  • Very well observed, thank you, but what I really need is for the second activity to send information to the other, without me having to start another activity, just going back to the initial.

1

Speaks Vitor Henrique, need to put my Android application to work in the background (notifications and audible alerts), what is missing enable this code? Hug

package com.aapbd.borakhdriver.Activity;
 /**
*@Developer Faysal
 **
 **/

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.Configuration;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aapbd.borakhdriver.BorakhApplication;
import com.aapbd.borakhdriver.Helper.LanguageData;
import com.aapbd.borakhdriver.Helper.LocaleUtils;
import com.aapbd.borakhdriver.adapter.LanguageAdapter;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.facebook.FacebookSdk;
import com.facebook.accountkit.AccountKit;
import com.facebook.login.LoginManager;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.firebase.auth.FirebaseAuth;
import com.squareup.picasso.Picasso;
import com.aapbd.borakhdriver.Bean.Connect;
import com.aapbd.borakhdriver.Fragment.EarningsFragment;
import com.aapbd.borakhdriver.Fragment.Help;
import com.aapbd.borakhdriver.Fragment.Map;
import com.aapbd.borakhdriver.Fragment.SummaryFragment;
import com.aapbd.borakhdriver.Helper.SharedHelper;
import com.aapbd.borakhdriver.Helper.URLHelper;
import com.aapbd.borakhdriver.Listeners.ConnectionBooleanChangedListener;
import com.aapbd.borakhdriver.R;
import com.aapbd.borakhdriver.Utilities.Utilities;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import static com.aapbd.borakhdriver.BorakhApplication.trimMessage;

public class MainActivity extends AppCompatActivity {
    // tags used to attach the fragments
    private static final String TAG_HOME = "home";
    private static final String TAG_YOURTRIPS = "yourtrips";
    private static final String TAG_SUMMARY = "summary";
    private static final String TAG_HELP = "help";
    private static final String TAG_EARNINGS = "earnings";
    private static final String TAG_SHARE = "share";
    private static final String TAG_LOGOUT = "logout";
    public static FragmentManager fragmentManager;
    // index to identify current nav menu item
    public int navItemIndex = 0;
    public String CURRENT_TAG = TAG_HOME;
    Fragment fragment;
    Activity activity;
    Context context;
    Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawer;
    private View navHeader;
    private ImageView imgProfile;
    private TextView txtName, approvaltxt;
    private ImageView status;
    private Dialog alertDialog;
    LanguageData languageData;
    // flag to load home fragment when user presses back key
    private boolean shouldLoadHomeFragOnBackPress = true;
    private static final int REQUEST_LOCATION = 1450;
    Utilities utils = new Utilities();
    boolean push = false;
    Button btnFusedLocation;
    TextView tvLocation;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;

    private NotificationManager notificationManager;

    Map lFrag;

    private static final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        context = getApplicationContext();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (SharedHelper.getKey(context, "login_by").equals("facebook"))
            FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        findViewById();
        Bundle extras = getIntent().getExtras();

        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();

        if (extras != null) {
            push = extras.getBoolean("push");
        }

        map();
        Connect.addMyBooleanListener(new ConnectionBooleanChangedListener() {
            @Override
            public void OnMyBooleanChanged() {
                Toast.makeText(getApplication(), "Changed", Toast.LENGTH_SHORT).show();
            }
        });
        loadNavHeader();
        setUpNavigationView();

        navHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawer.closeDrawers();
                startActivity(new Intent(activity, EditProfile.class));
            }
        });
    }

    private void findViewById() {
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.usernameTxt);
        approvaltxt = (TextView) navHeader.findViewById(R.id.status_txt);
        imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);
        status = (ImageView) navHeader.findViewById(R.id.status);
    }

    private void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.nav_home:
                        navItemIndex = 0;
                        CURRENT_TAG = TAG_HOME;
                        fragment = new Map();
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("push", push);
                        fragment.setArguments(bundle);
                        FragmentManager manager = getSupportFragmentManager();
                        @SuppressLint("CommitTransaction")
                        FragmentTransaction transaction = manager.beginTransaction();
                        transaction.replace(R.id.content, fragment);
                        transaction.addToBackStack(null);
                        transaction.commit();
                        break;
                    case R.id.nav_yourtrips:
                       /* navItemIndex = 1;
                        CURRENT_TAG = TAG_YOURTRIPS;
                        fragment = new YourTrips();
                        GoToFragment();*/
                        drawer.closeDrawers();
                        startActivity(new Intent(MainActivity.this, HistoryActivity.class));
                        break;
                    case R.id.nav_wallet:
                        navItemIndex = 2;
                        CURRENT_TAG = TAG_SUMMARY;
                        fragment = new SummaryFragment();
                        drawer.closeDrawers();
                        FragmentManager manager2 = getSupportFragmentManager();
                        @SuppressLint("CommitTransaction")
                        FragmentTransaction transaction1 = manager2.beginTransaction();
                        transaction1.replace(R.id.content, fragment);
                        transaction1.addToBackStack(null);
                        transaction1.commit();
                        //GoToFragment();
                        break;
                    case R.id.nav_help:
                        navItemIndex = 3;
                        CURRENT_TAG = TAG_HELP;
                        fragment = new Help();
                        drawer.closeDrawers();
                        FragmentManager manager4 = getSupportFragmentManager();
                        @SuppressLint("CommitTransaction")
                        FragmentTransaction transaction2 = manager4.beginTransaction();
                        transaction2.replace(R.id.content, fragment);
                        transaction2.addToBackStack(null);
                        transaction2.commit();
                        //GoToFragment();
                        break;
                    case R.id.nav_earnings:
                        navItemIndex = 4;
                        CURRENT_TAG = TAG_EARNINGS;
                        fragment = new EarningsFragment();
                        drawer.closeDrawers();
                        FragmentManager manager1 = getSupportFragmentManager();
                        @SuppressLint("CommitTransaction")
                        FragmentTransaction transaction3 = manager1.beginTransaction();
                        transaction3.replace(R.id.content, fragment);
                        transaction3.addToBackStack(null);
                        transaction3.commit();
//                        GoToFragment();
                        break;
                    case R.id.nav_share:
                        drawer.closeDrawers();
                        navigateToShareScreen(URLHelper.APP_URL+getPackageName());
                        return true;
                    case R.id.nav_language:
                        drawer.closeDrawer(Gravity.START);
                        language_alert_view(MainActivity.this);
                        return true;
                    case R.id.nav_logout:
                        drawer.closeDrawers();
                        showLogoutDialog();
                        return true;
                    default:
                        navItemIndex = 0;
                }


                return true;
            }
        });


        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    loadNavHeader();
                }
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawer.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessary or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }


    /*------------------Language Dialog here-------------------------*/

    public void language_alert_view(final Context mContext) {
        final ArrayList<LanguageData> languageDataArrayList = new ArrayList<>();
        if (alertDialog != null)
            if (alertDialog.isShowing())
                alertDialog.dismiss();
        final View view = View.inflate(mContext, R.layout.language_lay, null);

        alertDialog = new Dialog(mContext, R.style.dialogwinddow);
        alertDialog.setContentView(view);
        alertDialog.setCancelable(true);
        alertDialog.show();

        RecyclerView langList = alertDialog.findViewById(R.id.langList);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
        langList.setHasFixedSize(true);
        langList.setLayoutManager(linearLayoutManager);
        try {
            for (int i = 0; i < getResources().getStringArray(R.array.languagelist).length; i++) {

                String lang_name = (getResources().getStringArray(R.array.languagelist))[i];
                String lang_code = (getResources().getStringArray(R.array.languagecode))[i];
                String lang_country_code =(getResources().getStringArray(R.array.languagecountrycode))[i];
                languageData = new LanguageData(lang_name, lang_code, lang_country_code);
                languageDataArrayList.add(languageData);
            }

            LanguageAdapter detailsSizeAdapter = new LanguageAdapter(MainActivity.this, languageDataArrayList);
            langList.setAdapter(detailsSizeAdapter);


            detailsSizeAdapter.setOnItemClickListener(new LanguageAdapter.MyClickListener() {
                @Override
                public void onItemClick(int position, View v) {

                    System.out.println(" Lang_Ccode -- >  " + languageDataArrayList.get(position).getLanguageCode());


                    updateLocale(languageDataArrayList.get(position));
                    /*
                    restart the activity
                     */
                    Intent intent = getIntent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                }
            });

        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }


    private void loadNavHeader() {
        // name, website
        txtName.setText(SharedHelper.getKey(context, "first_name") + " " + SharedHelper.getKey(context, "last_name"));
        if (SharedHelper.getKey(context, "approval_status").equals("new") || SharedHelper.getKey(context, "approval_status").equals("onboarding")) {
            approvaltxt.setTextColor(Color.YELLOW);
            approvaltxt.setText(getText(R.string.waiting_for_approval));
            status.setImageResource(R.drawable.newuser);
        } else if (SharedHelper.getKey(context, "approval_status").equals("banned")) {
            approvaltxt.setTextColor(Color.RED);
            approvaltxt.setText(getText(R.string.banned));
            status.setImageResource(R.drawable.banned);
        } else {
            approvaltxt.setTextColor(Color.GREEN);
            approvaltxt.setText(getText(R.string.approved));
            status.setImageResource(R.drawable.approved);
        }


        utils.print("Profile_PIC", "" + SharedHelper.getKey(context, "picture"));

        // Loading profile image
//        Glide.with(this).load(SharedHelper.getKey(context,"picture"))
//                .placeholder(R.drawable.ic_dummy_user)
//                .error(R.drawable.ic_dummy_user)
//                .crossFade()
//                .thumbnail(0.5f)
//                .bitmapTransform(new CircleTransform(this))
//                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                .into(imgProfile);
        //Assign current profile values to the edittext
        //Glide.with(activity).load(SharedHelper.getKey(context,"picture")).placeholder(R.drawable.ic_dummy_user).error(R.drawable.ic_dummy_user).into(imgProfile);
        Picasso.get().load(SharedHelper.getKey(context, "picture")).placeholder(R.drawable.ic_dummy_user).error(R.drawable.ic_dummy_user).into(imgProfile);

    }


    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawers();
            return;
        }

        // This code loads home fragment when back key is pressed
        // when user is in other fragment than home
        if (shouldLoadHomeFragOnBackPress) {
            // checking if user is on other navigation menu
            // rather than home
            if (navItemIndex != 0) {
//                if (CURRENT_TAG.equalsIgnoreCase(TAG_SUMMARY) || CURRENT_TAG.equalsIgnoreCase(TAG_EARNINGS)
//                        || CURRENT_TAG.equalsIgnoreCase(TAG_YOURTRIPS)){
//
//                }else{
                    navItemIndex = 0;
                    CURRENT_TAG = TAG_HOME;
                    fragment = new Map();
                    GoToFragment();
                    return;
//                }
            } else {
                System.exit(0);
            }
        }
        super.onBackPressed();
    }


    private void map() {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fragment = new Map();
                FragmentManager manager = getSupportFragmentManager();
                @SuppressLint("CommitTransaction")
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.content, fragment);
                transaction.commit();
                fragmentManager = getSupportFragmentManager();
            }
        });
    }

    public void GoToFragment() {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                drawer.closeDrawers();
                FragmentManager manager = getSupportFragmentManager();
                @SuppressLint("CommitTransaction")
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.content, fragment);
                transaction.commit();
            }
        });
    }

    public void navigateToShareScreen(String shareUrl) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, shareUrl + " -via " + getString(R.string.app_name));
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }


    public void statusCheck() {
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            enableLoc();
        }
    }

    private void enableLoc() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(Bundle bundle) {

                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                        mGoogleApiClient.connect();
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult connectionResult) {

                        utils.print("Location error", "Location error " + connectionResult.getErrorCode());
                    }
                }).build();
        mGoogleApiClient.connect();

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        builder.setAlwaysShow(true);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(MainActivity.this, REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                }
            }
        });
//          }

    }


    public void logout() {
        JSONObject object = new JSONObject();
        try {
            object.put("id", SharedHelper.getKey(context, "id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URLHelper.LOGOUT, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                drawer.closeDrawers();
                if (SharedHelper.getKey(context, "login_by").equals("facebook"))
                    LoginManager.getInstance().logOut();
                if (SharedHelper.getKey(context, "login_by").equals("google"))
                    signOut();
                if (!SharedHelper.getKey(MainActivity.this, "account_kit_token").equalsIgnoreCase("")) {
                    Log.e("MainActivity", "Account kit logout: " + SharedHelper.getKey(MainActivity.this, "account_kit_token"));
                    AccountKit.logOut();
                    SharedHelper.putKey(MainActivity.this, "account_kit_token", "");
                }
                SharedHelper.putKey(context, "current_status", "");
                SharedHelper.putKey(activity, "loggedIn", getString(R.string.False));
                SharedHelper.putKey(context, "email", "");
                Intent goToLogin = new Intent(activity, WelcomeScreenActivity.class);
                goToLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(goToLogin);
                finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String json = null;
                String Message;
                NetworkResponse response = error.networkResponse;
                if (response != null && response.data != null) {
                    try {
                        JSONObject errorObj = new JSONObject(new String(response.data));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.