I am trying to retrieve the info of Facebook user in my android app
This is what I got so far:
MainActivity.java
package com.firstandroidapp;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.*;
import com.facebook.Session.OpenRequest;
import com.facebook.model.*;
import com.facebook.widget.LoginButton;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
and the MainFragment.java
package com.firstandroidapp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private TextView userInfoTextView;
private UiLifecycleHelper uiHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
authButton.setFragment(this);
List<String> permission=new ArrayList<String>();
permission.add("public_profile");
permission.add("email");
permission.add("user_birthday");
permission.add("user_location");
permission.add("user_likes");
permission.add("user_interests");
permission.add("user_relationships");
authButton.setReadPermissions(permission);
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
userInfoTextView.setVisibility(View.VISIBLE);
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
userInfoTextView.setText(buildUserInfoDisplay(user));
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
userInfoTextView.setVisibility(View.INVISIBLE);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private interface MyGraphLanguage extends GraphObject {
// Getter for the ID field
String getId();
// Getter for the Name field
String getName();
}
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
//Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
// Example: typed access (name)
// - no special permissions required
userInfo.append(String.format("Name: %s\n\n",
user.getName()));
// Example: typed access (birthday)
// - requires user_birthday permission
// userInfo.append(String.format("Birthday: %s\n\n",
// user.getBirthday()));
//
userInfo.append(String.format("E-mail: %s\n\n",
user.asMap().get("email").toString()));
// Example: partially typed access, to location field,
// name key (location)
// - requires user_location permission
// userInfo.append(String.format("Location: %s\n\n",
// user.getLocation().getProperty("name")));
// Example: access via property name (locale)
// - no special permissions required
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
// Example: access via key for array (languages)
// - requires user_likes permission
// JSONArray languages = (JSONArray)user.getProperty("languages");
// if (languages.length() > 0) {
// ArrayList<String> languageNames = new ArrayList<String> ();
//
// // Get the data from creating a typed interface
// // for the language data.
// GraphObjectList<MyGraphLanguage> graphObjectLanguages =
// GraphObject.Factory.createList(languages,
// MyGraphLanguage.class);
//
// // Iterate through the list of languages
// for (MyGraphLanguage language : graphObjectLanguages) {
// // Add the language name to a list. Use the name
// // getter method to get access to the name field.
// languageNames.add(language.getName());
// }
//
// userInfo.append(String.format("Languages: %s\n\n",
// languageNames.toString()));
// }
Log.d(TAG, user.getName() + user.asMap().get("email").toString() + user.getProperty("locale") );
return userInfo.toString();
}
}
and I only get he Name and e-mail and language and I want more information such as the birthday and pages he/she likes and already added these permissions but for example the birthday returns null any idea what I am doing wrong please ??
Any help would be appreciate it
Thanks
Are you sure if the birthday date exists on Facebook profile as well? or they may have set to privacy.
Related
I'm Trying to turn on bluetooth on my application, However when I click the button submit the application is getting crashed and showing error as java.lang.nullpointerexception
Error code
FATAL EXCEPTION: main
Process: com.example.smartaams, PID: 4094
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at com.example.smartaams.MarkAttendance.enableDisableBT(MarkAttendance.java:131)
at com.example.smartaams.MarkAttendance$1.onClick(MarkAttendance.java:92)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Script
package com.example.smartaams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
public class MarkAttendance extends Activity {
int year;
int month;
int day;
static final int DATE_DIALOG_ID=999;
String class_item,sub_item;
Button submitbutton,backbutton;
EditText tvDisplayDate,tvTopic;
Spinner spclassname,spsubject,session;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ArrayList<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mydate=java.text.DateFormat.getDateInstance().format(Calendar.getInstance().getTime());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark_attendance);
tvDisplayDate = (EditText) findViewById(R.id.currentdate);
tvTopic = (EditText) findViewById(R.id.topic);
final Calendar c = Calendar.getInstance();
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
int dd = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(yy).append(" ").append("-").append(mm + 1).append("-")
.append(dd));
submitbutton = (Button) findViewById(R.id.submit);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
submitbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}});
}
private static final String TAG = "Attendance";
BluetoothAdapter mBluetoothAdapter;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
public void enableDisableBT() {
if (mBluetoothAdapter == null) {
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if (mBluetoothAdapter.isEnabled()) {
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if (mBluetoothAdapter.isEnabled()) {
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
backbutton = (Button) findViewById(R.id.back);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MarkAttendance.this,StudentHome .class);
startActivity(i);
}
});
spclassname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?>spclassname, View view, int position, long id) {
// On selecting a spinner item
class_item =spclassname.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
spsubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> spsubject, View view, int position, long id) {
// On selecting a spinner item
sub_item = spsubject.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
session.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> session, View view, int position, long id) {
// On selecting a spinner item
sub_item = session.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
}
Please help
PS: I'm very new to coding, and I'm using someone else project
Make sure that you have added permissions for Bluetooth in your AndroidManifest.xml file as follows :
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
And you need to check if bluetooth is enabled, if not, request to enable it.
So, instead of checking (mBluetoothAdapter.isEnabled()) , you need to check not condition as follows and need to call Bluetooth enable Intent:
(!mBluetoothAdapter.isEnabled()).
Also, you need to add return statement if you get the instance of BluetoothAdapter as null. See the code below :
if (mBluetoothAdapter == null) {
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
return; // missing statement
}
I hope this will help you.
I have a .sql database which I edit using PHPmyadmin and a android app that retrieves the login credentials from the database and tries to login to the app according to the user's credentials. But it keeps showing "Unable to login" error in the app even though I use the correct credentials from the database, which in this case is phoneno and password. The Login_Activity.JAVA is as below. Why is the app not logging in properly?
Login_Activity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
I'm trying to implement the facebook login. I have followed everything from here.
https://developers.facebook.com/docs/facebook-login/android/v2.3
And I am trying to make a Graph API call to retrieve user data; however, when I do so I get this.
Warning: Request without access token missing application ID or client token.
I believe I have implemented this login correctly and followed all the steps.
I have done some research on this and since sessions are deprecated in this current Facebook API version it has been of no help.
Is there anything blatantly wrong with my implementation that would cause Facebook Login not to be validated for the user?
package com.ro.hitup1_0;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
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.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class LoginActivity extends Activity {
//Give your SharedPreferences file a name and save it to a static variable
public static final String PREFS_NAME = "MyPrefsFile";
//Facebook button
LoginButton loginButton;
Button email_button;
Button google_button;
CallbackManager callbackManager;
AccessTokenTracker accessTokenTracker;
ProfileTracker profileTracker;
JSONArray userInformation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.e("loginResult: ", loginResult.getAccessToken().getToken());
//LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "email", "user_friends"));
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
Log.e("JSON: ", object.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
//Log.e(" About to Graph Call", " ");
request.executeAsync();
//Log.e(" Finished Graph Call", " ");
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("Facebook exception: ", exception.getMessage());
}
});
// Callback registration
//make sure to redirect to main page
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
// App code
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
// App code
}
};
google_button=(Button)findViewById(R.id.google_button);
google_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
email_button= (Button)findViewById(R.id.email_button);
email_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.ro.hitup1_0",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
profileTracker.stopTracking();
}
}
I implemented this in a FragmentActivity is there anything wrong with doing so?
What am I missing and why is this occuring?
For additional context (no android pun intended),
https://github.com/rrtigga/Hitup1.0/tree/master/app/src/main
Thanks.
I'm working on an app where whatevever the user speaks on the phone gets added to the listview(up to this is working fine) and on clicking that item on that list view,send that over to the parse server.
This is my class called Speech
`package com.example.projecta;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
public class Speech extends Activity implements OnClickListener {
ListView viewlist;
static final int check = 1111;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.speech);
Parse.initialize(this, "JnmLmnvOjxvRgBMGPl4XzOzvoqPPY7KGG2cqiExL", "8ejsJCanB26YYB6Io3jKov5wcwuajcB1zjRPUyMs");
ParseObject.registerSubclass(Storedata.class);
ParseAnalytics.trackAppOpened(getIntent());
viewlist = (ListView)findViewById(R.id.speechview);
Button b = (Button)findViewById(R.id.speechb);
b.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
in.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
in.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Louder");
startActivityForResult(in, check);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == check && resultCode == RESULT_OK){
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
viewlist.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
}
super.onActivityResult(requestCode, resultCode, data);
}
public void createStoredata(View v) {
Storedata st = new Storedata();
st.setDescription(viewlist.toString());
st.saveEventually();
}
}
`
This is my store data class
package com.example.projecta;
import com.parse.ParseObject;
public class Storedata extends ParseObject{
public Storedata(){
}
public void setDescription(String description){
put("description", description);
}
{
}
}
I really need help with this thanks.
You need to add a listener to your listview itself to click the items
viewlist.setClickable(true);
viewlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//perform action with your item
}
});
I am trying to get the friends list of the current logged-in user.
Here's how I am trying to get it:
private void fetchFriends(Session session) {
Request.newMyFriendsRequest(session, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
friendsList = new ArrayList<FriendInfoHolder>();
for (GraphUser u : users) {
friendsList.add(buildFriendInfoHolder(u));
}
Intent intent = new Intent(parentActivity,
FriendListActivity.class);
intent.putParcelableArrayListExtra("friends_list",
friendsList);
parentActivity.startActivity(intent);
} else {
Log.i("users_status", "null");
}
}
}).executeAsync();
}
The problem is the users list (List<GraphUser> users) is always null.
I previously set the read permission as follows:
authButton.setReadPermissions(Arrays.asList("read_friendlists"));
So, I am not sure what's wrong. Here is the full Code:
Solved: I didn't add the INTERNET permission in my manifest file.
package home.example.logintest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.facebook.Request;
import com.facebook.Request.GraphUserListCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity {
private MainFragement mainFragement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragement = new MainFragement();
mainFragement.setParentActivity(this);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragement).commit();
} else {
// Or set the fragment from restored state info
mainFragement = (MainFragement) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
// try {
// PackageInfo info = getPackageManager().getPackageInfo(
// "home.example.logintest", PackageManager.GET_SIGNATURES);
// for (Signature signature : info.signatures) {
// MessageDigest md = MessageDigest.getInstance("SHA");
// md.update(signature.toByteArray());
// Log.d("KeyHash:",
// Base64.encodeToString(md.digest(), Base64.DEFAULT));
// }
// } catch (NameNotFoundException e) {
//
// } catch (NoSuchAlgorithmException e) {
//
// }
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static class MainFragement extends Fragment {
private UiLifecycleHelper uiHelper;
private ArrayList<FriendInfoHolder> friendsList;
private Activity parentActivity;
public Activity getParentActivity() {
return parentActivity;
}
public void setParentActivity(Activity parentActivity) {
this.parentActivity = parentActivity;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container,
false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("read_friendlists"));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i("msg", "Logged in...");
fetchFriends(session);
} else if (state.isClosed()) {
Log.i("msg", "Logged out...");
}
}
private void fetchFriends(Session session) {
Request.newMyFriendsRequest(session, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
if (users != null) {
friendsList = new ArrayList<FriendInfoHolder>();
for (GraphUser u : users) {
friendsList.add(buildFriendInfoHolder(u));
}
Intent intent = new Intent(parentActivity,
FriendListActivity.class);
intent.putParcelableArrayListExtra("friends_list",
friendsList);
parentActivity.startActivity(intent);
} else {
Log.i("users_status", "null");
}
}
}).executeAsync();
}
private FriendInfoHolder buildFriendInfoHolder(GraphUser user) {
String profilePictureUrl = "graph.facebook.com/" + user.getId()
+ "/picture?type=square";
return new FriendInfoHolder(user.getFirstName(),
user.getLastName(), profilePictureUrl);
}
}
}
The problem was that I didn't add the INTERNET permission in the manifest file.