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
}
});
Related
I am making a practice app for my self creating friends profile my self in my app and having their avatar as imageview and name,nickname as text view it accepts object but it never shows anything on recyclerview
Please Help!
My main activity.java
package rex.MyFriends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
FloatingActionButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView view = findViewById(R.id.elementsview);
btn = (FloatingActionButton) findViewById(R.id.newfbtn);
view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
view.setAdapter(new Friendsadapter(this));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),FriendsAdder.class));
}
});
}
}
my FriendAdder activity
package rex.MyFriends;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendsAdder extends AppCompatActivity {
TextView name,nickname;
Button add ,selectimage;
ImageView image;
String imgpath;
private static final int SELECT_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friendsadder);
name = findViewById(R.id.name);
nickname = findViewById(R.id.nickname);
add = findViewById(R.id.add);
selectimage = findViewById(R.id.selimg);
image = findViewById(R.id.disimg);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.toString().isEmpty() || nickname.toString().isEmpty() || image.getDrawable()==null){
Toast.makeText(getBaseContext(),"please fill every thing!",Toast.LENGTH_SHORT).show();
}
else{
FriendList.addFriend(name.toString(),nickname.toString(),imgpath);
finish();
Toast.makeText(getBaseContext(),"Friend Added!",Toast.LENGTH_SHORT).show();
}
}
});
selectimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Your Friends Avatar!"), SELECT_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==SELECT_IMAGE && resultCode== Activity.RESULT_OK){
imgpath= data.getData().getPath();
Toast.makeText(getBaseContext(),imgpath,Toast.LENGTH_LONG).show();
image.setImageURI(data.getData());
}
}
}
my adapter class
package rex.MyFriends;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
public class Friendsadapter extends RecyclerView.Adapter<Friendsadapter.FriendsHolder> {
Context context;
public Friendsadapter(Context context) {
this.context = context;
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.friendrow,null,false);
return new FriendsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsHolder holder, int position) {
FriendList.Friend friend = (FriendList.Friend) FriendList.friendlist.get(position);
holder.nickname.setText(friend.nickname);
holder.name.setText(friend.name);
File imgFile = new File(friend.imgpath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
holder.image.setImageBitmap(myBitmap);
}
}
#Override
public int getItemCount() {
return FriendList.friendlist.size();
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView name,nickname;
ImageView image;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
image = itemView.findViewById(R.id.imageView2);
}
}
}
A helper Class I made with static Array list of Friend object acting as A runtime temporary database to add and remove Friend used in adapter class to display
package rex.MyFriends;
import java.util.ArrayList;
public class FriendList {
public static ArrayList<Friend> friendlist = new ArrayList<>();
public static class Friend {
String name;
String nickname;
String imgpath ;
public Friend(String name, String nickname, String imgpath) {
this.name = name;
this.nickname = nickname;
this.imgpath = imgpath;
}
}
public static void addFriend(String name, String nickname, String imgpath){
Friend friend = new Friend(name,nickname,imgpath);
friendlist.add(friend);
}
public int getSize(){
return friendlist.size();
}
public Friend getFriend(int position){
return friendlist.get(position);
}
}
Where the RecyclerView is handled adapterName.notifyDataSetChanged (); you need to run.
In your case, the data is collected statically. The place where the data is processed is a different Activity.
After switching to the new screen and adding data, you will need to update your adapter in onResume if you want the relevant data to appear when you come back. Recyclerview will appear blank since there is no data in its initial state.
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
I'm making a simple place picker program in android. I want to save some text when user choose a point on map with place picker. And the problem is when I click on button the place picker opens too long and variable which is responsible for place can't keep up change and dialog that responses for enter text never opens. I think, maybe problem is with threads, isn't it?
MapsActivity.java
package com.example.kirill.myapplication;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, View.OnClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
if (place != null) {
openDialog();
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
addEventBtn = (Button) findViewById(R.id.AddEventButton);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
Marker marker = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
}
}
}
public void openDialog() {
DialogEventCreate dialogEventCreate = new DialogEventCreate();
dialogEventCreate.show(getSupportFragmentManager(), "dialog Event Create");
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DialogEventCreate.java
package com.example.kirill.myapplication;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
public class DialogEventCreate extends AppCompatDialogFragment {
private EditText editEventName;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
editEventName = view.findViewById(R.id.editEventName);
return builder.create();
}
}
Please help me, what could go wrong?
Your problem is that the Place Picker communicates with your main activity asynchronously, so you're opening your dialog before it returns. Try waiting until Place Picker has returned before opening the dialog like so:
.
.
.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddEventButton:
place = null;
callPlacePicker();
break;
}
}
.
.
.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}
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 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.
I need help, I am making a simple application, and I donĀ“t know how to return to the MainActivity the string from the spinner and the name of the person when i click in the "Aceptar" button.
MainActivity.java
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
String saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivity(intent);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
public void HobbyReturn(int requestcode, int resultadocode, Intent data) {
if (resultadocode == ActivitySaludo.ACEPTAR_OK); {
String string = data.getStringExtra(ActivitySaludo.ACEPTAR_OK);
}
}
#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;
}
}
ActivitySaludo
package com.example.holaamigos;
import com.example.holaamigos.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
public static final String ACEPTAR_OK = "com.example.holaamigos.ACEPTAR_OK";
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(ACEPTAR_OK, iboton);
finish();
}
});
}
}
You need to start your second activity with the flag that you are waiting for a result, so instead of startActivity you need to make use of startActivityForResult.
If you need a little bit more information take a look at this tutorial it should cover all you need to get things working.