System.error NullPointer - android

I try to write to share a post on twitter but this code works on Galaxy S2 but it doesn't work in Galaxy s3...I don't know why.
At this link there is the log error:
http://it.tinypic.com/r/2wqyd1w/5
This is the code of Twitter:
public class TwitterActivity extends Activity {
private Twitter twitter;
public final String PREFS = "MyPrefsFile";
final public String CALLBACK_URL = "app://casa";
private SharedPreferences shared;
private static RequestToken requestToken=null;
private LinkedList<RequestToken> lista=new LinkedList<RequestToken>();
private int it = 0;
private String frase = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
it = getIntent().getExtras().getInt("punteggio");
frase = getIntent().getExtras().getString("frase");
shared = this.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new updateTwitterStatus().execute();
}
});
}
#Override
public void onNewIntent(Intent data) {
super.onNewIntent(data);
dealWithTwitterResponse(data);
}
class updateTwitterStatus extends AsyncTask<Void, Void, String> {
private Intent i = null;
#Override
protected String doInBackground(Void... params) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("********")
.setOAuthConsumerSecret(
"**********");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = new TwitterFactory().getInstance();
twitter = tf.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("Stringa",requestToken.toString());
Log.i("bauu", "miao");
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
return authUrl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void onResume() {
Log.i("reume","re");
super.onResume();
}
private void dealWithTwitterResponse(final Intent intent) {
Log.i("Sonod entro", "vau");
final Uri uri = intent.getData();
if (uri == null) {
Log.i("è null", "null");
}
Log.i("callback funziona", "ciao");
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
final String verifier = uri.getQueryParameter("oauth_verifier");
final String oauthToken = uri.getQueryParameter("oauth_token");
new Thread(new Runnable() {
public void run() {
try {
//
// if(requestToken==null){
// Log.i("Il TOKEN è NULL","uihuh");
// }else{
// Log.i("IL TOKEN NON E NULL","huèh ");
// }
// if(verifier==null){
// Log.i("Verifier nullo","sdg");
// }else{
// Log.i("Verifier non null","asdfg");
// }
Log.i("SOno dentro il run", "asd");
//the next line throws exception
AccessToken at = twitter.getOAuthAccessToken(
requestToken,verifier);
twitter.setOAuthAccessToken(at);
twitter.updateStatus("CHI VUOLE ESSERE SCIENZIATO?? Punteggio: "
+ it
+ " "
+ frase
+ " "
+ "www.scienze-naturali.com");
} catch (Exception e) {
e.printStackTrace();
}
}
}).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.punteggio, menu);
return true;
}
}
and this is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicazionescienza"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.applicazionescienza.MenuPrincipale"
android:label="#string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.Informazioni"
android:label="#string/title_activity_informazioni" >
</activity>
<activity
android:name="com.example.applicazionescienza.Regolamento"
android:label="#string/title_activity_regolamento" >
</activity>
<activity
android:name="com.example.applicazionescienza.Gioca"
android:label="#string/title_activity_gioca" >
</activity>
<activity
android:name="com.example.applicazionescienza.Livello"
android:label="#string/title_activity_livello" >
</activity>
<activity
android:name="com.example.applicazionescienza.Punteggio"
android:label="#string/title_activity_punteggio" >
</activity>
<activity
android:name="com.example.applicazionescienza.TwitterActivity"
android:label="#string/title_activity_twitter"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="casa"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.FacebookActivity"
android:label="#string/title_activity_facebook" >
</activity>
</application>
</manifest>
I try this code in other real device. In one device works great but in my device the same code doesn't work. Anyone can help me to understand why?

It looks like twitter is null here
AccessToken at = twitter.getOAuthAccessToken(
requestToken,verifier);
because this method is called before you run your AsyncTask which initializes your twitter variable.
Try calling this method in onPostExecute() of your AsyncTask since this method will be called when doInBackground() is finished.

Related

I want to send an message from my Android Watch to my Android Phone. Other way around is working

I want to send an message to my phone on the moment I start an app on my watch.
I can't get this to work. The other way around is working every time.
Mobile manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="marcokreeft.domotica">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:name=".ListenerService">
<intent-filter>
<!--<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />-->
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/message_path" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Watch manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="marcokreeft.domotica">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:name=".ListenerService">
<intent-filter>
<!--<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />-->
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/message_path" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Mobile listenerservice:
public class ListenerService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
if (messageEvent.getPath().equals("/message_path")) {
final String message = new String(messageEvent.getData());
Log.v("myTag", "Message path received on watch is: " + messageEvent.getPath());
Log.v("myTag", "Message received on watch is: " + message);
}
else {
super.onMessageReceived(messageEvent);
}
}
}
Wear mainactivity:
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleClient;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Build a new GoogleApiClient for the Wearable API
googleClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
}
// Connect to the data layer when the Activity starts
#Override
protected void onStart() {
super.onStart();
googleClient.connect();
}
// Send a message when the data layer connection is successful.
#Override
public void onConnected(Bundle connectionHint) {
String message = "Hello mobile\n Via the data layer";
//Requires a new thread to avoid blocking the UI
new SendToDataLayerThread("/message_path", message).start();
}
// Disconnect from the data layer when the Activity stops
#Override
protected void onStop() {
if (null != googleClient && googleClient.isConnected()) {
googleClient.disconnect();
}
super.onStop();
}
// Placeholders for required connection callbacks
#Override
public void onConnectionSuspended(int cause) { }
#Override
public void onConnectionFailed(ConnectionResult connectionResult) { }
class SendToDataLayerThread extends Thread {
String path;
String message;
// Constructor to send a message to the data layer
SendToDataLayerThread(String p, String msg) {
path = p;
message = msg;
}
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleClient).await();
for (Node node : nodes.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(googleClient, node.getId(), path, message.getBytes()).await();
if (result.getStatus().isSuccess()) {
Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName());
}
else {
// Log an error
Log.v("myTag", "ERROR: failed to send Message");
}
}
}
}
}
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(getConnectedNodesResult -> {
List<Node> nodes = getConnectedNodesResult.getNodes();
if(nodes.size() == 0){
Toast.makeText(this,"You are not connected to any mobile device",Toast.LENGTH_LONG).show();
setButtonStatus(true);
} else {
for (Node node : nodes) {
Log.i(TAG, "WEAR sending " + message + " to " + node);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, payload).setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
Log.i(TAG, "WEAR Result " + sendMessageResult.getStatus());
}
});
}
}
});
Try this code to send the details from watch to mobile after connection established.

Repeat Alarm manager in Sending SMS not Sending

I created application that if the button is click it will send SMS to the number that came from webservice. Then I use Alarm Manager to send SMS repeatedly in the number that i get from the web service. It is working fine but when I change the number that I want to send an SMS it will not work. I don't know what is wrong with my code. Here is my code.
This is my code that send an SMS.
public class EmergencyAssistance extends ActionBarActivity {
ArrayList<Objects> objectsList = new ArrayList<>();
String url = "http://192.168.254.108:8080/taxisafe3/webService/listcontact";
String urls = "http://192.168.254.108:8080/taxisafe3/webService/plate";
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String message;
String message1;
Button send;
LocationService locationService;
double lat;
double lng;
StringBuilder address;
StringBuffer smsBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_assistance);
send = (Button) findViewById(R.id.emergency);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setData();
new Task().execute(urls);
new Tasks().execute(url);
}
});
}
public class Task extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setCon1(jsonobject.getString("con1"));
objects.setCon2(jsonobject.getString("con2"));
objects.setCon3(jsonobject.getString("con3"));
objects.setCon4(jsonobject.getString("con4"));
objects.setCon5(jsonobject.getString("con5"));
objectsList.add(objects);
contact1 = objects.getCon1();
contact2 = objects.getCon2();
contact3 = objects.getCon3();
contact4 = objects.getCon4();
contact5 = objects.getCon5();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Tasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(urls);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setTaxi_plate_no(jsonobject.getString("taxi_plate_no"));
objects.setDriver_operator(jsonobject.getString("driver_operator"));
objectsList.add(objects);
message = objects.getTaxi_plate_no();
message1 = objects.getDriver_operator();
emergency();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void emergency() {
smsBody = new StringBuffer();
smsBody.append("https://maps.google.com/maps?q=");
smsBody.append(lat);
smsBody.append(",");
smsBody.append(lng);
String msgs = "[EMERGENCY!] \nTaxi plate #: " + message + "\nTaxi operator: " + message1 + "\n" + address + smsBody.toString();
try {
if (PatternChecker.isNotNull(contact1)) {
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(EmergencyAssistance.this, AlarmReceiver.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num1", contact1);
bundle.putCharSequence("msg1", msgs);
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(EmergencyAssistance.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 1000 * 60 * 1, pendingIntent);
Toast.makeText(getApplicationContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "No Number", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
public void setData() {
locationService = new LocationService(getApplication());
if(locationService.canGetLocation()){
lat = locationService.getLatitude();
lng = locationService.getLongitude();
}else{
locationService.showSettingsAlert();
}
getMyLocationAddress();
}
public void getMyLocationAddress() {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
address = new StringBuilder();
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
address.append(fetchedAddress.getAddressLine(i)).append("\n");
}
} else
Toast.makeText(getApplicationContext(),"No Address", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
This is my Alarm Receiver.
public class AlarmReceiver extends BroadcastReceiver
{
String msg;
String num;
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
num = bundle.getString("num1");
msg = bundle.getString("msg1");
//Toast.makeText(context, num + msg, Toast.LENGTH_SHORT).show();
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(num, null, msg, null, null);
}
}
This is my manifest to allow sending SMS and to register the alarm receiver.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.group.taxisafe" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<permission
android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/taxisafe"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Login"
android:label="TaxiSafe" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Home"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name=".DriverDetails"
android:label="#string/title_activity_driver_details" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".Contacts"
android:label="#string/title_activity_contacts" >
</activity>
<activity
android:name=".ReportActivity"
android:label="#string/title_activity_report" >
</activity>
<activity
android:name=".DriversList"
android:label="#string/title_activity_drivers_list" >
</activity>
<activity
android:name=".DriverAdapter"
android:label="#string/title_activity_driver_adapter" >
</activity>
<activity
android:name=".EmergencyAssistance"
android:label="#string/title_activity_emergency_assistance" >
</activity>
<activity
android:name=".DisplayContact"
android:label="#string/title_activity_display_contact" >
</activity>
<activity
android:name=".ContactAdapter"
android:label="#string/title_activity_contact_adapter" >
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>

Application with Internet for the main and without for the rest

I have an app in which starting page needs internet,
Rest want to work without internet (ie, only one activity need the internet permission).
But when I turn off the Internet, the app shows a message like turn internet connection on and then only I can proceed to further (Here i want to work with out internet).
Is there any solution for that?
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exampleMock.ibps_test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:screenOrientation="landscape" >
<activity
android:name="com.exampleMock.ibps_test.MainActivity"
android:label="#string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.exampleMock.ibps_test.testClass"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.startTest"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.resultActivity"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.showDialog"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.showSolution"
android:label="#string/app_name"
android:screenOrientation="landscape" />
<activity
android:name="com.exampleMock.ibps_test.InfoGift"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
</application>
Main Activity:
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Void>, AsyncHttpRequestDelegate
{
static EditText n;
static EditText p;
ProgressBar pb;
static String mail="";
private DatabaseHelper helper;
private SQLiteDatabase db;
private static WeakReference<MainActivity> mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new DatabaseHelper(this);
helper.initializeDataBase();
db=helper.getWritableDatabase();
String stat=check();
if(stat.equals("true"))
{
gotoNextPage();
}
else
{
n=(EditText)findViewById(R.id.name);
p=(EditText)findViewById(R.id.phone);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
mail=fetchEmail();
/*
if(mail==null)
{
EditText m=(EditText)findViewById(R.id.mail);
m.setVisibility(1);
mail=m.getText().toString();
} */
Button b=(Button)findViewById(R.id.regBtn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(n.getText().toString().length()<1)
{
n.requestFocus();
Toast.makeText(MainActivity.this, "Enter your Name", Toast.LENGTH_SHORT).show();
}
else if(p.getText().toString().length()<10)
{
p.requestFocus();
Toast.makeText(MainActivity.this, "Enter a valid phone number", Toast.LENGTH_SHORT).show();
}
else
{
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
pb.setVisibility(View.VISIBLE);
//call asyncTask
startWork();
} else {
Toast.makeText(MainActivity.this, "No Network connection available...",Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
public String fetchEmail()
{
String e="";
Pattern email= Patterns.EMAIL_ADDRESS;
Account[] accounts= AccountManager.get(this).getAccounts();
for(Account account:accounts)
{
if(email.matcher(account.name).matches())
{
e=account.name;
return e;
}
}
return null;
}
public String check()
{
String flag="";
String sql="select * from reg_status";
Cursor c=db.rawQuery(sql, null);
if(c!=null)
{
c.moveToFirst();
flag=c.getString(0);
}
return flag;
}
public void updateStatus()
{
String sql="update reg_status set status = 'true'";
db.execSQL(sql);
gotoNextPage();
}
public void gotoNextPage()
{
Intent intent=new Intent(this,startTest.class);
startActivity(intent);
}
void startWork() {
getSupportLoaderManager().initLoader(0, (Bundle) null, this);
}
static class AsyncTaskMaker extends AsyncTaskLoader<Void> {
int progress = 0;
int percentProgress = 0;
int fileLength = 0;
AsyncTaskMaker(MainActivity activity) {
super(activity);
mActivity = new WeakReference<MainActivity>(activity);
}
#Override
public Void loadInBackground() {
System.out.println("inside loadInBackground");
processWebRequest();
return null;
}
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Void> arg0,
Void arg1) {
pb.setVisibility(View.GONE);
updateStatus();
//Toast.makeText(MainActivity.this, "Load finished", Toast.LENGTH_SHORT).show();
gotoNextPage();
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Void> arg0) {
//Toast.makeText(MainActivity.this, "Load reset", Toast.LENGTH_SHORT).show();
}
#Override
public android.support.v4.content.Loader<Void> onCreateLoader(int arg0, Bundle arg1) {
AsyncTaskMaker asyncTaskLoader = new AsyncTaskMaker(this);
asyncTaskLoader.forceLoad();
return asyncTaskLoader;
}
private static void processWebRequest(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://beta.wisdom24x7.com/gapps.php/");
//System.out.println("inside processWebRequest");
try
{
List<NameValuePair> pair=new ArrayList<NameValuePair>(4);
pair.add(new BasicNameValuePair("name",n.getText().toString()));
pair.add(new BasicNameValuePair("email",mail));
pair.add(new BasicNameValuePair("phone",p.getText().toString()));
pair.add(new BasicNameValuePair("exam","AIEEE"));
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse= httpclient.execute(httpPost);
Log.d("Http Response:", httpResponse.toString());
}catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void didComplete(HttpRequest request, String responseString) {
pb.setVisibility(View.GONE);
//Toast.makeText(MainActivity.this, "data sent", Toast.LENGTH_SHORT).show();
}
#Override
public void didFail(HttpRequest request) {
}
#Override
public void publishProgress(final int progress) {
if (mActivity.get() != null) {
mActivity.get().runOnUiThread(new Runnable() {
#Override
public void run() {
mActivity.get().pb.setProgress(progress);
}
});
}
}
}
Another activity, which does not require internet:
public class showDialog extends ActionBarActivity
{
CheckBox b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_sub);
b1=(CheckBox)findViewById(R.id.checkBox1);
b2=(CheckBox)findViewById(R.id.checkBox2);
b3=(CheckBox)findViewById(R.id.checkBox3);
b4=(CheckBox)findViewById(R.id.checkBox4);
final List<String> subs=new ArrayList<String>();
ImageButton bn=(ImageButton)findViewById(R.id.imageButton1);
bn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(b1.isChecked())
subs.add(b1.getText().toString());
if(b2.isChecked())
subs.add(b2.getText().toString());
if(b3.isChecked())
subs.add(b3.getText().toString());
if(b4.isChecked())
subs.add(b4.getText().toString());
System.out.print("subjects "+subs);
Intent intent = new Intent(showDialog.this,testClass.class);
intent.putStringArrayListExtra("subject", (ArrayList<String>) subs);
startActivity(intent);
}
});
}
}
It seems you didn't write this Android application by yourself (or else you would understand what the message means). This message that "asks for internet connection" is something that is done through your app and not by the Android framework. Please understand your application first, then ask questions about it.
Hint: Search for the String inside your app (by search functionality of your IDE) that is shown in your "asks for internet connection" message and look up why it is displayed. You will see, that you can disable it.
in your AndroidManifest.xml put :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
and inonCreate method of each activity you don't want to use the internet_connection in:
WifiManager wifiManager = (WifiManager)this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
You can only set permission for the complete app, not on single activity.
Why is it so important that the user doesn't have an internet connection in the rest of the app? When you don't code anything that connects to the internet in those "internet-free" activities, then you won't use up the (possible) date

Why am I getting this error "android.view.InflateException: Binary XML file line #29: Error inflating class fragment"

I am using Google Map v2 in Tabs.
Here is layout file of activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" >
<RelativeLayout
android:id="#+id/registrationLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#333333" >
<ImageView
android:id="#+id/activity_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:contentDescription="#string/content_description"
android:src="#drawable/logo" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/registrationLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/registrationLayout" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I get this error when I transfer my project to another PC. I have imported GooglePlayService for GoogleMap V2 and Facebook SDK 3.5.2 in my work space.
Here is the java code
public class NearMe extends FragmentActivity {
GpsProvider gpsProvider;
private GoogleMap googleMap;
double lat;
double lng;
JsonParser jparser;
String latString, longString, titleString, dis, distanceString,
stationIdString, colorNameString;
ArrayList<HashMap<String, String>> dockitstationsArrayList,
stationidArrayList;
BitmapDescriptor bitmapMarker;
NetworkHelper nh;
AlertDialogManager alertDialogManager = new AlertDialogManager();
// flag for Internet connection status
Boolean isInternetPresent = false;
HashMap<String, String> markershashmap = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Setting View for Screen
setContentView(R.layout.near_me);
dockitstationsArrayList = new ArrayList<HashMap<String, String>>();
markershashmap = new HashMap<String, String>();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
String distance[] = marker.getSnippet().split(" - ");
String distanceString = distance[0];
String idString = marker.getId();
String stationid = markershashmap.get(idString);
Message mesg = new Message();
Bundle b = new Bundle();
b.putString("stationId", stationid);
b.putString("distance", distanceString);
mesg.setData(b);
handler.sendMessage(mesg);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Bundle b1 = new Bundle();
b1.putString("stationId", b.getString("stationId"));
b1.putString("distance", b.getString("distance"));
Intent dockitdetailsIntent = new Intent(getParent(),
DockItStationDetails.class);
dockitdetailsIntent.putExtras(b1);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("Dock It Details",
dockitdetailsIntent);
}
};
#Override
protected void onResume() {
super.onResume();
initilizeMap();
nh = new NetworkHelper(getApplicationContext());
isInternetPresent = nh.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alertDialogManager.showInfoAlertDialog(NearMe.this.getParent(),
"Please connect to working internet connection");
// stop executing code by return
return;
}
gpsProvider = new GpsProvider(this.getParent());
// check if GPS enabled
if (gpsProvider.canGetLocation()) {
double latitude = gpsProvider.getLatitude();
double longitude = gpsProvider.getLongitude();
// \n is for new line
/*
* Toast.makeText( getApplicationContext(),
* "Your Location is - \nLat: " + latitude + "\nLong: " + longitude,
* Toast.LENGTH_LONG).show();
*/
new LoadNearByDockITStations().execute(String.valueOf(latitude),
String.valueOf(longitude));
} else {
// can't get location
// GPS is not enabled
// Ask user to enable GPS in settings
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
this.getParent());
// Setting Dialog Message
alertDialog
.setMessage("Your GPS seems to be disabled, do you want to enable it?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
// Setting Gravity to Center
AlertDialog dialog = alertDialog.show();
dialog.setCanceledOnTouchOutside(false);
TextView messageText = (TextView) dialog
.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
// Showing Alert Message
dialog.show();
}
}
private class LoadNearByDockITStations extends
AsyncTask<String, String, String> {
String res, status;
JSONArray resultJsonArray;
HashMap<String, String> map;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String lat = arg0[0];
String lng = arg0[1];
jparser = new JsonParser();
JSONObject jsonObject = jparser
.makeHttpRequest(Utility.GETDOCKITLIST + "?latitude=" + lat
+ "&longitude=" + lng + "&klm=20");
try {
// /Getting array of Events.......
if (jsonObject.getJSONArray(Utility.STATIONS) != null) {
res = jsonObject.getString(Utility.SUCCESS);
if (Integer.parseInt(res) == 1) {
resultJsonArray = jsonObject
.getJSONArray(Utility.STATIONS);
// looping through All Contacts
for (int i = 0; i < resultJsonArray.length(); i++) {
JSONObject c = resultJsonArray.getJSONObject(i);
// Storing each json item in variable
latString = c.getString(Utility.LAT);
longString = c.getString(Utility.LONG);
titleString = c.getString(Utility.TITLE);
distanceString = c.getString(Utility.DISTANCE);
stationIdString = c.getString(Utility.STATION_ID);
colorNameString = c.getString(Utility.COLOR_NAME);
// creating new HashMap
map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(Utility.LAT, latString);
map.put(Utility.LONG, longString);
map.put(Utility.TITLE, titleString);
map.put(Utility.DISTANCE, distanceString);
// map.put(Utility.DISTANCE, distanceString);
map.put(Utility.STATION_ID, stationIdString);
map.put(Utility.COLOR_NAME, colorNameString);
dockitstationsArrayList.add(map);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dockitstationsArrayList.size() == 0) {
Toast.makeText(getApplicationContext(),
"No Dock It Stations Found", Toast.LENGTH_LONG).show();
} else {
/*
* Toast.makeText(getApplicationContext(),
* "Dock It Stations Found", Toast.LENGTH_LONG).show();
*/
googleMap.clear();
addMarkersToMap();
}
}
}
private void addMarkersToMap() {
ArrayList<Marker> mMarkers = new ArrayList<Marker>();
LatLng ll = null;
String distance;
for (int i = 0; i < dockitstationsArrayList.size(); i++) {
ll = new LatLng(Double.parseDouble(dockitstationsArrayList.get(i)
.get(Utility.LAT)),
Double.parseDouble(dockitstationsArrayList.get(i).get(
Utility.LONG)));
distance = dockitstationsArrayList.get(i).get(Utility.DISTANCE);
stationIdString = dockitstationsArrayList.get(i).get(
Utility.STATION_ID);
colorNameString = dockitstationsArrayList.get(i).get(
Utility.COLOR_NAME);
if (colorNameString.equals("Cyan"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.cyan_marker);
else if (colorNameString.equals("Red"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.red_marker);
else if (colorNameString.equals("Yellow"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.yellow_marker);
else if (colorNameString.equals("Blue"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.blue_marker);
else if (colorNameString.equals("Green"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.green_marker);
else if (colorNameString.equals("Purple"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.purple_marker);
MarkerOptions mOption = new MarkerOptions();
mOption.position(ll);
mOption.title(dockitstationsArrayList.get(i).get(Utility.TITLE));
mOption.anchor(0.0f, 1.0f);
mOption.snippet(Utility.convertDistance(distance) + "m - Here");
mOption.icon(bitmapMarker);
Marker marker = googleMap.addMarker(mOption);
mMarkers.add(marker);
String markerkey = marker.getId();
markershashmap.put(markerkey,
dockitstationsArrayList.get(i).get(Utility.STATION_ID));
}
// stationidArrayList.add(markers);
final LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < dockitstationsArrayList.size(); i++) {
LatLng ll2 = new LatLng(Double.parseDouble(dockitstationsArrayList
.get(i).get(Utility.LAT)),
Double.parseDouble(dockitstationsArrayList.get(i).get(
Utility.LONG)));
bld.include(ll2);
}
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(
bld.build(), 30));
// googleMap.animateCamera(CameraUpdateFactory.zoomIn());
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// Move camera.
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(
bld.build(), 50));
// Remove listener to prevent position reset on camera move.
googleMap.setOnCameraChangeListener(null);
}
});
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
}
Here is manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dockit"
android:versionCode="2"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<permission
android:name="com.dockit.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.dockit.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- Access Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/app_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
<activity
android:name="com.dockit.SplashScreen"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.dockit.AboutUs"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.ListViewDockItStations"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.More"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden|stateHidden" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="twitter"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.dockit.NearByDockItTabs"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.NearMeold"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.Registration"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroupActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroup1"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.NearMe"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroup2"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroup3"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.DockItStationDetails"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAlvDShdumWacdKdHldu3TCAUPyUXId30k" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.dockit.RateApplication"
android:label="#string/title_activity_rate_application" >
</activity>
</application>
</manifest>
I capitalize fragment but I got this warning "Invalid tag Fragment should be fragment"

Why onPushMessageReceived() is not called in Geoloqi API in Android?

In my android app i am using Latest Geoloqi API to implement Geofence concept.when user entered into some region he has notify, for that purpose i am using Push Notifications.in GeoReceiver class three callback methods are calling but not onPushMessageReceived().please help me how to do it?
I am creating trigger with current location is it required to enter into region manually or since i am already in the location its not calling?
Note:I ve given required credentials in assets/geoloqi.properties file.when app is launched in logcat "Successfully registered for the C2DM service" msg also displayed.my code:
GeoloqiExampleActivity.java
public class GeoloqiExampleActivity extends Activity{
String TAG = "Geoloqi Example";
private LQService mService;
private boolean mBound;
GeoReceiver geoReceiver = new GeoReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, LQService.class);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
// Bind to the tracking service so we can call public methods on it
Intent intent = new Intent(this, LQService.class);
bindService(intent, mConnection, 0);
// Wire up the sample location receiver
final IntentFilter filter = new IntentFilter();
filter.addAction(GeoReceiver.ACTION_LOCATION_CHANGED);
filter.addAction(GeoReceiver.ACTION_TRACKER_PROFILE_CHANGED);
filter.addAction(GeoReceiver.ACTION_LOCATION_UPLOADED);
filter.addAction(GeoReceiver.ACTION_PUSH_MESSAGE_RECEIVED);
registerReceiver(geoReceiver, filter);
}
#Override
public void onPause() {
super.onPause();
// Unbind from LQService
if (mBound) {
unbindService(mConnection);
mBound = false;
}
// Unregister our location receiver
unregisterReceiver(geoReceiver);
}
public void sendRequest() {
// Performing a Trigger POST request
if (mService != null) {
LQSession session = mService.getSession();
LQTracker tracker = mService.getTracker();
tracker.setSession(session);
// Build your request
JSONObject trigger = new JSONObject();
try {
trigger.put("text", "Popcornapps");
trigger.put("type", "message");
trigger.put("latitude", 17.42557068);
trigger.put("longitude", 78.42022822);
trigger.put("radius", 500);
trigger.put("place_name", "Banjara Hills");
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
// Send the request
session.runPostRequest("trigger/create", trigger, new OnRunApiRequestListener() {
#Override
public void onSuccess(LQSession session, HttpResponse response) {
Toast.makeText(GeoloqiExampleActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
String result = s.toString().trim();
Log.d("On success Result", result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(LQSession session, LQException e) {
Log.e(TAG, e.getMessage());
Toast.makeText(GeoloqiExampleActivity.this, "Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(LQSession session, HttpResponse response, StatusLine status) {
Toast.makeText(GeoloqiExampleActivity.this, "Complete", Toast.LENGTH_LONG).show();
}
});
} else{
Toast.makeText(this, "service null", Toast.LENGTH_LONG).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
// We've bound to LocalService, cast the IBinder and get LocalService instance.
LQBinder binder = (LQBinder) service;
mService = binder.getService();
mBound = true;
sendRequest();//Sending API Request
} catch (ClassCastException e) {
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
}
GeoReceiver.java
public class GeoReceiver extends LQBroadcastReceiver {
#Override
public void onLocationChanged(Context arg0, Location arg1) {
Toast.makeText(arg0, "Loc Changed ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPushMessageReceived(Context context, Bundle data) {
Toast.makeText(context, "Push Msg Received ", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationUploaded(Context arg0, int arg1) {
Toast.makeText(arg0, "Location Uploaded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onTrackerProfileChanged(Context arg0, LQTrackerProfile oldp,
LQTrackerProfile newp) {
Toast.makeText(arg0, "onTrackerProfileChanged ",Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pop.geoloqi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<permission
android:name="com.pop.geoloqi.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.pop.geoloqi.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".GeoloqiExampleActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.geoloqi.android.sdk.service.LQService"
android:exported="false" />
<receiver
android:name=".GeoReceiver"
android:enabled="false"
android:exported="false" >
<intent-filter>
<action android:name="com.geoloqi.android.sdk.action.LOCATION_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="com.geoloqi.android.sdk.receiver.LQDeviceMessagingReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.pop.geoloqi" />
</intent-filter>
</receiver>
</application>
</manifest>
There was a bug in earlier versions of the Geoloqi Android SDK. If you update to the latest version this problem should be resolved.

Categories

Resources