当使用facebook sdk打开活动时,Android应用程序崩溃并重新打开

时间:2016-03-02 21:00:03

标签: android eclipse facebook

我遇到了facebook sdk的问题,我在这里尝试了很多其他问题而没有解决我的问题。

我的问题是,当我在eclipse模拟器中启动我的应用程序时,我的应用程序非常有效,包括与facebook sdk的活动。

但是,当我构建apk文件并在我的手机中安装我的应用程序工作,但如果我尝试打开有facebook sdk(登录Facebook)的活动我的应用程序崩溃并重新打开。在此之后,我可以正常使用facebook sdk打开活动。

但如果我关闭应用程序并手动重新打开并尝试使用facebook sdk打开活动,应用程序会再次崩溃并重新打开,现在我可以使用facebook sdk导航到该活动。

在模拟器中,打开活动时没有发生错误。

我在活动中使用的代码是:

    package com.myapps.rssadv;

import java.util.Arrays;
import java.util.List;

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

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.GraphRequest.GraphJSONObjectCallback;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.pushbots.push.Pushbots;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FbConn extends ActionBarActivity{

       private LoginButton buttonFacebook;  
       private List<String> facebookPermitions;  
       private CallbackManager callbackManager;


    @SuppressLint("SetJavaScriptEnabled") @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_fbconnect);
        facebookPermitions = Arrays.asList("email", "public_profile", "user_friends");
        callbackManager = CallbackManager.Factory.create();
        buttonFacebook = (LoginButton)findViewById(R.id.login_button_facebook); 
        buttonFacebook.setReadPermissions(facebookPermitions);
        String[] MenuAPP= getResources().getStringArray(R.array.MenuAPP);
        ArrayAdapter<String> aad= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, MenuAPP);
        setListAdapter(aad);


        TextView textEma = (TextView)findViewById(R.id.fbemail);
        TextView textNom = (TextView)findViewById(R.id.fbnome);
        WebView view = (WebView) this.findViewById(R.id.webView1);

        view.getSettings().setJavaScriptEnabled(true);
        view.setBackgroundColor(Color.TRANSPARENT);



        WebView view2 = (WebView) this.findViewById(R.id.Loading);
        view2.getSettings().setJavaScriptEnabled(true);
        view2.setBackgroundColor(Color.TRANSPARENT);
        view2.loadUrl("file:///android_asset/loading.html");


        Profile profileid = Profile.getCurrentProfile();
        if (profileid != null) {

            String idIMG = profileid.getId();
            String nom = profileid.getName();
            Pushbots.getInstance().setAlias(this, nom);

            textEma.setText(getString("aTextView"));
            textNom.setText(nom);
            view.loadUrl("http://graph.facebook.com/"+idIMG+"/picture?type=large&redirect=true&width=100&height=100");
            //CookieManager.getInstance().setAcceptCookie(true);
            }else{

        textEma.setText("");
        textNom.setText("");
        view.loadUrl("http://graph.facebook.com/1536910559864352/picture?type=large&redirect=true&width=100&height=100");
        Toast.makeText(FbConn.this, "Você precisa conectar-se ao facebook para podermos recuperar seus dados!", Toast.LENGTH_LONG).show();  
            }

        view.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                //hide loading image
                findViewById(R.id.Loading).setVisibility(View.GONE);
                //show webview
                findViewById(R.id.webView1).setVisibility(View.VISIBLE);
            }


        });


        //Botão Sobre Nós
        Button btnAbout =(Button)findViewById(R.id.about);
        btnAbout.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Intent intInfo = new Intent(getApplicationContext(), About.class);
            startActivity(intInfo);
        }
        });

        //Botão Regras
        Button btnRegras =(Button)findViewById(R.id.rules);
        btnRegras.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
          showAlertDialog(FbConn.this, "Regras de Postagens",
                    "Todas as notícias postadas serão submetidas à verificação e aprovação. Para que sua notícia seja aprovada ela deve ser: \n\n 1 - Postagem inédita. Não será republicada postagens com o mesmo conteúdo ou que tratem do mesmo evento. \n\n 2 - Não pode ser postagem com conteúdo diverso do foco do aplicativo. Postagens que não estejam relacionadas a eventos/programações ou conteúdos relacionados à eventos religiosos não serão publicadas. \n\n 3 - Não pode ser notícia com conteúdo impróprio. \n\n 4 - Necessariamente deve ser uma notícia verdadeira. As postagem de notícias não verdadeiras serão analisadas por nossa equipe técnica e poderão acarretar no bloqueio de envio de suas notícias. \n\n 5 - De preferência conecte o aplicativo ao seu perfil do facebook para que possamos utilizar a sua imagem na postagem. \n\n\n OBS.: As notícias aqui postadas são de inteira responsabilidade de seus postadores.", true);  
        }
        });
       //Botão Conexão
        Button btnConexao =(Button)findViewById(R.id.connection);
        btnConexao.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            if (!isNetworkAvailable()) {
                 showAlertDialog(FbConn.this, "Status da Rede:",
                         "Sua conexão não está ativa. Para ter acesso completo ao aplicativo você precisa estar conectado à uma rede móvel ou Wifi.", true);

     } else {
         showAlertDialog(FbConn.this, "Status da Rede:",
                "Sua conexão está ativa! Você terá acesso completo ao aplicativo!", true); 
     }

        }
        });
      //Botão Servidor
        Button btnServidor =(Button)findViewById(R.id.server);
        btnServidor.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Intent intCheck = new Intent(getApplicationContext(), CheckSite.class);
            startActivity(intCheck); 
        }
        });
      //Botão +Apps
        Button btnApps =(Button)findViewById(R.id.apps);
        btnApps.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Toast.makeText(getApplicationContext(), "Carregando...", Toast.LENGTH_SHORT).show();
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://brmyapps.com/site/apps.php"));
            startActivity(browserIntent);
        }
        });
        //Botão Contato
        Button btnContato =(Button)findViewById(R.id.emailSend);
        btnContato.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
         Toast.makeText(getApplicationContext(), "Carregando...", Toast.LENGTH_SHORT).show();
         Intent emailIntent = new Intent(Intent.ACTION_SEND);
         emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"decco.santos@hotmail.com"});
         emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Contato - RSSAdv");
         emailIntent.putExtra(Intent.EXTRA_TEXT, "Escreva aqui sua mensagem!");
         emailIntent.setType("message/rfc822");
         startActivity(Intent.createChooser(emailIntent, "Selecione o seu aplicativo de email...")); 
        }
        });
        //Botão Doação
        Button btnDoar =(Button)findViewById(R.id.doar);
        btnDoar.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Intent intDoar = new Intent(getApplicationContext(), Doacao.class);
            startActivity(intDoar);  
        }
        });
        //Botão Convidar
        Button btnConvidar =(Button)findViewById(R.id.compartilhar);
        btnConvidar.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Intent intConvidar = new Intent(getApplicationContext(), Convidar.class);
            startActivity(intConvidar);  
        }
        });
        //Botão Votar
        Button btnVotar =(Button)findViewById(R.id.buttonVote);
        btnVotar.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
            Toast.makeText(getApplicationContext(), "Abrindo a PlayStore...", Toast.LENGTH_SHORT).show();
            Intent browserIntentVote = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.myapps.rssadv&hl=pt_BR"));
            startActivity(browserIntentVote);  
        }
        });

        Button btnVoltar =(Button)findViewById(R.id.button1);
        ListView listView1 =(ListView)findViewById(R.id.listView1);
        listView1.setVisibility(listView1.GONE);
        FrameLayout myView = (FrameLayout)findViewById(R.id.container);

        myView.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                ListView listView1 =(ListView)findViewById(R.id.listView1);
                listView1.setVisibility(listView1.GONE);
                return false;
            }

        });

        btnVoltar.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
             ListView listView1 =(ListView)findViewById(R.id.listView1);
                //Intent intent = new Intent(getApplicationContext(),Menus.class);
                //startActivity(intent);
                 if (listView1.getVisibility() == View.GONE) {
                    // Its visible
                     listView1.setVisibility(listView1.VISIBLE);
                } else {
                    // Either gone or invisible
                    listView1.setVisibility(listView1.GONE);
                }
          }
         });


        buttonFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult arg0) {
                // TODO Auto-generated method stub
                GraphRequest request = GraphRequest.newMeRequest(arg0.getAccessToken(), new GraphJSONObjectCallback() { 

                    @Override  
                     public void onCompleted(JSONObject object, GraphResponse response) {  
                        System.out.println(object.toString());  
                        //Toast.makeText(FbConnect.this, object.toString(), Toast.LENGTH_LONG).show();
                        Profile profile = Profile.getCurrentProfile();
                        TextView textNome = (TextView)findViewById(R.id.fbnome);
                        textNome.setText(profile.getName());

                        WebView viewImg = (WebView)findViewById(R.id.webView1);
                        viewImg.loadUrl("http://graph.facebook.com/"+profile.getId()+"/picture?type=large&redirect=true&width=100&height=100");

                        try {
                            TextView textEmail = (TextView)findViewById(R.id.fbemail);
                            textEmail.setText(object.getString("email"));
                            if (!TextUtils.isEmpty(textEmail.getText())) {
                                saveString("aTextView", textEmail.getText().toString());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                       //Toast.makeText(FbConnect.this, object.toString(), Toast.LENGTH_LONG).show();

                      }  
                 });
                 request.executeAsync();
            }

            @Override
            public void onCancel() {
                // TODO Auto-generated method stub
                Toast.makeText(FbConn.this, "Cancelado pelo usuário!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException arg0) {
                // TODO Auto-generated method stub
                Toast.makeText(FbConn.this, "Não foi possível conectar-se ao facebook!", Toast.LENGTH_LONG).show();
            } 

        });


        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();

        }
}

    // Private class isNetworkAvailable
    private boolean isNetworkAvailable() {
        // Using ConnectivityManager to check for Network Connection
        ConnectivityManager connectivityManager = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

    @SuppressWarnings("deprecation")
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    private void setListAdapter(ArrayAdapter<String> aad) {
        ListView listview=(ListView)findViewById(R.id.listView1);


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

                      if (position == 0) {
                          Intent int0 = new Intent(getApplicationContext(), Geral.class);
                            startActivity(int0);

                      }

                      if (position == 1) {
                          Intent int1 = new Intent(getApplicationContext(), Cultos.class);
                            startActivity(int1);
                      }
                      if (position == 2) {
                          Intent int2 = new Intent(getApplicationContext(), Musical.class);
                        startActivity(int2);
                      }
                      if (position == 3) {
                          Intent int3 = new Intent(getApplicationContext(), Eventos.class);
                            startActivity(int3);
                      }
                      if (position == 4) {
                          Intent int4 = new Intent(getApplicationContext(), Social.class);
                            startActivity(int4);
                      }
                      if (position == 5) {
                          Intent int5 = new Intent(getApplicationContext(), Enviar.class);
                            startActivity(int5);
                      }
                      if (position == 6) {
                          Intent int6 = new Intent(getApplicationContext(), Info.class);
                            startActivity(int6);
                      }
                      if (position == 7) {
                          ListView listView1 =(ListView)findViewById(R.id.listView1);
                          listView1.setVisibility(listView1.GONE);
                      }
                  }

        });
    }

    private String getString(String key){
        SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
        return bifrostPrefs.getString(key, "");
    }

    private void saveString(String key, String value){
        SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = bifrostPrefs.edit();
        editor.putString(key, value);
        editor.commit();
   }

    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
       super.onActivityResult(requestCode, resultCode, data);  
       callbackManager.onActivityResult(requestCode, resultCode, data);  
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_geral, container, false);
            return rootView;
        }
    }


}

请帮助我找出错误的原因,因为我尝试了所有我发现的东西,没有解决。

0 个答案:

没有答案