How to upload photo to facebook from a camera application - android

I just used a code for camera application in android. In this application, the photo that clicked is saved in to SD Card.My code for saving as shown bellow $
Camera.PictureCallback jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
FileOutputStream outStream = null;
try
{
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Log.d(TAG, "on pictureTaken" + data.length);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d(TAG, "on pictureTaken-jpeg");
}
};
I just upload that image from sd card to facebook by using another activity by using FacebookSDK as shown bellow.
public class Upload extends Activity implements OnItemClickListener
{
/* Your Facebook Application ID must be set before running this example
* See http://www.facebook.com/developers/createapp.php
*/
public static final String APP_ID = "146770088755283";
private LoginButton mLoginButton;
private TextView mText;
private ImageView mUserPic;
private Handler mHandler;
ProgressDialog dialog;
final int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
final int PICK_EXISTING_PHOTO_RESULT_CODE = 1;
private ListView list;
String[] main_items = {"Upload Photo"};
String[] permissions = {"offline_access", "publish_stream", "user_photos", "publish_checkins", "photo_upload"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (APP_ID == null)
{
Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " +
"specified before running this example: see FbAPIs.java");
return;
}
setContentView(R.layout.main);
mHandler = new Handler();
mText = (TextView) Upload.this.findViewById(R.id.txt);
mUserPic = (ImageView)Upload.this.findViewById(R.id.user_pic);
//Create the Facebook Object using the app id.
Utility.mFacebook = new Facebook(APP_ID);
//Instantiate the asynrunner object for asynchronous api calls.
Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
mLoginButton = (LoginButton) findViewById(R.id.login);
//restore session if one exists
SessionStore.restore(Utility.mFacebook, this);
SessionEvents.addAuthListener(new FbAPIsAuthListener());
SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
/*
* Source Tag: login_tag
*/
mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);
if(Utility.mFacebook.isSessionValid())
{
requestUserData();
}
list = (ListView)findViewById(R.id.main_list);
list.setOnItemClickListener(this);
list.setAdapter(new ArrayAdapter<String>(this, R.layout.main_list_item, main_items));
}
#Override
public void onResume()
{
super.onResume();
if(Utility.mFacebook != null && !Utility.mFacebook.isSessionValid())
{
mText.setText("You are logged out! ");
mUserPic.setImageBitmap(null);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
/*
* if this is the activity result from authorization flow, do a call back to authorizeCallback
* Source Tag: login_tag
*/
case AUTHORIZE_ACTIVITY_RESULT_CODE:
{
Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
break;
}
/*
* if this is the result for a photo picker from the gallery, upload the image after scaling it.
* You can use the Utility.scaleImage() function for scaling
*/
case PICK_EXISTING_PHOTO_RESULT_CODE:
{
if (resultCode == Activity.RESULT_OK)
{
Uri photoUri = data.getData();
if(photoUri != null) {
Bundle params = new Bundle();
try
{
params.putByteArray("photo", Utility.scaleImage(getApplicationContext(), photoUri));
} catch (IOException e)
{
e.printStackTrace();
}
params.putString("caption", "FbAPIs Sample App photo upload");
Utility.mAsyncRunner.request("me/photos", params, "POST", new PhotoUploadListener(), null);
}
else
{
Toast.makeText(getApplicationContext(), "Error selecting image from the gallery.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "No image selected for upload.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
switch(position)
{
/*
* Source Tag: upload_photo
* You can upload a photo from the media gallery or from a remote server
* How to upload photo: https://developers.facebook.com/blog/post/498/
*/
case 0:
{
if(!Utility.mFacebook.isSessionValid())
{
Util.showAlert(this, "Warning", "You must first log in.");
}
else
{
dialog = ProgressDialog.show(Upload.this, "", getString(R.string.please_wait), true, true);
new AlertDialog.Builder(this)
.setTitle(R.string.gallery_title)
.setMessage(R.string.gallery_msg)
.setPositiveButton(R.string.gallery_button, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Intent.ACTION_PICK, (MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
startActivityForResult(intent, PICK_EXISTING_PHOTO_RESULT_CODE);
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface d) {
dialog.dismiss();
}
})
.show();
}
break;
}
}
}
/*
* callback for the feed dialog which updates the profile status
*/
public class UpdateStatusListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
new UpdateStatusResultDialog(Upload.this, "Update Status executed", values).show();
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No wall post made", Toast.LENGTH_SHORT);
toast.show();
}
}
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
public void onCancel() {
Toast toast = Toast.makeText(getApplicationContext(), "Update status cancelled", Toast.LENGTH_SHORT);
toast.show();
}
}
/*
* callback for the apprequests dialog which sends an app request to user's friends.
*/
public class AppRequestsListener extends BaseDialogListener {
public void onComplete(Bundle values) {
Toast toast = Toast.makeText(getApplicationContext(), "App request sent", Toast.LENGTH_SHORT);
toast.show();
}
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
public void onCancel() {
Toast toast = Toast.makeText(getApplicationContext(), "App request cancelled", Toast.LENGTH_SHORT);
toast.show();
}
}
/*
* callback for the photo upload
*/
public class PhotoUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
dialog.dismiss();
mHandler.post(new Runnable() {
public void run() {
new UploadPhotoResultDialog(Upload.this, "Upload Photo executed", response).show();
}
});
}
public void onFacebookError(FacebookError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
public class FQLRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Response: " + response, Toast.LENGTH_LONG).show();
}
});
}
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
/*
* Callback for fetching current user's name, picture, uid.
*/
public class UserRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(response);
final String picURL = jsonObject.getString("picture");
final String name = jsonObject.getString("name");
Utility.userUID = jsonObject.getString("id");
mHandler.post(new Runnable() {
public void run() {
mText.setText("Welcome " + name + "!");
mUserPic.setImageBitmap(Utility.getBitmap(picURL));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/*
* The Callback for notifying the application when authorization
* succeeds or fails.
*/
public class FbAPIsAuthListener implements AuthListener {
public void onAuthSucceed() {
requestUserData();
}
public void onAuthFail(String error) {
mText.setText("Login Failed: " + error);
}
}
/*
* The Callback for notifying the application when log out
* starts and finishes.
*/
public class FbAPIsLogoutListener implements LogoutListener {
public void onLogoutBegin() {
mText.setText("Logging out...");
}
public void onLogoutFinish() {
mText.setText("You have logged out! ");
mUserPic.setImageBitmap(null);
}
}
/*
* Request user name, and picture to show on the main screen.
*/
public void requestUserData() {
mText.setText("Fetching user name, profile pic...");
Bundle params = new Bundle();
params.putString("fields", "name, picture");
Utility.mAsyncRunner.request("me", params, new UserRequestListener());
}
/**
* Definition of the list adapter
*/
public class MainListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MainListAdapter() {
mInflater = LayoutInflater.from(Upload.this.getBaseContext());
}
public int getCount() {
return main_items.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View hView = convertView;
if(convertView == null) {
hView = mInflater.inflate(R.layout.main_list_item, null);
ViewHolder holder = new ViewHolder();
holder.main_list_item = (TextView) hView.findViewById(R.id.main_api_item);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
holder.main_list_item.setText(main_items[position]);
return hView;
}
}
class ViewHolder {
TextView main_list_item;
}
}
I want to upload that photo to facebook without save to SD Card and from the same activity that photo clicked. If anyone knows about it, please help me....

It is not possible in your case. The reason looks to be you are using native camera to capture a snap.So by default your snap will be saved to sdcard in the default location. There is no way you can stop it. But still you can delete the image after it is captured using the data returned from the Activity Result.

Related

Flashlight function crashes after returning from activity

I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.
It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.
This is my code (i did not include my imports to save some space):
public class MainActivity extends AppCompatActivity {
// Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;
// Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;
// MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;
// Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
mySpinner = (Spinner) findViewById(R.id.spinner);
flashlightButton = (ImageButton) findViewById(R.id.image);
myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
myToolbar.setTitle(getResources().getString(R.string.app_name));
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_itam,
getResources().getStringArray(R.array.Toolbar_dropdown_entries));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
ringtone = (Button) this.findViewById(R.id.ringtone);
message = (EditText)findViewById(R.id.messagePublish);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,
mySpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT)
.show();
if (mySpinner.getSelectedItem().toString().equals("Exit App")){
exit();
}else if(mySpinner.getSelectedItem().toString().equals("Settings"))
{
Intent intent;
intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("CURRENT_IP",client.getServerURI());
intent.putExtra("CURRENT_QOS", Integer.toString(qos));
intent.putExtra("CURRENT_TOPIC",topicStr);
startActivityForResult(intent,1); // this is so we can take the results back to mainActivity later
}else{
System.out.println("ara3e, den exw diale3ei tipota");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
//Flashlight on Create start
if(isFlashAvailable()) // check if flash is available on this device, if it is open camera (module) and make button clickable
{
camera = Camera.open();
parameters = camera.getParameters();
}else
{ // if flashlight is not supported dont let the user click the button
flashlightButton.setEnabled(false);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error.");
builder.setMessage("Flashlight not available on this device. \nExit?"); // inform the user and let him choose how to continue
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
exit();
}
});
builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
flashlightButton.setOnClickListener(new View.OnClickListener() { // listen for flash button clicks
#Override
public void onClick(View view) {
flashOnOff();
}
});
ringtone.setOnClickListener(new View.OnClickListener() { // Ringtone listener
#Override
public void onClick(View view) {
ringtoneOnOff(ringtoneMP);
}
});
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
// client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
Log.d("Connection:"," Lost");
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
}
});
}
//Flashlight start
#Override
protected void onStop() {
super.onStop();
if(camera!=null)
{
camera.release();
camera = null;
}
}
//Flashlight end
//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit application?")
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
// when yes is clicked exit the application
public void onClick(DialogInterface arg0, int arg1) {
exit();
}
})
.setNegativeButton("No", new
DialogInterface.OnClickListener() {
// when no is clicked do nothing
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
//Backkey end
// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
try{
client.subscribe(topic, qos);
}
catch (MqttException e){
e.printStackTrace();
}
}
private void unsetSubscription(MqttAndroidClient client,String topic){
try{
client.unsubscribe(topic);
}catch (MqttException e){
e.printStackTrace();
}
}
public void conn(View v){
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
// pub();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconn(View v){
if (client.isConnected()) {
try {
IMqttToken token = client.disconnect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}else {
Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void pub(View v) {
String topic = topicStr;
try {
client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void ringtoneOnOff(MediaPlayer ringtoneMP){
if (ringtoneMP.isPlaying()){
ringtoneMP.pause();
}else{
ringtoneMP.start();
}
}
private void myMessageArrived(String s,MqttMessage mqttMessage){
if ((mqttMessage.toString()).equals("Flash on")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
flashOnOff();
}
} else if ((mqttMessage.toString()).equals("Flash off")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
flashOnOff();
} else {
Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
}
} else if ((mqttMessage.toString()).equals("Ringtone on")) {
if (ringtoneMP.isPlaying()) {
Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
ringtoneMP.start();
}
} else if ((mqttMessage.toString()).equals("Ringtone off")) {
if (ringtoneMP.isPlaying()) {
ringtoneMP.pause();
} else {
Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("INFO:", "This Command does not exist");
}
vibrator.vibrate(500);
myRingtone.play();
}
public void exit(){
finish();
System.exit(0);
}
public boolean isFlashAvailable(){ // boolean function that returns true if flash is supported on this device
return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void flashOnOff(){ // self explanatory
if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){ // if the flash is on torch mode
Log.d("BHKE","408");
this.flashlightButton.setImageResource(R.drawable.off);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // turn it off
}else{
Log.d("BHKE","412");
this.flashlightButton.setImageResource(R.drawable.on);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); // else turn it on
}
this.camera.setParameters(this.parameters);
this.camera.startPreview();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String tempBrokerIp;
String temptopic="";
Integer tempqos;
Boolean BrokerIpChanged = true;
Boolean qosChanged = true;
Boolean topicChanged = true;
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (1) : {
if (resultCode == Activity.RESULT_OK) {
tempBrokerIp = data.getStringExtra("CURRENT_IP");
tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
temptopic = data.getStringExtra("CURRENT_TOPIC");
Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
if (tempBrokerIp.equals(BrokerIp)) {
BrokerIpChanged=false;
Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
}
if (tempqos.equals(qos)) {
qosChanged=false;
Log.i("qosChanged =", qosChanged.toString());
}else {
qos = tempqos;
}
if (temptopic.equals(topicStr)){
topicChanged=false;
Log.i("topicChanged =", topicChanged.toString());
}else{
topicStr = temptopic;
}
if (!BrokerIpChanged && !qosChanged && !topicChanged) return;
if (BrokerIpChanged){
try {
client.disconnect();
BrokerIp = tempBrokerIp;
topicStr = temptopic;
qos = tempqos;
// final String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
// options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1); // to user the latest mqtt version
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
Log.w("Mqtt","Connected to:"+ BrokerIp);
try{
Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
client.subscribe(topicStr,qos);
}catch (MqttException e){
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
System.out.println(client.isConnected());
// if (client.isConnected()){
// Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
// client.subscribe(temptopic,tempqos);
// }
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}catch (MqttException e){
e.printStackTrace();
}
}else
{
try {
client.unsubscribe(topicStr);
client.subscribe(temptopic,tempqos);
topicStr = temptopic;
qos = tempqos;
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public boolean isFlashOn(){
return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}
I can provide the settings activity code too is needed
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.
Ι added :
if (isFlashAvailable()){
camera = Camera.open();
parameters = camera.getParameters();
}
at the onActivityResult start and it works like a charm.

how to get unique id and profile info in social auth in integration for facebook

i have implement social auth for integration of facebook now i want to get user profile info and unique id .I have get access token but unable to get user profile info .I have implement it by following
public class SignUp extends Activity implements OnClickListener {
private EditText email_mEditText, password_mEditText;
SocialAuthAdapter socialAuthAdapter;
private RelativeLayout facebook_layout, twitter_layout, googleplus_layout, linkdin_layout;
private Button signIn_mButton;
String email_mString, password_mString;
private ImageView backIcon_mImageView, logoIcon_mImageView;
private TextView forgotpassword_mTextView;
String emailid_mString ;
EditText emailid_mEt;
Button submit_mbtn;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
signIn_mButton = (Button) findViewById(R.id.signin_button);
email_mEditText = (EditText) findViewById(R.id.email_editText);
password_mEditText = (EditText) findViewById(R.id.password_editText);
backIcon_mImageView = (ImageView) findViewById(R.id.backicon_imageView);
logoIcon_mImageView = (ImageView) findViewById(R.id.logoicon_imageView);
facebook_layout = (RelativeLayout) findViewById(R.id.facebook_layout);
twitter_layout = (RelativeLayout) findViewById(R.id.twitter_layout);
googleplus_layout = (RelativeLayout) findViewById(R.id.google_layout);
linkdin_layout = (RelativeLayout) findViewById(R.id.linkdin_layout);
facebook_layout.setOnClickListener(this);
twitter_layout.setOnClickListener(this);
googleplus_layout.setOnClickListener(this);
linkdin_layout.setOnClickListener(this);
socialAuthAdapter = new SocialAuthAdapter(new ResponseListener());
signIn_mButton.setOnClickListener(this);
backIcon_mImageView.setOnClickListener(this);
logoIcon_mImageView.setOnClickListener(this);
forgotpassword_mTextView = (TextView) findViewById(R.id.forgotpassword_textView);
forgotpassword_mTextView.setPaintFlags(forgotpassword_mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
forgotpassword_mTextView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.signin_button:
email_mString = email_mEditText.getText().toString();
password_mString = password_mEditText.getText().toString();
if ((email_mString.isEmpty()) && (password_mString.isEmpty())) {
email_mEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
email_mEditText.setError("Value required");
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
email_mEditText.setError(null);
}
});
} else if ((email_mString.isEmpty())) {
email_mEditText.setError("Please Enter the Email ");
} else if ((password_mString.isEmpty())) {
password_mEditText.setError("Please Enter the Password ");
} else {
Log.d("u r", "ur in else part");
new Thread(null, threadEventListing, "").start();
}
break;
case R.id.backicon_imageView:
Intent signInIntent = new Intent(SignUp.this, SignIn.class);
startActivity(signInIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
finish();
break;
case R.id.logoicon_imageView:
Intent signIntent = new Intent(SignUp.this, SignIn.class);
startActivity(signIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
finish();
break;
case R.id.forgotpassword_textView:
Log.d("hello", "u clicked FOrgot textview");
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.forgot_password);
emailid_mEt=(EditText)dialog.findViewById(R.id.etforgotpassword);
submit_mbtn=(Button)dialog.findViewById(R.id.btnsubmit);
submit_mbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
emailid_mString = emailid_mEt.getText().toString();
new Thread(null,threadForgotPassword,"").start();
}
});
dialog.show();
break;
case R.id.facebook_layout:
socialAuthAdapter.authorize(SignUp.this, Provider.FACEBOOK);
socialAuthAdapter.signOut(this, Provider.FACEBOOK.toString());
break;
case R.id.twitter_layout:
socialAuthAdapter.authorize(SignUp.this, Provider.TWITTER);
socialAuthAdapter.signOut(this, Provider.TWITTER.toString());
break;
case R.id.google_layout:
socialAuthAdapter.authorize(SignUp.this, Provider.GOOGLEPLUS);
socialAuthAdapter.signOut(this, Provider.GOOGLEPLUS.toString());
break;
case R.id.linkdin_layout:
socialAuthAdapter.authorize(SignUp.this, Provider.LINKEDIN);
socialAuthAdapter.signOut(this, Provider.LINKEDIN.toString());
break;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent signInIntent = new Intent(SignUp.this, SignIn.class);
startActivity(signInIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
finish();
}
private final class ResponseListener implements DialogListener {
public void onComplete(Bundle values) {
Log.d("tag", "In on comppleter");
String token = socialAuthAdapter.getCurrentProvider().getAccessGrant().getKey();
Log.d("Token", token);
}
#Override
public void onBack() {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
#Override
public void onError(SocialAuthError arg0) {
// TODO Auto-generated method stub
}
}
}
Use this Code
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
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) {
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_location"));
authButton.setFragment(this);
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
makeMeRequest(session);
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
/*
* #Override public void onCompleted(GraphUser user, Response
* response) { // If the response is successful if (session ==
* Session.getActiveSession()) { if (user != null) { // Set the
* id for the ProfilePictureView // view that in turn displays
* the profile picture. Log.e("user",user.toString()); } } if
* (response.getError() != null) { // Handle errors, will do so
* later. } }
*/
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
Log.e("FB Return", user.toString());
Log.e("FullName", user.getName());
Log.e("Id", user.getId());
Log.e("username", "" + user.getUsername());
Log.e("Fname", user.getFirstName());
Log.e("Fname", user.getLastName());
Log.e("gender", user.asMap().get("gender").toString());
String gender = user.asMap().get("gender").toString();
String email = (String) user.asMap().get("email") + "";
Log.e("email", email);
}
});
request.executeAsync();
}
#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);
}
}
Since you are using Social Auth, so you can try this :
private final class ProfileDataListener implements SocialAuthListener {
#Override
public void onExecute(Profile t) {
Log.d("Custom-UI", "Receiving Data");
Profile profileMap = t;
Log.d("Custom-UI", "Validate ID = " + profileMap.getValidatedId());
Log.d("Custom-UI", "First Name = " + profileMap.getFirstName());
Log.d("Custom-UI", "Last Name = " + profileMap.getLastName());
Log.d("Custom-UI", "Email = " + profileMap.getEmail());
Log.d("Custom-UI", "Gender = " + profileMap.getGender());
Log.d("Custom-UI", "Country = " + profileMap.getCountry());
Log.d("Custom-UI", "Language = " + profileMap.getLanguage());
Log.d("Custom-UI", "Location = " + profileMap.getLocation());
Log.d("Custom-UI", "Profile Image URL = " + profileMap.getProfileImageURL()); }

Chartboost PostInstall Tracker

Can someone explain to me how can i integrate Chartboost post install?
Already tried this post-install integration guide with my testing app (uploaded as alpha test) and with this reserved in-app purchases:
android.test.purchased
android.test.canceled
android.test.refunded
android.test.item_unavailable
When i try to run this code:
public void ChartboostPI(View view) {
trackInAppGooglePlayPurchaseEvent("Sample Title", "Sample description for product: android.test.canceled.", "0.99", "USD", "android.test.purchased", "inapp:"+this.getPackageName()+":android.test.canceled", "j");
}
i'm getting:
iap failure responce!!
P.S.:
Maybe there is some ways to test my own inapps, but i dont know how to specify this in in-app purchase code (I will be glad if someone will explain me how).
Finally i found the answer, cb developers posted example with release of 5.0.3
Here is example code:
public class GoogleIAPTracking extends Activity{
private static final String TAG = "com.chartboost.sdk.sample.cbtest.inappbilling";
private static final int INAPP_REQUEST_CODE = 10001;
//private static final String RELEASE_ITEM_SKU = "com.example.buttonclick";
private static final String TEST_ITEM_SKU = "android.test.purchased";
private Button clickButton;
private Button buyButton;
private String ITEM_SKU;
IabHelper mHelper;
Inventory inventory;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pit);
Chartboost.onCreate(this);
Chartboost.setDelegate(delegate);
buyButton = (Button)findViewById(R.id.buyButton);
clickButton = (Button)findViewById(R.id.clickButton);
clickButton.setEnabled(false);
ITEM_SKU = TEST_ITEM_SKU;
String base64EncodedPublicKey = getResources().getString(R.string.base64EncodedPublicKey);
/*Setting up Inapp billing purchase*/
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(true);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " +
result);
} else {
Log.d(TAG, "############# In-app Billing is set up ###############");
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, INAPP_REQUEST_CODE, mPurchaseFinishedListener, "mypurchasetoken");
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG,"###### onIabPurchaseFinished"+purchase +"#####"+ ITEM_SKU);
if (result.isFailure()) {
Runnable r = new Runnable() {
#Override
public void run() {
mHelper.myconsume(GoogleIAPTracking.this.getPackageName(), "inapp:"+getPackageName()+":android.test.purchased");
}
};
r.run();
Log.d(TAG,"###### onIabPurchaseFinished Error ");
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
buyButton.setEnabled(false);
}
}
};
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
Log.d(TAG,"###### onQueryInventoryFinished : " + inv);
if (result.isFailure()) {
// Handle failure
}
else {
Log.d(TAG," ####### Its in the inventory consuming the item !!!!");
try{
// MIGHT THROW AN EXCEPTION IF Chartboost.onStart() is not called.
Log.d(TAG,"########## Send it to Chartboost PIT ###########");
SkuDetails item = inv.getSkuDetails(ITEM_SKU);
Purchase purchase = inv.getPurchase(ITEM_SKU);
if(item !=null && purchase != null) {
String data =purchase.getOriginalJson();
String signature = TextUtils.isEmpty(purchase.getSignature()) ?"test":purchase.getSignature();
signature = TextUtils.isEmpty(signature) ?"test":signature;
if(item != null){
CBAnalytics.trackInAppGooglePlayPurchaseEvent(item.getTitle(),
item.getDescription(),
item.getPrice(),
item.getCurrencyCode(),
purchase.getSku(),
data,
signature);
}
}
} catch(Exception e){
Log.d(TAG, e.getMessage());
}
mHelper.consumeAsync(inv.getPurchase(ITEM_SKU), mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
Log.d(TAG,"###### onConsumeFinished");
if (result.isSuccess()) {
Log.d(TAG,"###### onConsumeFinished sucess");
}
buyButton.setEnabled(true);
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
// Pass on the activity result to the helper for handling
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
// not handled, so handle it ourselves (here's where you'd
// perform any handling of activity results not related to in-app
// billing...
super.onActivityResult(requestCode, resultCode, data);
}
else {
Log.d(TAG, "onActivityResult handled by IABUtil.");
}
};
/* The following methods reflect the buttons in our UI. */
public void onLoadButtonClick(View view) {
String toastStr = "Loading Interstitial";
Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
Chartboost.showInterstitial(CBLocation.LOCATION_STARTUP);
}
public void onMoreButtonClick(View view) {
String toastStr = "Loading More Apps";
Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
Chartboost.showMoreApps(CBLocation.LOCATION_GAME_SCREEN);
}
public void trackMiscRevenueGeneratingEventOfType(View view) {
String toastStr = "Sending trackMiscRevenueGeneratingEventOfType to SDK ..";
Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
//pit.trackMiscRevenueGeneratingEvent(CBMiscRevenueGeneratingEventType.CBMiscRevenueGeneratingEventType1, 100, "USD", "HayDay");
}
public void trackCustomEventOfType(View view) {
String toastStr = "Sending trackCustomEventOfType to SDK ..";
Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
//pit.trackCustomEventofType(CBCustomEventType.CBCustomEventType1, 2);
}
public void trackInGameScore(View view) {
String toastStr = "Sending trackInGameScore to SDK ..";
Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
//pit.trackInGameScore(10);
}
public void trackPlayerCurrencyBalance(View view) {
String toastStr = "Sending trackPlayerCurrencyBalance to SDK ..";
Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
//pit.trackPlayerCurrencyBalance(5, "USD");
}
/*Activity callback methods*/
#Override
protected void onStart() {
super.onStart();
Chartboost.onStart(this);
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG,"### onResume");
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
Chartboost.onStop(this);
}
#Override
public void onBackPressed() {
if (Chartboost.onBackPressed())
return;
else
super.onBackPressed();
}
#Override
public void onDestroy() {
super.onDestroy();
Chartboost.onDestroy(this);
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
/**
* Chartboost Delegate callbacks
*/
private ChartboostDelegate delegate = new ChartboostDelegate() {
};
}

some line of code not getting executed, when doing facebook post functionality

guys i am want to post on facebook, for that using facebook sdk, but some line of code not executed. is pops-up a dialog for login, when i do login, then SessionEvents.AuthListener listener should listen for login success. but its not listening. and every time when i start app it ask for login.
below is my code.
public class FacebookConnector {
private Facebook mFacebook;
private AuthListener mSessionListener;
private Context context;
private String[] permissions;
private Activity activity;
public FacebookConnector(String appId, Activity activity, Context context, String[] permissions) {
this.mFacebook = new Facebook(appId);
SessionStore.restore(mFacebook, context);
SessionEvents.addAuthListener(mSessionListener);
SessionEvents.addLogoutListener((LogoutListener) mSessionListener);
this.context = context;
this.permissions = permissions;
this.activity = activity;
}
public void postMessageOnWall(String msg) {
if (mFacebook.isSessionValid()) {
Bundle parameters = new Bundle();
parameters.putString("message", msg);
try {
String response = mFacebook.request("me/feed", parameters, "POST");
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
} else {
login();
}
}
public void login() {
if (!mFacebook.isSessionValid()) {
mFacebook.authorize(this.activity, this.permissions, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
}
public Facebook getFacebook() {
return mFacebook;
}
}
and in my activity Class....
private void onFacebookBtnClicked() {
if (facebookConnector.getFacebook().isSessionValid()) {
postMessageInThread();
} else {
SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
#Override
public void onAuthSucceed() {
postMessageInThread();
}
#Override
public void onAuthFail(String error) {
}
};
SessionEvents.addAuthListener(listener);
facebookConnector.login();
}
}
private void postMessageInThread() {
Thread t = new Thread() {
public void run() {
try {
facebookConnector.postMessageOnWall(mQuote.getQuoteText() + "\n" + mQuote.getAuthorName());
mFacebookHandler.post(mUpdateFacebookNotification);
} catch (Exception ex) {
Log.e("Facebook", "Error sending msg", ex);
}
}
};
t.start();
}
final Runnable mUpdateFacebookNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Facebook updated !", Toast.LENGTH_LONG).show();
}
};
in that postMessageInThread method not executing, don't know why
set this permission as public
private String[] PERMISSIONS = new String[]
{ "publish_stream", "read_stream", "offline_access" };
This will check is session exist if yes then it will direct update if not then ask user permission to update on wall.
Hi friends i got the solution, for my problem, so now posting the answer. i just had to overrideonActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
i just added it and got my app working correctly.

Android Facebook CheckIn getting null

i m getting null jsonarray , using official android Facebook api example code Hackbook for user Check in and nearest places list.
public class Places extends Activity implements OnItemClickListener {
private Handler mHandler;
private JSONObject location;
protected ListView placesList;
private Facebook mFacebook;
protected LocationManager lm;
protected MyLocationListener locationListener;
private AsyncFacebookRunner mAsyncRunner;
protected static JSONArray jsonArray;
final static double TIMES_SQUARE_LAT = 40.756;
final static double TIMES_SQUARE_LON = -73.987;
protected ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
location = new JSONObject();
setContentView(R.layout.places_list);
mFacebook = new Facebook(Constants.FB_APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle extras = getIntent().getExtras();
String default_or_new = extras.getString("LOCATION");
if (default_or_new.equals("times_square")) {
try {
location.put("latitude",new Double(TIMES_SQUARE_LAT) );
location.put("longitude",new Double(TIMES_SQUARE_LON));
} catch (JSONException e) {
}
fetchPlaces();
} else {
getLocation();
}
}
public void getLocation() {
/*
* launch a new Thread to get new location
*/
new Thread() {
#Override
public void run() {
Looper.prepare();
dialog = ProgressDialog.show(Places.this, "","Fetching Location", false, true,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
showToast("No location fetched.");
}
});
if (lm == null) {
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
if (locationListener == null) {
locationListener = new MyLocationListener();
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
if (provider != null && lm.isProviderEnabled(provider)) {
lm.requestLocationUpdates(provider, 1, 0, locationListener,
Looper.getMainLooper());
} else {
/*
* GPS not enabled, prompt user to enable GPS in the
* Location menu
*/
new AlertDialog.Builder(Places.this)
.setTitle("enable_gps_title")
.setMessage("enable_gps")
.setPositiveButton("GPS Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Places.this.finish();
}
}).show();
}
Looper.loop();
}
}.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/*
* User returning from the Location settings menu. try to fetch location
* again.
*/
dialog.dismiss();
getLocation();
}
/*
* Fetch nearby places by providing the search type as 'place' within 1000
* mtrs of the provided lat & lon
*/
private void fetchPlaces() {
if (!isFinishing()) {
dialog = ProgressDialog.show(Places.this, "", "nearby_places", true,
true, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
showToast("No places fetched.");
}
});
}
/*
* Source tag: fetch_places_tag
*/
Bundle params = new Bundle();
params.putString("type", "place");
try {
params.putString("center",
location.getString("latitude") + "," + location.getString("longitude"));
} catch (JSONException e) {
showToast("No places fetched.");
return;
}
params.putString("distance", "1000");
mAsyncRunner.request("search", params, new placesRequestListener());
}
/*
* Callback after places are fetched.
*/
public class placesRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
Log.d("Facebook-FbAPIs", "Got response: " + response);
dialog.dismiss();
try {
jsonArray = new JSONObject(response).getJSONArray("data");
if (jsonArray == null) {
showToast("Error: nearby places could not be fetched");
return;
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
mHandler.post(new Runnable() {
#Override
public void run() {
placesList = (ListView) findViewById(R.id.places_list);
placesList.setOnItemClickListener(Places.this);
placesList.setAdapter(new PlacesListAdapter(Places.this));
}
});
}
public void onFacebookError(FacebookError error) {
dialog.dismiss();
showToast("Fetch Places Error: " + error.getMessage());
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
if (!mFacebook.isSessionValid()) {
Util.showAlert(this, "Warning", "You must first log in.");
} else {
try {
final String message = "Check-in from the " + getString(R.string.app_name);
final String name = jsonArray.getJSONObject(position).getString("name");
final String placeID = jsonArray.getJSONObject(position).getString("id");
new AlertDialog.Builder(this).setTitle("check_in_title")
.setMessage(String.format("check_in_at"))
.setPositiveButton("Chaeck in", new DialogInterface.OnClickListener() {
/*
* Source tag: check_in_tag Check-in user at the
* selected location posting to the me/checkins
* endpoint. More info here:
* https://developers.facebook
* .com/docs/reference/api/user/ - checkins
*/
#Override
public void onClick(DialogInterface dialog, int which) {
Bundle params = new Bundle();
params.putString("place", placeID);
params.putString("message", message);
params.putString("coordinates", location.toString());
mAsyncRunner.request("me/checkins", params, "POST",
new placesCheckInListener(), null);
}
}).setNegativeButton(R.string.cancel, null).show();
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
}
}
}
public class placesCheckInListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
showToast("API Response: " + response);
}
public void onFacebookError(FacebookError error) {
dialog.dismiss();
showToast("Check-in Error: " + error.getMessage());
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(Places.this, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
/**
* Definition of the list adapter
*/
public class PlacesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
Places placesList;
public PlacesListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.place_item, null);
ViewHolder holder = new ViewHolder();
holder.name = (TextView) hView.findViewById(R.id.place_name);
holder.location = (TextView) hView.findViewById(R.id.place_location);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
String location = jsonObject.getJSONObject("location").getString("street") + ", "
+ jsonObject.getJSONObject("location").getString("city") + ", "
+ jsonObject.getJSONObject("location").getString("state");
holder.location.setText(location);
} catch (JSONException e) {
holder.location.setText("");
}
return hView;
}
}
class ViewHolder {
TextView name;
TextView location;
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
dialog.dismiss();
if (loc != null) {
try {
location.put("latitude", new Double(loc.getLatitude()));
location.put("longitude", new Double(loc.getLongitude()));
} catch (JSONException e) {
}
showToast("Location acquired: " + String.valueOf(loc.getLatitude()) + " "
+ String.valueOf(loc.getLongitude()));
lm.removeUpdates(this);
fetchPlaces();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Getting Jsonarray null in below line:
jsonArray = new JSONObject(response).getJSONArray("data");
let me know what is wrong in this above code thnx a lot

Categories

Resources