Gcm Notification only comes in my own device - java

I am new in Gcm and I want to send notification using gcm to my spacific users of my app but notification comes only in my own device
Here is my code
MainActivity.java
public class MainActivity extends ActionBarActivity {
private GoogleCloudMessaging gcm;
String regid;
CheckBox isdriver;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
String user_name = "";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String TAG = "MainActivity";
String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";
Utils utils;
private Context context = MainActivity.this;
private ProgressDialog pb;
private EditText username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
utils = new Utils(this);
isdriver = (CheckBox) findViewById(R.id.isDriver);
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
} catch (IOException ex) {
msg = ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
Log.i(TAG, "onPostExecute : " + msg);
if (!msg.equalsIgnoreCase("SERVICE_NOT_AVAILABLE")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("server_response", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
} else {
utils.showToast("Error : " + msg
+ "\nPlease check your internet connection");
hidePB();
}
}
// Define the Handler that receives messages from the thread and
// update the progress
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString(
"server_response");
if ((null != aResponse)) {
Log.i(TAG, " sendRegistrationIdToBackend();");
sendRegistrationIdToBackend();
} else {
}
}
};
}.execute(null, null, null);
}
/**
* Sends the registration ID to your server over HTTP, so it can use
* GCM/HTTP or CCS to send messages to your app. Not needed for this demo
* since the device sends upstream messages to a server that echoes back the
* message using the 'from' address in the message.
*/
public void sendRegistrationIdToBackend() {
Log.i(TAG, "sendRegistrationIdToBackend");
Thread thread = new Thread() {
#Override
public void run() {
try {
httpclient = new DefaultHttpClient();
// yahan reg id ki server webserivcice dalegi
httppost = new HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/save_reg_id.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username",
user_name));
nameValuePairs.add(new BasicNameValuePair("reg_id", regid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
Log.i(TAG, "Response : " + response);
if (response != null) {
if (response
.equalsIgnoreCase("Username already registered")) {
utils.showToast("Username already registered");
hidePB();
} else {
if (response
.equalsIgnoreCase("New Device Registered successfully")) {
utils.savePreferences(Utils.UserName, user_name);
// Persist the regID - no need to register
// again.
utils.storeRegistrationId(regid);
utils.showToast("Device registration successful");
}
}
}
} catch (Exception e) {
hidePB();
Log.d(TAG, "Exception : " + e.getMessage());
}
}
};
thread.start();
}
public void onClick(View view) {
if (view.getId() == R.id.btnsave) {
username = (EditText) findViewById(R.id.username);
user_name = username.getText().toString().trim();
if (user_name.length() > 0) {
Log.d(TAG, "startRegistration");
showPB("Registering the device");
startRegistration();
/*if(isdriver.isChecked()){
Log.i(TAG,"Driver reg id");
Log.d(TAG, utils.getFromPreferences(user_name));
}*/
Intent i = new Intent(MainActivity.this,BookingActivity.class);
i.putExtra("username",user_name);
i.putExtra("regid",regid);
startActivity(i);
} else {
Log.d(TAG, "Username empty");
}
}
}
void startRegistration() {
if (checkPlayServices()) {
// If this check succeeds, proceed with normal processing.
// Otherwise, prompt user to get valid Play Services APK.
Log.i(TAG, "Google Play Services OK");
gcm = GoogleCloudMessaging.getInstance(this);
regid = utils.getRegistrationId();
/*if(isdriver.isChecked()){
utils.savePreferences(user_name, regid);
Log.d(TAG,utils.getFromPreferences(user_name));
}*/
System.out.println(regid);
if (regid.isEmpty()) {
registerInBackground();
} else {
Log.i(TAG, "Reg ID Not Empty");
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Log.i(TAG, "No Google Play Services...Get it from the store.");
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
void showPB(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pb = new ProgressDialog(MainActivity.this);
pb.setMessage(message);
pb.show();
}
});
}
void hidePB() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pb != null && pb.isShowing())
pb.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BookingActivity.java
public class BookingActivity extends ActionBarActivity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
Utils utils;
Intent i;
static String TAG = "GCM DEMO";
String user_name;
String regid;
String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
i = getIntent();
registerReceiver(broadcastReceiver, new IntentFilter(
"CHAT_MESSAGE_RECEIVED"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
String message = b.getString("message");
Log.i(TAG, " Received in Activity " + message + ", NAME = "
+ i.getStringExtra("username"));
}
};
public void onClick(final View view) {
if (view == findViewById(R.id.booking)) {
sendMessage();
//clearMessageTextBox();
}
}
public void sendMessage() {
final String messageToSend = "Driver you are now booked by: "+i.getStringExtra("username");
if (messageToSend.length() > 0) {
Log.i(TAG, "sendMessage");
Thread thread = new Thread() {
#Override
public void run() {
try {
httpclient = new DefaultHttpClient();
httppost = new
HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/gcm_engine.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("message",
messageToSend));
nameValuePairs.add(new BasicNameValuePair(
"registrationIDs", i.getStringExtra("regid")));
nameValuePairs.add(new BasicNameValuePair("apiKey",
API_KEY));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
Log.i(TAG, "Response : " + response);
if (response.trim().isEmpty()) {
Log.d(TAG, "Message Not Sent");
}
} catch (Exception e) {
Log.d(TAG, "Exception : " + e.getMessage());
}
}
};
thread.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_booking, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Utils.java
public class Utils {
static Context context;
public static final String TAG = "Utils";
public static final String UserName = "UserName";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
public Utils(Context context) {
Utils.context = context;
}
public SharedPreferences getGCMPreferences() {
return context.getSharedPreferences(((ActionBarActivity) context)
.getClass().getSimpleName(), Context.MODE_PRIVATE);
}
public void savePreferences(String key, String value) {
final SharedPreferences prefs = getGCMPreferences();
Log.i(TAG, key + " : " + value);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public String getFromPreferences(String key) {
final SharedPreferences prefs = getGCMPreferences();
String value = prefs.getString(key, "");
if (value.isEmpty()) {
Log.i(TAG, key + " not found.");
return "";
}
return value;
}
String getRegistrationId() {
final SharedPreferences prefs = getGCMPreferences();
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
Integer.MIN_VALUE);
int currentVersion = getAppVersion();
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
static int getAppVersion() {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
public void storeRegistrationId(String regId) {
final SharedPreferences prefs = getGCMPreferences();
int appVersion = Utils.getAppVersion();
Log.i(TAG, "Saving regId on app version " + appVersion);
Log.i(TAG, "Reg ID : " + regId);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public String getCurrentIPAddress() {
return "http://192.168.0.101/";
}
public void showToast(final String txt) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, txt, Toast.LENGTH_LONG).show();
}
});
}
}
In my app user login as simple user or login as driver if user login and register with gcm and press booked button notification send to specific driver

It is just because you are calling your own device id to get notified,Please check out the backend , all the registered users must have their own device id's . Make sure their is different device id generated while a new Registration happens.

Related

Twitter Intregration not working in fragment?

I am using twitter4j lib,but it is not working in fragment.I have created a twitterShare java class but the fragment class is not migrating to the twitter class.I also added the twitter class but its not working.
Here is my code of fragment class. #Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button8:
try{
Intent intent=new Intent(getActivity(),TwitterView.class);
startActivity(intent);
}
catch (NullPointerException e){
AlertDialog alert=new AlertDialog.Builder(context).create();
alert.setMessage(e.getMessage());
}
break;
Here is my code of TwitterView.java.
`
public class TwitterView extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "twitter_oauth";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
private static final String PREF_USER_NAME = "befriendtest";
/* Any number for uniquely distinguish your request */
public static final int WEBVIEW_REQUEST_CODE = 100;
private ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private EditText mShareEditText;
private TextView userName;
private View loginLayout;
private View shareLayout;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initTwitterConfigs();
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/* Check if required twitter keys are set */
if (TextUtils.isEmpty(consumerKey) || TextUtils.isEmpty(consumerSecret)) {
Toast.makeText(this, "Twitter key and secret not configured", LENGTH_LONG).show();
return ;
}
loginLayout= findViewById(R.id.login_layout);
shareLayout= findViewById(R.id.share_layout);
mShareEditText=(EditText)findViewById(R.id.share_text);
userName=(TextView)findViewById(R.id.user_name);
loginLayout.setOnClickListener(this);
shareLayout.setOnClickListener(this);
/* Initialize application preferences */
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
/* if already logged in, then hide login layout and show share layout */
if (isLoggedIn) {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
String username = mSharedPreferences.getString(PREF_USER_NAME, "");
userName.setText(getResources ().getString(R.string.hello) + username);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(callbackUrl)) {
String verifier = uri.getQueryParameter(oAuthVerifier);
try {
/* Getting oAuth authentication token */
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
/* Getting user id form access token */
long userID = accessToken.getUserId();
final User user = twitter.showUser(userID);
final String username = user.getName();
/* save updated token */
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
userName.setText(getString(R.string.hello) + username);
} catch (Exception e) {
Log.e("Failed to login Twitter!!", e.getMessage());
}
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_layout:
loginToTwitter();
break;
case R.id.share_layout:
final String status = mShareEditText.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(this, "Message is empty!!", Toast.LENGTH_SHORT).show();
}
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
/* Storing oAuth tokens to shared preferences */
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.putString(PREF_USER_NAME, username);
e.apply();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
/* Reading twitter essential configuration parameters from strings.xml */
private void initTwitterConfigs() {
consumerKey = BuildConfig.CONSUMER_KEY;
consumerSecret = BuildConfig.CONSUMER_SECRET;
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = BuildConfig.OUTH_VERIFIER;
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(oAuthVerifier);
/**
* Loading twitter login page on webview for authorization
* Once authorized, results are received at onActivityResult
* */
final Intent intent = new Intent(this, WebActivity.class);
intent.putExtra(WebActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
long userID = accessToken.getUserId();
final User user = twitter.showUser(userID);
String username = user.getName();
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
userName.setText(TwitterView.this.getResources().getString(
R.string.hello) + username);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
class updateTwitterStatus extends AsyncTask<String,String,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TwitterView.this);
pDialog.setMessage("Posting to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
String status = params[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
StatusUpdate statusUpdate = new StatusUpdate(status);
twitter4j.Status response = twitter.updateStatus(statusUpdate);
Log.d("Status", response.getText());
} catch (TwitterException e) {
Log.d("Failed to post!", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
/* Dismiss the progress dialog after sharing */
pDialog.dismiss();
Toast.makeText(TwitterView.this, "Posted to Twitter!", LENGTH_SHORT).show();
// Clearing EditText field
mShareEditText.setText("");
}
}
}

Connect bluetooth from android to computer(paired devices)

So, i want my application to connect to my pc and then use android as a touch pad. Iv been doing a lot of research on the net, but I didn't find anywhere how to exactly connect my phone to pc. I made the pair device function and everything else, I just need the connection method, or at least how could it be done. Here is the code:
public class MainActivity extends Activity {
private BluetoothAdapter adapter;
private Intent turnOn;
private Set<BluetoothDevice> pairedDevices;
private ListView lv;
private Button on,off,pairedDevice,discoverable,nearDevices;
private List<BluetoothDevice> discoveredDevices = new ArrayList<BluetoothDevice>();
private Handler mHandler;
private static final UUID MY_UUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
buttonFunc();
find();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void lista(int i){
if(i==0) {
final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this, discoveredDevices);
lv.setAdapter(deviceAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pairDevice(deviceAdapter.getItem(position));
Message.message(MainActivity.this, deviceAdapter.getItem(position).getName().toString());
}
});
}
else if(i == 1){
List<BluetoothDevice> vecUpareni = new ArrayList<BluetoothDevice>();
for (BluetoothDevice bt:adapter.getBondedDevices()){
vecUpareni.add(bt);
}
final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this, vecUpareni);
lv.setAdapter(deviceAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String adresa = deviceAdapter.getItem(position).getAddress();
Method connect = getConnectMethod();
BluetoothDevice device = deviceAdapter.getItem(position);
}
});
}
}
private Method getConnectMethod () {
try {
return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
} catch (NoSuchMethodException ex) {
Message.message(MainActivity.this , "Unable to connect");
return null;
}
}
private void pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
}
public void buttonFunc(){
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn,0);
Message.message(MainActivity.this , "Bluetooth enabled");
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.disable();
}
});
pairedDevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lista(1);
}
});
discoverable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(discoverableIntent);
}
});
nearDevices.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista(0);
}
});
}
public void find(){
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
adapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
discoveredDevices.add(device);
Message.message(MainActivity.this, "Found device " + device.getName());
lista(0);
}
}
};
public void initialize(){
on = (Button) findViewById(R.id.ON);
off = (Button) findViewById(R.id.OFF);
pairedDevice = (Button) findViewById(R.id.pairedDevices);
nearDevices = (Button) findViewById(R.id.nearDevices);
discoverable = (Button) findViewById(R.id.makeDiscoverable);
lv = (ListView) findViewById(R.id.listaUredjaja);
adapter = BluetoothAdapter.getDefaultAdapter();
if(adapter == null){
System.out.close();
}
if(adapter.isEnabled()){
Message.message(MainActivity.this , "Enabled");
}
else{
Message.message(MainActivity.this , "Not enabled");
}
}
}
And here is the server that is on my pc that is awaiting connection:
public class Mejn {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
Mejn sampleSPPServer=new Mejn();
sampleSPPServer.startServer();
}
}
So, while looking more, found this somewhere and put it in my code, here is the code:
public class MainActivity extends Activity {
private BluetoothAdapter adapter;
private Intent turnOn;
private Set<BluetoothDevice> pairedDevices;
private ListView lv;
private Button on,off,pairedDevice,discoverable,nearDevices;
private List<BluetoothDevice> discoveredDevices = new ArrayList<BluetoothDevice>();
private BluetoothSocket btSocket = null;
public OutputStream outStream;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "C01885BD823C";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
buttonFunc();
find();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void lista(int i){
if(i==0) {
final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this, discoveredDevices);
lv.setAdapter(deviceAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pairDevice(deviceAdapter.getItem(position));
Message.message(MainActivity.this, deviceAdapter.getItem(position).getName().toString());
}
});
}
else if(i == 1){
List<BluetoothDevice> vecUpareni = new ArrayList<BluetoothDevice>();
for (BluetoothDevice bt:adapter.getBondedDevices()){
vecUpareni.add(bt);
}
final DeviceAdapter deviceAdapter = new DeviceAdapter(MainActivity.this, vecUpareni);
lv.setAdapter(deviceAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice device = adapter.getRemoteDevice(deviceAdapter.getItem(position).getAddress());
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Message.message(MainActivity.this , "In onResume() and socket create failed: " + e.toString() + ".");
}
adapter.cancelDiscovery();
try {
btSocket.connect();
System.out.print("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Message.message(MainActivity.this , "In onResume() and unable to close socket during connection failure" + e2.getMessage().toString() + ".");
}
}
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Message.message(MainActivity.this , "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
System.out.print("\n...Sending message to server...");
String message = "Hello from Android.\n";
System.out.print("\n\n...The message that we will send to the server is: "+message);
byte[] msgBuffer = message.getBytes();
try {
outStream.write(message.getBytes());
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
Message.message(MainActivity.this , msg);
}
}
});
}
}
private Method getConnectMethod () {
try {
return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
} catch (NoSuchMethodException ex) {
Message.message(MainActivity.this , "Unable to connect");
return null;
}
}
private void pairDevice(BluetoothDevice device) {
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
}
public void buttonFunc(){
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn,0);
Message.message(MainActivity.this , "Bluetooth enabled");
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.disable();
}
});
pairedDevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lista(1);
}
});
discoverable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(discoverableIntent);
}
});
nearDevices.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista(0);
}
});
}
public void find(){
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
adapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
discoveredDevices.add(device);
Message.message(MainActivity.this, "Found device " + device.getName());
lista(0);
}
}
};
public void initialize(){
on = (Button) findViewById(R.id.ON);
off = (Button) findViewById(R.id.OFF);
pairedDevice = (Button) findViewById(R.id.pairedDevices);
nearDevices = (Button) findViewById(R.id.nearDevices);
discoverable = (Button) findViewById(R.id.makeDiscoverable);
lv = (ListView) findViewById(R.id.listaUredjaja);
adapter = BluetoothAdapter.getDefaultAdapter();
if(adapter == null){
System.out.close();
}
if(adapter.isEnabled()){
Message.message(MainActivity.this , "Enabled");
}
else{
Message.message(MainActivity.this , "Not enabled");
}
}
}
And code for server:
/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class Mejn {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
Mejn sampleSPPServer=new Mejn();
sampleSPPServer.startServer();
}
}

How to integrate with jsonwebservices in Android?

I'm implementing json_web services in my Android application. I want to send the json data on jsonwebservices which is created in Java. When I run the application data does not send from the Android and does not show any error and also does not show any type of exception.
How can I identify whether my data is sent or not?
Here is my Activity Code:
public class Login extends Activity
{
Button btnLogin;
EditText etextUsername , etextPassword;
String strUserName , strPassWord ;
ProgressDialog pDialog;
JSONObject jObject ;
SharedPreferences.Editor editor;
SharedPreferences sharedPref1;
String str_Device_IP_Address=null;
JSONArray user = null;
String pref_filename = "IP_ADDRESS";
static final String KEY_REQUEST_ID = "RequestId";
static final String KEY_REQUEST_CODE = "RequestCode";
static final String KEY_CHANNEL_ID = "ChannelId";
static final String KEY_IP_ADDRESS="IPAddress";
static final String KEY_USERNAME="UserId";
static final String KEY_PASSWORD="Password";
static final String KEY_REQUEST="Request";
static final String KEY_VENDOR_ID="VendorId";
String RequestId="77777";
String RequestCode="001";
String stringChannelId="MobileApp";
String strIpAddress = null;
private String textToEncrypt = "Hi, this is a test to check its gone work or not.";
String encrypted = "MzA3RDBCMjMxMjQzNzcxREUxMUYxNjg1NzgwOTU1MjU1M0FDOUZEN0M3Q0JGQ0Q5MTI2NEIyNTE2"
+ "OTQwQTc3NjM2QTBCRDFDMUEyNkUwRjlDMzQwN0U0MEI0NDg2M0JBMDU1OThCNTI1NTZCMEFGNjk1NjJFNzZBMUE0NzM4NTQ=";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Context context = getApplicationContext();
connectWithHttpGet_IpAddress();
etextUsername = (EditText)findViewById(R.id.edittext_username);
etextPassword = (EditText)findViewById(R.id.edittext_password);
btnLogin=(Button)findViewById(R.id.button_Login);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (!isOnline())
{
showNoConnectionDialog(Login.this);
}
else
{
connectWithHttpGet_LoginData();
}
}
});
}
private void connectWithHttpGet_LoginData()
{
class GetJSONParse extends AsyncTask<String, Integer, JSONObject>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
str_Device_IP_Address=sharedPref1.getString("ip_address", "a\n");
System.out.println("strCode in Gsk_Demo ="+str_Device_IP_Address);
strUserName = etextUsername.getText().toString().trim();
strPassWord = etextPassword.getText().toString().trim();
pDialog = new ProgressDialog(Login.this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("Progress Dialog!!!!!!!!!!!!!!!!!!!!!!!");
}
#Override
protected JSONObject doInBackground(String... args)
{
String strUrl = "http://test.xxxxxx.com/cms/json/w2iWS";
JSONParser jParser = new JSONParser();
Log.e("DoinBackground !!!!!","Method");
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(strUrl);
String jsonString=json.toString();
Log.e("jsonString in DoinBackground !!!!!","Method" + jsonString);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
// Getting JSON Array
user = json.getJSONArray( KEY_REQUEST_ID );
JSONObject jsonObject = user.getJSONObject(0);
jsonObject.put(KEY_REQUEST_CODE, RequestCode);
jsonObject.put(KEY_CHANNEL_ID, stringChannelId);
jsonObject.put(KEY_IP_ADDRESS, str_Device_IP_Address);
jsonObject.put(KEY_USERNAME, strUserName);
jsonObject.put(KEY_PASSWORD, strPassWord);
String encrypted1 = EncodeDecodeAES.encrypt(jsonObject.toString(), textToEncrypt);
System.out.println("encrypted1 =" + encrypted1);
JSONObject inner = new JSONObject();
inner.put(KEY_REQUEST, encrypted1);
inner.put(KEY_VENDOR_ID, "1");
String decrypted = EncodeDecodeAES.decrypt(jsonObject.toString(), encrypted);
System.out.println("decrypted =" + decrypted);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJSONParse getjsonparse = new GetJSONParse();
getjsonparse.execute();
}
// Get Ip Address
private void connectWithHttpGet_IpAddress() {
class httpGetAsynchTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
String url = "http://api.externalip.net/ip";
Log.e("!!STRING URL DATE DETAIL", "" + url);
HttpGet httpGet = new HttpGet(url);
Log.e("", "" + httpGet);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.e("HTTP.RESPONSE.DATE.DTAIL", "" + httpResponse);
System.out.println("HTTPRESPONSE");
InputStream inpustream = httpResponse.getEntity()
.getContent();
InputStreamReader inputstreamreader = new InputStreamReader(
inpustream);
BufferedReader bufferedreader = new BufferedReader(
inputstreamreader);
StringBuilder stringbuilder = new StringBuilder();
Log.e("", "" + stringbuilder);
String strbuffer = null;
while ((strbuffer = bufferedreader.readLine()) != null)
{
stringbuilder.append(strbuffer);
}
String strResponse = stringbuilder.toString();
/****************** Code For Shared Preferences **************************************/
sharedPref1 = getSharedPreferences(pref_filename, 0);
editor = sharedPref1.edit();
editor.putString("ip_address", strResponse);
Log.e("Returning value of doInBackground REsponse:" ,strResponse);
System.out.println("IPADDRESS IN DOIN BACKGRAOUND");
editor.commit();
/***************** Code For Shared Preferences **************************************/
}
catch (ClientProtocolException cpe) {
cpe.printStackTrace();
Log.e("Exception generates caz of httpResponse :", "-"
+ cpe);
}
catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Second exception generates caz of httpResponse :",
"-" + ioe);
}
return null;
}
}
httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
httpGetAsyncTask.execute();
}
public static void showNoConnectionDialog(final Login login)
{
AlertDialog.Builder builder = new AlertDialog.Builder(login);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
login.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
}
Asynctask is not invoked
JSONParse jp =new JSONParse();
jp.execute(params);
http://developer.android.com/reference/android/os/AsyncTask.html
public final AsyncTask<Params, Progress, Result> execute (Params... params)
Executes the task with the specified parameters.
You had no invoked asynctask before
GetJSONParse get = new GetJSONParse();
get.execute(params);
And you said i can't see the log message in doInbackground. i just ran your code and i can see the log

How to get user details after successful Login through Facebook

I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity

Cleaning up Android Main Activity Code

I'm a real noob when it comes to Java and OOP in general. I'm having issues with my app crashing and I think it's because my Main Activity is cluttered and my overall program is not structured properly. Can anyone advise me on how to clean up the following code to make things run smoother and have a better app structure? I think I need to separate things into different classes and keep most of the functions in different classes, but I'm new and really not sure. I keep getting an ANR error when I run the app on a phone (keyDispatchingTimedOut error) and I think my unorganized code is causing this. Any help would be great! Thanks.
package com.example.www;
public class MainActivity extends Activity {
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
private Button send_button;
EditText msgTextField;
private LocationManager locManager;
private LocationListener locListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature( Window.FEATURE_NO_TITLE );
setContentView(R.layout.main);
mDrawer.open();
final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
final String phone = shared.getString("PHONE", "");
String usr_id = shared.getString("USR_ID", null);
if(phone == null) {
TextView text = (TextView)findViewById(R.id.textView1);
text.setText("Please Enter Your Phone Number");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Enter Your Phone Number");
alert.setMessage("You must enter your phone number in order to use this application");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
if (value.length() == 10) {
Editor editor = shared.edit();
editor.putString("PHONE", value);
editor.commit();
}
}
});
alert.show();
}
Button profile = (Button) findViewById(R.id.button1);
profile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, PreferencesActivity.class));
}
});
if (usr_id == null) {
char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
Random r = new Random(System.currentTimeMillis());
char[] id = new char[8];
for (int i = 0; i < 8; i++) {
id[i] = chars[r.nextInt(chars.length)];
}
usr_id = new String(id);
Editor editor = shared.edit();
editor.putString("USR_ID", usr_id);
editor.commit();
}
final String usr_id1 = shared.getString("USR_ID", "none");
send_button = (Button)findViewById(R.id.button2);
send_button.setOnClickListener(new OnClickListener() {
private boolean running = false;
private CountDownTimer timer;
public void onClick(View v) {
if(!running)
{
running = true;
timer = new CountDownTimer(4000, 1000) {
#Override
public void onFinish() {
send_button.setText("GPS Sent");
startLocation();
sendId(usr_id1, phone);
}
#Override
public void onTick(long sec) {
send_button.setText("CANCEL (" + sec / 1000 + ")");
}
}.start();
}
else
{
timer.cancel();
send_button.setText("Send GPS");
running = false;
}
}
});
}
private void startLocation()
{
//get a reference to the LocationManager
locManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get the last known position
Location loc =
locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//show the last known position
//showPosition(loc);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location location) {
showPosition(location);
}
public void onProviderDisabled(String provider){
//labelState.setText("Provider OFF");
}
public void onProviderEnabled(String provider){
//labelState.setText("Provider ON ");
}
public void onStatusChanged(String provider, int status, Bundle extras){
//Log.i("", "Provider Status: " + status);
//labelState.setText("Provider Status: " + status);
}
};
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
private void showPosition(Location loc) {
if(loc != null)
{
Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));
send(loc);
}
}
private void send(Location loc)
{
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
final String usr_id2 = shared.getString("USR_ID", "none");
if (lat != "0" && lon != "0")
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example1.php");
//HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat"
nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line
nameValuePairs.add(new BasicNameValuePair("id", usr_id2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
private void sendId(String usr_id1, String phone)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
//HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive_user.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
nameValuePairs.add(new BasicNameValuePair("id", usr_id1));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
mCloseButton.setOnClickListener( new OnClickListener() {
public void onClick( View v )
{
mDrawer.animateClose();
}
});
mOpenButton.setOnClickListener( new OnClickListener() {
public void onClick( View v )
{
if( !mDrawer.isOpened() )
mDrawer.animateOpen();
}
});
}
#Override
public void onContentChanged()
{
super.onContentChanged();
mCloseButton = (Button) findViewById( R.id.button_open );
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer );
}
}
I would encapsulate the LocationListener in a totally different class. That should shorten up most of your code and leave you with a manageable chunk to work with.
Additionally, you seem to have some HTTP post or web-request methods in your MainActivity. Take those out and put them in a different class as well. Name it something like ActivityServer or something akin to that.
In your ActivityServer class, you should make a callback and asynchronous interfaces so that you don't block the UI thread when doing web requests.

Categories