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
Related
I have implemented Twilio in my android app for outgoing and incoming calls. But I'm facing an issue while getting incoming call with the background service. The issue is that I get calls in first 30-40 mins only. After sometime phone stops getting incoming calls. I tried so much. Please respond me soon. I'm sharing code with you too.
I get token from a background service which generates token after a time period.
IncomingCallService.java
public class IncomingCallService extends Service implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static Handler handler, handler_login;
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
Ringtone r;
Uri notification;
public static final String LOGIN_DETAILS = "XXXXXXXX";
AudioManager am;
Intent intent;
public static String DEFAULT_CLIENT_NAME = "developer";
static String Twilio_id = "",
INCOMING_AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT
+ MenuItems.Twilio_id;
Runnable newrun;
Activity context;
Context ctx;
static String op_id = "";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
handler_login = new Handler();
handler_login.postDelayed(new Runnable() {
#Override
public void run() {
Login();
handler_login.postDelayed(this, 20000);
}
}, 1000);
}
public void Login() {
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, true, true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.intent = intent;
// I know getIntent always return NULL in service
if (intent != null) {
op_id = intent.getStringExtra("operator_id");
onCallHandler();
}
return START_STICKY;
}
public void onCallHandler() {
handler = new Handler();
newrun = new Runnable() {
#Override
public void run() {
handler.removeCallbacks(newrun);
new IncomingTokenTask().execute();
if (phone.handleIncomingIntent(intent)) {
}
handler.postDelayed(this, 2000000);
}
};
handler.postDelayed(newrun, 8000000);
}
class IncomingTokenTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
}
}
The BasicPhone class of twilio
public class IncomingPhone implements DeviceListener, ConnectionListener {
private static final String TAG = "IncomingPhone";
static String decodedString = "";
static String capabilityToken = "";
// TODO: change this to point to the script on your public server
private static final String AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT+MenuItems.Twilio_id;
public interface LoginListener {
public void onLoginStarted();
public void onLoginFinished();
public void onLoginError(Exception error);
}
public interface BasicConnectionListener {
public void onIncomingConnectionDisconnected();
public void onConnectionConnecting();
public void onConnectionConnected();
public void onConnectionFailedConnecting(Exception error);
public void onConnectionDisconnecting();
public void onConnectionDisconnected();
public void onConnectionFailed(Exception error);
}
public interface BasicDeviceListener {
public void onDeviceStartedListening();
public void onDeviceStoppedListening(Exception error);
}
private static IncomingPhone instance;
public static final IncomingPhone getInstance(Context context) {
if (instance == null)
instance = new IncomingPhone(context);
return instance;
}
private final Context context;
private LoginListener loginListener;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private static boolean twilioSdkInited;
private static boolean twilioSdkInitInProgress;
private boolean queuedConnect;
private Device device;
private Connection pendingIncomingConnection;
private Connection connection;
private boolean speakerEnabled;
private String lastClientName;
private boolean lastAllowOutgoing;
private boolean lastAllowIncoming;
private IncomingPhone(Context context) {
this.context = context;
}
public void setListeners(LoginListener loginListener,
BasicConnectionListener basicConnectionListener,
BasicDeviceListener basicDeviceListener) {
this.loginListener = loginListener;
this.basicConnectionListener = basicConnectionListener;
this.basicDeviceListener = basicDeviceListener;
}
private void obtainCapabilityToken(String clientName,
boolean allowOutgoing, boolean allowIncoming) {
StringBuilder url = new StringBuilder();
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient httpclient = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory
.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(
httpclient.getParams(), registry);
#SuppressWarnings("unused")
DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
httpclient.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
url.append(AUTH_PHP_SCRIPT);
// This runs asynchronously!
new GetAuthTokenAsyncTask().execute(url.toString());
}
private boolean isCapabilityTokenValid() {
if (device == null || device.getCapabilities() == null)
return false;
long expTime = (Long) device.getCapabilities().get(
Capability.EXPIRATION);
return expTime - System.currentTimeMillis() / 1000 > 0;
}
//
private void updateAudioRoute() {
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(speakerEnabled);
}
public void login(final String clientName, final boolean allowOutgoing,
final boolean allowIncoming) {
if (loginListener != null)
loginListener.onLoginStarted();
this.lastClientName = clientName;
this.lastAllowOutgoing = allowOutgoing;
this.lastAllowIncoming = allowIncoming;
if (!twilioSdkInited) {
if (twilioSdkInitInProgress)
return;
twilioSdkInitInProgress = true;
Twilio.setLogLevel(Log.DEBUG);
Twilio.initialize(context, new Twilio.InitListener() {
#Override
public void onInitialized() {
twilioSdkInited = true;
twilioSdkInitInProgress = false;
obtainCapabilityToken(clientName, allowOutgoing,
allowIncoming);
}
#Override
public void onError(Exception error) {
twilioSdkInitInProgress = false;
if (loginListener != null)
loginListener.onLoginError(error);
}
});
} else {
obtainCapabilityToken(clientName, allowOutgoing, allowIncoming);
}
}
private void reallyLogin(final String capabilityToken) {
try {
if (device == null) {
device = Twilio.createDevice(capabilityToken, this);
Intent intent = new Intent(context, IncomingPhoneActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
device.setIncomingIntent(pendingIntent);
} else
device.updateCapabilityToken(capabilityToken);
if (loginListener != null)
loginListener.onLoginFinished();
if (queuedConnect) {
// If someone called connect() before we finished initializing
// the SDK, let's take care of that here.
connect(null);
queuedConnect = false;
}
} catch (Exception e) {
if (device != null)
device.release();
device = null;
if (loginListener != null)
loginListener.onLoginError(e);
}
}
public void setSpeakerEnabled(boolean speakerEnabled) {
if (speakerEnabled != this.speakerEnabled) {
this.speakerEnabled = speakerEnabled;
updateAudioRoute();
}
}
public void connect(Map<String, String> inParams) {
if (twilioSdkInitInProgress) {
// If someone calls connect() before the SDK is initialized, we'll
// remember
// that fact and try to connect later.
queuedConnect = true;
return;
}
if (!isCapabilityTokenValid())
login(lastClientName, lastAllowOutgoing, lastAllowIncoming);
if (device == null)
return;
if (canMakeOutgoing()) {
disconnect();
connection = device.connect(inParams, this);
if (connection == null && basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
"Couldn't create new connection"));
}
}
public void disconnect() {
IncomingPhoneActivity.incomingAlert = null;
if (connection != null) {
connection.disconnect(); // will null out in onDisconnected()
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnecting();
}
}
public void acceptConnection() {
if (pendingIncomingConnection != null) {
if (connection != null)
disconnect();
pendingIncomingConnection.accept();
connection = pendingIncomingConnection;
pendingIncomingConnection = null;
}
}
public void connecta(String phoneNumber) {
Toast.makeText(context, "Calling...", Toast.LENGTH_SHORT).show();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("group_id", "11");
// String capabilityToken;
try {
device = Twilio
.createDevice(decodedString, this /* DeviceListener */);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
device.disconnectAll();
} catch (Exception e) {
e.printStackTrace();
}
connection = device.connect(parameters, this);
if (connection == null) {
Log.w(TAG, "Failed to create new connection");
}
}
public void ignoreIncomingConnection() {
if (pendingIncomingConnection != null) {
pendingIncomingConnection.ignore();
}
}
public boolean isConnected() {
return connection != null
&& connection.getState() == Connection.State.CONNECTED;
}
public Connection.State getConnectionState() {
return connection != null ? connection.getState()
: Connection.State.DISCONNECTED;
}
public boolean hasPendingConnection() {
return pendingIncomingConnection != null;
}
public boolean handleIncomingIntent(Intent intent) {
Device inDevice = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection inConnection = intent
.getParcelableExtra(Device.EXTRA_CONNECTION);
if (inDevice == null && inConnection == null)
return false;
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
if (pendingIncomingConnection != null) {
Log.i(TAG, "A pending connection already exists");
inConnection.ignore();
return false;
}
pendingIncomingConnection = inConnection;
pendingIncomingConnection.setConnectionListener(this);
return true;
}
public boolean canMakeOutgoing() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.OUTGOING)
&& (Boolean) caps.get(Capability.OUTGOING);
}
public boolean canAcceptIncoming() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.INCOMING)
&& (Boolean) caps.get(Capability.INCOMING);
}
public void setCallMuted(boolean isMuted) {
if (connection != null) {
connection.setMuted(isMuted);
}
}
#Override
/* DeviceListener */
public void onStartListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStartedListening();
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(null);
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice, int inErrorCode,
String inErrorMessage) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(new Exception(
inErrorMessage));
}
#Override
/* DeviceListener */
public boolean receivePresenceEvents(Device inDevice) {
return false;
}
#Override
/* DeviceListener */
public void onPresenceChanged(Device inDevice, PresenceEvent inPresenceEvent) {
}
#Override
/* ConnectionListener */
public void onConnecting(Connection inConnection) {
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnecting();
}
#Override
/* ConnectionListener */
public void onConnected(Connection inConnection) {
updateAudioRoute();
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnected();
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnected();
} else if (inConnection == pendingIncomingConnection) {
pendingIncomingConnection = null;
if (basicConnectionListener != null)
basicConnectionListener.onIncomingConnectionDisconnected();
}
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection, int inErrorCode,
String inErrorMessage) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
inErrorMessage));
}
}
private class GetAuthTokenAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
IncomingPhone.this.reallyLogin(result);
}
#Override
protected String doInBackground(String... params) {
try {
capabilityToken = HttpHelper.httpGet(params[0]);
decodedString = capabilityToken.replace("\"", "");
} catch (Exception e) {
e.printStackTrace();
}
return decodedString;
}
}
}
And the activity which opens after getting incoming call via Service class.
public class IncomingPhoneActivity extends Activity implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static final Handler handler = new Handler();
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
private LinearLayout disconnect_btn;
private LinearLayout mainButton;
private ToggleButton speakerButton;
private ToggleButton muteButton;
private EditText logTextBox;
static AlertDialog incomingAlert;
private EditText outgoingTextBox;
private EditText clientNameTextBox;
private Button capabilitesButton;
private CheckBox incomingCheckBox, outgoingCheckBox;
Button call_btn, dis_call_btn, updateButton;
public static String AUTH_PHP_SCRIPT, rating1, rating2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_screen);
Intent intent = getIntent();
Operator_id = intent.getStringExtra("operator_id");
gps = new GPSTracker(IncomingPhoneActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// gps.showSettingsAlert();
latitude = 0.00;
longitude = 0.00;
}
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
AUTH_PHP_SCRIPT = "http://xxxxxxxxxxxxxx/getGenToken?group_id="
+ Operator_id + "&twilio_id=" + Twilio_id + "&latitude="
+ latitude + "&longitude=" + longitude;
disconnect_btn = (LinearLayout) findViewById(R.id.d_call);
mainButton = (LinearLayout) findViewById(R.id.call);
call_btn = (Button) findViewById(R.id.call_btn);
dis_call_btn = (Button) findViewById(R.id.d_call_btn);
mainButton.setOnClickListener(this);
call_btn.setOnClickListener(this);
dis_call_btn.setOnClickListener(this);
disconnect_btn.setOnClickListener(this);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
speakerButton = (ToggleButton) findViewById(R.id.speaker_btn);
speakerButton.setOnCheckedChangeListener(this);
muteButton = (ToggleButton) findViewById(R.id.mute_btn);
muteButton.setOnCheckedChangeListener(this);
logTextBox = (EditText) findViewById(R.id.log_text_box);
outgoingTextBox = (EditText) findViewById(R.id.outgoing_client);
clientNameTextBox = (EditText) findViewById(R.id.client_name);
clientNameTextBox.setText(DEFAULT_CLIENT_NAME);
capabilitesButton = (Button) findViewById(R.id.capabilites_button);
capabilitesButton.setOnClickListener(this);
outgoingCheckBox = (CheckBox) findViewById(R.id.outgoing);
incomingCheckBox = (CheckBox) findViewById(R.id.incoming);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (MenuItems.Speaker == true) {
speakerButton.setVisibility(View.VISIBLE);
} else {
speakerButton.setVisibility(View.INVISIBLE);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, outgoingCheckBox.isChecked(),
incomingCheckBox.isChecked());
}
private void syncMainButton() {
handler.post(new Runnable() {
public void run() {
if (IncomingPhone.decodedString.length() != 0) {
if (phone.isConnected()) {
switch (phone.getConnectionState()) {
default:
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case DISCONNECTED:
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case CONNECTED:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
case CONNECTING:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
}
} else if (phone.hasPendingConnection()) {
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
} else {
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
}
/*
* else { Toast.makeText(getApplicationContext(),
* "TRY AGAIN!", Toast.LENGTH_SHORT).show(); }
*/
}
}
});
}
public void onBackPressed() {
phone.disconnect();
incomingAlert = null;
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
in.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(in);
finish();
}
class TokenTask extends AsyncTask<Void, Void, Void> {
String message;
JSONObject jsonResponse;
int crash_app;
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(AUTH_PHP_SCRIPT);
try {
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
IncomingPhone.decodedString = IncomingPhone.capabilityToken
.replace("\"", "");
}
}
} catch (Exception e) {
crash_app = 5;
message = "Something went wrong. Please try again later.";
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (status.equals("success")) {
final Handler handler12 = new Handler();
handler12.postDelayed(new Runnable() {
public void run() {
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton
.setBackgroundResource(R.drawable.light_green_connect);
}
}, 3000);
}
if (status.equals("failure")) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
// mainButton.setBackgroundColor(Color.parseColor("#4ca64c"));
mainButton.setBackgroundResource(R.drawable.dark_green_connect);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
}
}
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
if (phone.handleIncomingIntent(getIntent())) {
showIncomingAlert();
addStatusMessage(R.string.got_incoming);
if (Utils.isNetworkAvailable(IncomingPhoneActivity.this)) {
syncMainButton();
} else {
Toast.makeText(IncomingPhoneActivity.this,
"No internet connection!!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (phone != null) {
phone.setListeners(null, null, null);
phone = null;
}
}
#Override
public void onClick(View view) {
if ((view.getId() == R.id.d_call) || (view.getId() == R.id.d_call_btn)) {
phone.disconnect();
incomingAlert = null;
phone.setSpeakerEnabled(false);
phone.setCallMuted(false);
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
startActivity(in);
finish();
}
if ((view.getId() == R.id.call) || (view.getId() == R.id.call_btn)) {
} else if (view.getId() == R.id.capabilites_button) {
phone.login(clientNameTextBox.getText().toString(),
outgoingCheckBox.isChecked(), incomingCheckBox.isChecked());
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (group.getId() == R.id.input_select) {
if (checkedId == R.id.input_number) {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_PHONE);
outgoingTextBox.setHint(R.string.outgoing_number);
} else {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_TEXT);
outgoingTextBox.setHint(R.string.outgoing_client);
}
outgoingTextBox.setText("");
}
}
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (button.getId() == R.id.speaker_btn) {
phone.setSpeakerEnabled(isChecked);
} else if (button.getId() == R.id.mute_btn) {
phone.setCallMuted(isChecked);
}
}
private void addStatusMessage(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
logTextBox.append('-' + message + '\n');
}
});
}
private void addStatusMessage(int stringId) {
addStatusMessage(getString(stringId));
}
private void showIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert == null) {
notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.play();
break;
case AudioManager.RINGER_MODE_VIBRATE:
long pattern[] = { 0, 500, 200, 300, 500 };
vibrator.vibrate(pattern, 0);
break;
case AudioManager.RINGER_MODE_NORMAL:
r.play();
break;
}
incomingAlert = new AlertDialog.Builder(
IncomingPhoneActivity.this)
.setTitle(R.string.incoming_call)
.setCancelable(false)
.setMessage(R.string.incoming_call_message)
.setPositiveButton(R.string.answer,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.acceptConnection();
disconnect_btn
.setVisibility(View.VISIBLE);
mainButton.setVisibility(View.GONE);
incomingAlert = null;
}
})
.setNegativeButton(R.string.ignore,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.ignoreIncomingConnection();
incomingAlert = null;
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(
DialogInterface dialog) {
phone.ignoreIncomingConnection();
}
}).create();
incomingAlert.show();
}
}
});
}
private void hideIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert != null) {
incomingAlert.dismiss();
incomingAlert = null;
}
}
});
}
#Override
public void onLoginStarted() {
addStatusMessage(R.string.logging_in);
}
#Override
public void onLoginFinished() {
addStatusMessage(phone.canMakeOutgoing() ? R.string.outgoing_ok
: R.string.no_outgoing_capability);
addStatusMessage(phone.canAcceptIncoming() ? R.string.incoming_ok
: R.string.no_incoming_capability);
syncMainButton();
}
#Override
public void onLoginError(Exception error) {
if (error != null)
addStatusMessage(String.format(getString(R.string.login_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.login_error_unknown);
syncMainButton();
}
#Override
public void onIncomingConnectionDisconnected() {
hideIncomingAlert();
addStatusMessage(R.string.incoming_disconnected);
syncMainButton();
}
#Override
public void onConnectionConnecting() {
addStatusMessage(R.string.attempting_to_connect);
syncMainButton();
}
#Override
public void onConnectionConnected() {
addStatusMessage(R.string.connected);
syncMainButton();
}
#Override
public void onConnectionFailedConnecting(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.couldnt_establish_outgoing_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.couldnt_establish_outgoing);
}
#Override
public void onConnectionDisconnecting() {
addStatusMessage(R.string.disconnect_attempt);
syncMainButton();
}
#Override
public void onConnectionDisconnected() {
addStatusMessage(R.string.disconnected);
syncMainButton();
}
#Override
public void onConnectionFailed(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.connection_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.connection_error);
syncMainButton();
}
#Override
public void onDeviceStartedListening() {
addStatusMessage(R.string.device_listening);
}
#Override
public void onDeviceStoppedListening(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.device_listening_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.device_not_listening);
}
}
Hey here is the code in which is for placeId by nearest places but I want to take location by its name. Like if I want any location and write its name it will give locations containing name of location because i cant get desired locations if i search by lat and long. I just get some popular locations only.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
#SuppressWarnings("deprecation")
public class Places extends Activity implements OnItemClickListener {
private Handler mHandler;
private JSONObject location;
protected ListView placesList;
protected LocationManager lm;
protected MyLocationListener locationListener;
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);
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, "",
getString(R.string.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(R.string.enable_gps_title)
.setMessage(getString(R.string.enable_gps))
.setPositiveButton(R.string.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, "",
getString(R.string.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");
Utility.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 (!Utility.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(R.string.check_in_title)
.setMessage(
String.format(getString(R.string.check_in_at),
name))
.setPositiveButton(R.string.checkin,
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());
Utility.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) {
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) {
}
}
}
I have made a program in which i am fetching list of all my Facebook Friends with their name, dob and profile picture, but i have decided to use tabs in my existing program therefore, i have also written code for that, but whenever i run my app, every time i am getting tabs but not getting list of friends..
In my case i am not getting FriendsList Activity data in TabSample Class, why?
SplashScreen.java:-
private final static int FACEBOOK_AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
private final static int FRIENDS_LIST_ACTIVITY = 1;
public void onRequestReceived(int result, String message) {
Log.d(LOG_TAG, "onRequestReceived(" + result + ")");
if(isFinishing())
return;
switch (result) {
case FacebookRequest.COMPLETED:
Intent intent = new Intent(this, com.chr.tatu.sample.friendslist.TabSample.class);
intent.putExtra("FRIENDS", message);
while (System.currentTimeMillis() - startTime < DELAY) {
try { Thread.sleep(50); } catch (Exception e) {}
}
startActivityForResult(intent, FRIENDS_LIST_ACTIVITY);
isLoadingFriends = false;
break;
case FacebookRequest.IO_EXCEPTION:
case FacebookRequest.FILE_NOT_FOUND_EXCEPTION:
case FacebookRequest.MALFORMED_URL_EXCEPTION:
case FacebookRequest.FACEBOOK_ERROR:
FacebookUtility.displayMessageBox(this, this.getString(R.string.friends_error));
onButton();
break;
}
}
FriendsList.java:-
public class FriendsList extends Activity implements FacebookRequest, OnItemClickListener {
private static String LOG_TAG = "FriendsList";
private static JSONArray jsonArray;
private static ListView friendsList;
private Handler mHandler;
private Button saveGreeting;
public void onCreate(Bundle savedInstanceState) {
mHandler = new Handler();
super.onCreate(savedInstanceState);
try {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getActionBar().hide();
} catch (Exception e) {}
setContentView(R.layout.friends_list_screen);
try {
setProgressBarIndeterminateVisibility(false);
} catch (Exception e) {}
init();
saveGreeting = (Button) findViewById(R.id.greeting);
saveGreeting.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
customGreeting(v);
}
});
}
public void customGreeting(View v) {
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://google.com/"));
startActivity(myWebLink);
}
#Override
public void onDestroy() {
super.onDestroy();
exit();
}
private void exit() {
if (friendsList != null)
friendsList.setAdapter(null);
friendsList = null;
jsonArray = null;
GetProfilePictures.clear();
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
exit();
}
private void init() {
friendsList = (ListView) findViewById(R.id.friends_list);
friendsList.setOnItemClickListener(this);
friendsList.setAdapter(new FriendListAdapter(this));
friendsList.setTextFilterEnabled(true);
friendsList.setDivider(null);
friendsList.setDividerHeight(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(LOG_TAG, "onCreateOptionsMenu()");
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
/**
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(LOG_TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case R.id.menu_refresh:
FacebookUtility.logout(this);
setProgressBarInDVisibility(true);
return true;
case R.id.retry_button:
GetProfilePictures.clear();
init();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
**/
public void onRequestReceived(int result, String message) {
Log.d(LOG_TAG, "onRequestReceived(" + result + ")");
if(isFinishing())
return;
// setProgressBarInDVisibility(false);
switch (result) {
case FacebookRequest.COMPLETED:
FacebookUtility.clearSession(this);
finish();
break;
case FacebookRequest.IO_EXCEPTION:
case FacebookRequest.FILE_NOT_FOUND_EXCEPTION:
case FacebookRequest.MALFORMED_URL_EXCEPTION:
case FacebookRequest.FACEBOOK_ERROR:
FacebookUtility.displayMessageBox(this, this.getString(R.string.logout_failed));
break;
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Log.d(LOG_TAG, "onItemClick()");
try {
final long friendId;
friendId = jsonArray.getJSONObject(position).getLong("uid");
String name = jsonArray.getJSONObject(position).getString("name");
new AlertDialog.Builder(this).setTitle(R.string.post_on_wall_title)
.setMessage(String.format(getString(R.string.post_on_wall), name))
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Bundle params = new Bundle();
params.putString("to", String.valueOf(friendId));
params.putString("caption", getString(R.string.app_name));
params.putString("description", getString(R.string.app_desc));
params.putString("picture", FacebookUtility.HACK_ICON_URL);
params.putString("name", getString(R.string.app_action));
FacebookUtility.facebook.dialog(FriendsList.this, "feed", params,
(DialogListener) new PostDialogListener());
}
}).setNegativeButton(R.string.no, null).show();
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(FriendsList.this, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
public class FriendListAdapter extends BaseAdapter implements SectionIndexer {
private LayoutInflater mInflater;
private GetProfilePictures picturesGatherer = null;
FriendsList friendsList;
private String[] sections;
Hashtable<Integer, FriendItem> listofshit = null;
public FriendListAdapter(FriendsList friendsList) {
Log.d(LOG_TAG, "FriendListAdapter()");
this.friendsList = friendsList;
sections = new String[getCount()];
listofshit = new Hashtable<Integer, FriendItem>();
for (int i = 0; i < getCount(); i++) {
try {
sections[i] = jsonArray.getJSONObject(i).getString("name").substring(0);
sections[i] = jsonArray.getJSONObject(i).getString("birthday").substring(1);
} catch (JSONException e) {
sections[i] = "";
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
}
}
if (picturesGatherer == null) {
picturesGatherer = new GetProfilePictures();
}
picturesGatherer.setAdapterForListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
public int getCount() {
Log.d(LOG_TAG, "getCount()");
if (jsonArray == null)
return 0;
return jsonArray.length();
}
public Object getItem(int position) {
Log.d(LOG_TAG, "getItem()");
return listofshit.get(position);
}
public long getItemId(int position) {
Log.d(LOG_TAG, "getItemId()");
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG, "getView(" + position + ")");
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
}
FriendItem friendItem;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_friend, null);
friendItem = new FriendItem();
convertView.setTag(friendItem);
}
else {
friendItem = (FriendItem) convertView.getTag();
}
friendItem.friendPicture = (ImageView) convertView.findViewById(R.id.picture_square);
friendItem.friendName = (TextView) convertView.findViewById(R.id.name);
friendItem.friendDob = (TextView) convertView.findViewById(R.id.dob);
friendItem.friendLayout = (RelativeLayout) convertView.findViewById(R.id.friend_item);
try {
String uid = jsonObject.getString("uid");
String url = jsonObject.getString("pic_square");
friendItem.friendPicture.setImageBitmap(picturesGatherer.getPicture(uid, url));
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}
public int getPositionForSection(int position) {
return position;
}
public int getSectionForPosition(int position) {
return position;
}
public Object[] getSections() {
return sections;
}
}
class FriendItem {
TextView friendDob;
int id;
ImageView friendPicture;
TextView friendName;
RelativeLayout friendLayout;
}
}
TabSample.java:-
public class TabSample extends TabActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabmain);
setTabs() ;
}
private void setTabs()
{
addTab("All", R.drawable.tab_menu, FriendsList.class);
addTab("Current Month", R.drawable.tab_offers, FriendsList.class);
addTab("Current Week", R.drawable.tab_location, FriendsList.class);
addTab("Today", R.drawable.tab_reservation, FriendsList.class);
}
private void addTab(String labelId, int drawableId, Class<?> c)
{
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
}
Please tell me where i have to add this code :
Bundle extras = getIntent().getExtras();
String response = extras.getString("FRIENDS");
Log.d(LOG_TAG, "onCreate()" + response);
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this, this.getString(R.string.json_failed));
}
and any other code need to move from FriendsList class to TabSample Class
I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
e.printStackTrace();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
thread.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);
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.