Function not saving data to file onDestroy() Android - android

I do the following function in my main activity
#Override
public void onDestroy() {
super.onDestroy();
SimpleBookManager.getSimpleBookManager().saveChanges(this);
}
When Android later call the method function saveChanges() when I close the Application I get the "SaveChanges" outprint but not the last print "After Saving" meaning that its not executing the whole function and I'm not getting any outPrints on the catch exceptions lines either. Do you know why? I'm new to android and do not understand if you could run this code onDestroy(). =)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import android.content.Context;
public class SimpleBookManager implements BookManager, java.io.Serializable {
private ArrayList<Book> allBooks = new ArrayList<Book>();
private static SimpleBookManager ref;
public void saveChanges(Context context){
try{
System.out.println("SaveChanges");
FileOutputStream f_out = context.openFileOutput("myobject.data",Context.MODE_PRIVATE);
// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
// Write object out to disk
obj_out.writeObject(allBooks);
System.out.println("After Saving");
}catch (FileNotFoundException e) {
System.out.println("No file found saveChanges");
} catch (IOException e) {
System.out.println("IOException in SaveChanges");
}
}
public void loadBooks(Context context){
try{
// Read from disk using FileInputStream
FileInputStream f_in = context.openFileInput("myobject.data");
// Read object using ObjectInputStream
ObjectInputStream obj_in = new ObjectInputStream (f_in);
// Read an object
Object obj = obj_in.readObject();
//System.out.println(obj);
if (obj instanceof ArrayList<?>)
{
allBooks = (ArrayList<Book>) obj;
System.out.println("Worked");
System.out.println(allBooks);
}
}catch (FileNotFoundException e) {
System.out.println("No file found LoadBooks");
} catch (IOException e) {
System.out.println("IOException in loadBooks");
}
catch (ClassNotFoundException e) {
System.out.println("ClassNotFound in loadBooks");
}
}
public static SimpleBookManager getSimpleBookManager()
{
if (ref == null){
ref = new SimpleBookManager();
}
return ref;
}
public SimpleBookManager(){
Book book1 = createBook();
book1.setAuthor("RandomBookAuthor");
book1.setCourse("Kunskap");
book1.setPrice(199);
book1.setTitle("Some Random Title");
book1.setIsbn("9780590353403");
}
}
I also get IOException when doing this onCreate() in main, so something is really fishy about my load and save functions.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleBookManager.getSimpleBookManager().loadBooks(this);
setContentView(R.layout.activity_action_bar_main);
}
__________________________________________________________________________________
I have added the permission to the manifest to write to storage in the last lines of the manifest below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.av.BookApp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<application
android:icon="#drawable/ic_launcher"
>
<activity
android:name=".BookApp"
android:label="#string/title_bookapp"
android:uiOptions="splitActionBarWhenNarrow" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddBookActivity"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="edu.chalmers.BookApp" />
</activity>
<activity
android:name=".DetailActivity"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="edu.chalmers.BookApp" />
</activity>
<activity
android:name=".EditBookActivity"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="edu.chalmers.BookApp" />
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
</manifest>
Edit
After I followed the advice below I now get a IOException in saveChanges()
And I do set the data correct like this (In SimpleBookManager)
public SimpleBookManager(){
Book book1 = createBook();
book1.setAuthor("RandomBookAuthor");
book1.setCourse("Kunskap");
book1.setPrice(199);
book1.setTitle("Some Random Title");
book1.setIsbn("9780590353403");
}

i think you save the data in onResume meothd it's guarantee the system will make the action before kill the process

Reorder your onCreate() method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action_bar_main);
SimpleBookManager.getSimpleBookManager().loadBooks(this);
}
and Override onStop() method and don't override onDestroy method:
#Override
public void onStop() {
super.onStop();
SimpleBookManager.getSimpleBookManager().saveChanges(this);
}

Related

System.error NullPointer

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.

Receiving files from Java server to Android. accept() not working

Hi guys I'm creating simple interactive android application. Server runs Java.
It turns out, that I can not receive files from server.
Android code is following
public class MainActivity extends Activity {
public DataReceiving dataReceiving;
public DataTransfer dataTransfer;
private EditText inputData;
private Button sendParameters;
private Button startComputation;
public TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputData= (EditText) findViewById(R.id.editText1);
sendParameters=(Button) findViewById(R.id.button1);
startComputation=(Button) findViewById(R.id.button2);
displayText=(TextView) findViewById(R.id.textView1);
startComputation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String numberOfGates=inputData.getText().toString();
ArrayList send=new ArrayList();
send.add(numberOfGates);
dataTransfer=new DataTransfer();
dataTransfer.execute(send);
}
});
sendParameters.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dataReceiving=new DataReceiving();
dataReceiving.execute();
}
});
}
public class DataReceiving extends AsyncTask<Void, Void, ArrayList>
{
#Override
protected ArrayList doInBackground(Void... params) {
ArrayList receivedData=new ArrayList();
Log.i("DataReceiving", "doInbackgroung works");
try {
receivedData=receive();
} catch (ClassNotFoundException e) {
Log.e("DataReceiving", "Problems with receive method. Issue with class");
e.printStackTrace();
} catch (IOException e) {
Log.e("DataReceiving", "Problems with receive method. Issue with IO");
e.printStackTrace();
}
return receivedData;
}
#Override
protected void onPostExecute(ArrayList result) {
super.onPostExecute(result);
displayText.setText(result.toString());
}
}
public ArrayList receive () throws IOException, ClassNotFoundException
{
Log.i("receive method", "works");
ServerSocket s= new ServerSocket(8888);
Log.i("receive method", "ServerSocket(8888)");
Socket incoming =s.accept();
Log.i("receive method", "accept()");
ObjectInputStream ios = new ObjectInputStream(incoming.getInputStream());
Log.i("receive method", "ios");
ArrayList b=new ArrayList();
b = (ArrayList) ios.readObject();
Log.i("receive method", "data were received");
ios.close();
incoming.close();
s.close();
return b;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Here is the Log
06-18 18:08:51.709: D/dalvikvm(2160): GC_CONCURRENT freed 69K, 7% free 2760K/2952K, paused 78ms+85ms, total 261ms
06-18 18:08:52.079: D/gralloc_goldfish(2160): Emulator without GPU emulation detected.
06-18 18:09:05.090: I/DataReceiving(2160): doInbackgroung works
06-18 18:09:05.099: I/receive method(2160): works
06-18 18:09:05.099: I/receive method(2160): ServerSocket(8888)
It seems like Socket incoming =s.accept(); doesn't work and I have no idea why
Here is Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Server side is very simple
Socket s=new Socket("192.168.1.110", 8888);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ArrayLIst b = new ArrayList();
b.add("It Works");
oos.writeObject(b);
oos.close();
s.close();
I will be very appreciated for any Ideas, how to fix this problem. Thank you
I think the client part is working right, it stops at the accept method. So the problem is in the server which never gets to connect.
The server part should be like this:
try {
Socket s = new Socket();
InetAddress addr = InetAddress.getByName("192.168.1.110");
SocketAddress sockaddr = new InetSocketAddress(addr, 8888);
s.connect(sockaddr, 20000); // 20 seconds time out
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ArrayLIst b = new ArrayList();
b.add("It Works");
oos.writeObject(b);
oos.close();
s.close();
}
catch (Exception e)
{
.....
}

Files are created in the external storage, but are empty

Part of my application creates some files in the external storage and writes into them.
Everything was working like a charm until I changed something, I don't remember what. Now application creates files but doesn't write anything, i.e the files are empty.
Any ideas what is the problem?
Here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myloader"
android:versionCode="26"
android:versionName="1.1" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:debuggable="true">
<activity
android:name="com.example.myloader.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is where I write to a file. I haven't changed anything though. It was like this when it was working
public class GraphHelper {
File directory;
File myExternalFile;
PrintWriter writer;
FileOutputStream outputStream;
ArrayList<float[]> dataList;
float []toWrite;
String strToWrite;
private String filepath = "MyFileStorage";
public GraphHelper(Context context)
{
directory = context.getExternalFilesDir(filepath);
}
public GraphHelper(Application application)
{
directory = application.getExternalFilesDir(filepath);
}
public void writeToFile(String filename,ArrayList <float[]>data)
{
if(isExternalStorageAvailable()&&!isExternalStorageReadOnly())
{
myExternalFile = new File(directory, filename);
try {
outputStream = new FileOutputStream(myExternalFile);
writer = new PrintWriter(outputStream);
dataList = data;
for(int i=0;i< data.size();i++)
{
toWrite = data.get(i);
System.out.println("toWrite[1]: "+toWrite[0]+"toWrite[2]: "+toWrite[1]);
}
writer.close();
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
you never call print
for(int i=0;i< data.size();i++) {
toWrite = data.get(i);
System.out.println("toWrite[1]: "+toWrite[0]+"toWrite[2]: "+toWrite[1]);
writer.print(toWrite);
}
writer.flush();
writer.close();

NFC Intent Filter - Sending Message Non-Main Activity

I am sure this is simple but I cannot figure it out. All I am trying to do is send a message via NFC. The code I have work perfectly if I am sending it to the main activity, but I don't know how to send it to a different activity. I have looked over both the NFC and Intent Filter articles on the Android Developer pages but am still not sure exactly how to do this. I am trying to send it to a NFC activity, I will post my manifest and NFC class below.
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.justbaumdev.tagsense"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo" >
<activity
android:name=".TagSense"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.justbaumdev.tagsense.NFC" android:exported="false">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/com.justbaumdev.tagsense" />
</intent-filter>
</activity>
</application>
</manifest>
NFC Class:
package com.justbaumdev.tagsense;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.widget.Toast;
public class NFC extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfc);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // Check for available NFC Adapter
if (mNfcAdapter == null)
{
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
else
{
mNfcAdapter.setNdefPushMessageCallback(this, this); // Register callback to set NDEF message
mNfcAdapter.setOnNdefPushCompleteCallback(this, this); // Register callback to listen for message-sent success
}
}
#Override
public void onResume() {
super.onResume();
// Check to see that the Activity started due to an Android Beam
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
#Override
public NdefMessage createNdefMessage(NfcEvent event) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
String newMac = mac.substring(0, 2);
mac = mac.substring(2);
int hex = Integer.parseInt(newMac, 16) + 0x2;
newMac = Integer.toHexString(hex);
String text = newMac + mac;
NdefMessage msg = new NdefMessage(NdefRecord.createMime(
"application/com.justbaumdev.tagsense", text.getBytes()));
return msg;
}
/**
* Implementation for the OnNdefPushCompleteCallback interface
*/
#Override
public void onNdefPushComplete(NfcEvent arg0) {
// A handler is needed to send messages to the activity when this
// callback occurs, because it happens from a binder thread
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
/** This handler receives a message from onNdefPushComplete */
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SENT:
Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
break;
}
}
};
/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
//TODO Currently overwrites any previously saved mac addresses. Get FB ID as value. Auto end activity.
void processIntent(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
//textView.setText(new String(msg.getRecords()[0].getPayload()));
String payload = new String(msg.getRecords()[0].getPayload());
Toast.makeText(this, new String(msg.getRecords()[0].getPayload()), Toast.LENGTH_LONG).show();
SharedPreferences appData = getSharedPreferences("appData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
String addresses = appData.getString("mac_address", null);
if(addresses==null)
{
JSONArray addressArray = new JSONArray();
addressArray.put(payload);
addresses = addressArray.toString();
}
else
{
try {
if(!addresses.contains(payload))
{
JSONArray addressArray = new JSONArray(addresses);
addressArray.put(payload);
addresses = addressArray.toString();
}
} catch (JSONException e) {
Toast.makeText(this, "Error adding new friend. Please try again.", Toast.LENGTH_SHORT).show();
}
}
editor.putString("mac_address", addresses);
editor.commit();
}
}
Thanks for your help.
Remove the attribute android:exported="false". See also https://stackoverflow.com/a/12719621/1202968

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