Files are created in the external storage, but are empty - android

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();

Related

Epson printer connect fails status ERR_CONN

I have an Epson printer and I used epos2_printer (sample project) code given with SDK to integrate with my app. I have copied the same code but it never seems to work!
However, the same works when I connect the sample project to my printer.
private boolean runPrintReceiptSequence() {
if (!initializeObject()) {
return false;
}
if (!createReceiptData()) {
finalizeObject();
return false;
}
if (!printData()) {
finalizeObject();
return false;
}
return true;
}
private boolean initializeObject() {
try {
final SpnModelsItem spnModel = new SpnModelsItem("TM-T82 Series", Printer.TM_T82);
final SpnModelsItem spnLang = new SpnModelsItem("ANK", Printer.MODEL_ANK);
mPrinter = new Printer(spnModel.getModelConstant(),
spnLang.getModelConstant(), this);
}
catch (Exception e) {
Log.e("Printer", e.toString());
return false;
}
mPrinter.setReceiveEventListener(this);
return true;
}
private boolean createReceiptData() {
String method = "";
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.logo_saltnpepper);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
Date currentDate = new Date();
info.saltnpepper.ordersmart2.MenuItem currItem = null;
double price = 0;
double total = 0;
int totalQty =0;
if (mPrinter == null) {
return false;
}
try {
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
method = "addImage";
mPrinter.addImage(logoData, 0, 0,
logoData.getWidth(),
logoData.getHeight(),
Printer.COLOR_1,
Printer.MODE_MONO,
Printer.HALFTONE_DITHER,
Printer.PARAM_DEFAULT,
Printer.COMPRESS_AUTO);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("SALT-N-PEPPER\n");
//textData.append("STORE DIRECTOR – John Smith\n");
textData.append("\n");
textData.append((new SimpleDateFormat("dd/MM/yy HH:mm:ss")).format(currentDate).toString() + "\n");
//textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
if(alFinalOrder != null)
{
for(int i=0; i < alFinalOrder.size(); i++)
{
currItem = alFinalOrder.get(i);
textData.append(currItem.getName()+" "+currItem.getQty()+" "+currItem.getPrice()+"\n");
//calculate total quantity
totalQty = totalQty + currItem.getQty();
//calculate price
double dPrice = currItem.getQty()*Double.parseDouble(currItem.getPrice().substring(1));
total = total + dPrice;
total = Math.round(total*100.0)/100.0;
}
}
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("TOTAL "+"\n");
textData.append("TAX "+"\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
mPrinter.addFeedLine(2);
method = "addBarcode";
mPrinter.addBarcode("01209457",
Printer.BARCODE_CODE39,
Printer.HRI_BELOW,
Printer.FONT_A,
barcodeWidth,
barcodeHeight);
method = "addCut";
mPrinter.addCut(Printer.CUT_FEED);
}
catch (Exception e) {
//ShowMsg.showException(e, method, mContext);
return false;
}
textData = null;
return true;
}
private boolean printData() {
if (mPrinter == null) {
return false;
}
if (!connectPrinter()) {
return false;
}
PrinterStatusInfo status = mPrinter.getStatus();
dispPrinterWarnings(status);
if (!isPrintable(status)) {
Log.e("Printer", "Is not printable");
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
try {
mPrinter.sendData(Printer.PARAM_DEFAULT);
}
catch (Exception e) {
Log.e("Printer", e.getMessage());
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
return true;
}
private boolean connectPrinter() {
boolean isBeginTransaction = false;
if (mPrinter == null) {
return false;
}
try {
mPrinter.connect("TCP:"+mIP, Printer.PARAM_DEFAULT);
}
catch (Epos2Exception e) {
//ShowMsg.showException(e, "connect", this);
if(e.getErrorStatus() == Epos2Exception.ERR_CONNECT)
{
Log.e("testing", "error connect");
}
if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_OPENED)
{
Log.e("testing", "already open");
}
if(e.getErrorStatus() == Epos2Exception.ERR_ALREADY_USED)
{
Log.e("testing", "already used");
}
if(e.getErrorStatus() == Epos2Exception.ERR_BOX_CLIENT_OVER)
{
Log.e("testing", "box client over");
}
if(e.getErrorStatus() == Epos2Exception.ERR_BOX_COUNT_OVER)
{
Log.e("testing", "count over");
}
if(e.getErrorStatus() == Epos2Exception.ERR_DISCONNECT)
{
Log.e("testing", "disconnect");
}
if(e.getErrorStatus() == Epos2Exception.ERR_FAILURE)
{
Log.e("testing", "failure");
}
if(e.getErrorStatus() == Epos2Exception.ERR_ILLEGAL)
{
Log.e("testing", "illegal");
}
if(e.getErrorStatus() == Epos2Exception.ERR_IN_USE)
{
Log.e("testing", "in use");
}
if(e.getErrorStatus() == Epos2Exception.ERR_MEMORY)
{
Log.e("testing", "memory");
}
return false;
}
try {
mPrinter.beginTransaction();
isBeginTransaction = true;
}
catch (Exception e) {
Log.e("Printer", e.toString ());
}
if (isBeginTransaction == false) {
try {
mPrinter.disconnect();
}
catch (Epos2Exception e) {
// Do nothing
return false;
}
}
return true;
}
It always gives me exception ERR_CONNECT on printer.connect inside connectprinter function.
What am I doing wrong?
This code works fine with the sample app.
P.S: I have tried to connect this app before connecting the sample app to check if the sample app holds the connection and does not allow other apps to connect but that is not the case. Epson help is unable to provide any further help.
My AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xyz"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="21"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
<activity android:name=".MenuActivity" >
</activity>
<activity
android:name=".SaltnPepperActivity"
android:label="#string/title_activity_saltn_pepper" >
</activity>
<activity
android:name=".FinalOrder"
></activity>
<activity
android:name=".ZinVietActivity"
>
</activity>
<activity
android:name="com.epson.epos2_printer.DiscoverActivity"
></activity>
</application>
Looks like you don't have the proper permissions in your manifest. Try putting these in your project under the manifest tag:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
They also have the
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
permission but I'm not sure you need it. I think the essentials are Bluetooth and Internet permissions.
As I suspect there seems to be an error in connect printer method. I have used this SDK once so better follow the documentation properly (means don't skip steps). Make sure you have defined permission as mentioned in the SDK.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<activity android:name=".MainActivity" android:label="#string/app_title" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="#xml/device_filter"/>
As I see you haven't mentioned what type of connection you are making thus, in that case, there must be problem in selecting target
Check out the function from SDK:
Public void connect(String target, int timeout) throws Epos2Exception;
You might be using wrong target parameter.
Note: if you are using USB or any other mode make sure run discoverability service as per the docs.
Discovery.start(this, mFilterOption, mDiscoveryListener);
It will return you the required target name. And I am sure no connection failure will occur. Good Luck \o
Status ERR_CONN is basically shows if device cannot be reached or connection failing with device. It can be USB, LAN/NETWORK, Bluetooth Connection failure status.
If you are trying to connect printer with Bluetooth then you must write below permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
If you are using LAN for network printers then
<uses-permission android:name="android.permission.INTERNET"/>
For USB Printer Connection Use:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
As you are using EPOS2 Sample Project, remember to import Jar file "EPOS2.jar". Click here to download the file.

Android : Sync Adapter not running in some devices

In my android project i have a sync adapter that will sync data from android device to the server and its working fine, but recently i noticed that the onPerfomSync is not calling in my moto g3 android phone, I don't know whether there is the same problem in any other phones,I have tested it in some other Samsung phones with different android api level,but didn't find any problem there.I have configured the sync when a successful user login found.What will be the reason for this behaviour.Correct me if i am doing anything wrong.
Below is my codes.
private void finishLogin(Intent intent) {
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)) {
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = authTokenType;
String refreshToken = intent.getStringExtra(KEY_REFRESH_TOKEN);
Bundle userData = new Bundle();
userData.putString(KEY_REFRESH_TOKEN, refreshToken);
accountManager.addAccountExplicitly(account, accountPassword, userData);
accountManager.setAuthToken(account, authtokenType, authtoken);
accountManager.setUserData(account,KEY_REFRESH_TOKEN,refreshToken);
ContentResolver.setMasterSyncAutomatically(true);
ContentResolver.setSyncAutomatically(account, "com.myexample.mysampleproject", true);
configurePeriodicSync(account, SYNC_INTERVAL, SYNC_FLEXTIME);
try {
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("condition else getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)");
accountManager.setPassword(account, accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}
public void configurePeriodicSync(Account account, int syncInterval, int flexTime) {
Log.d(TAG, "PERIODC SYNC CONFIGURED");
Bundle mySyncExtras = new Bundle();
mySyncExtras.putBoolean("MY_SYNC", true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
System.out.println("if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
SyncRequest request = new SyncRequest.Builder().
syncPeriodic(syncInterval, flexTime).
setSyncAdapter(account, "com.myexample.mysampleproject").setExtras(mySyncExtras).build();
ContentResolver.requestSync(request);
} else {
System.out.println("else (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
ContentResolver.addPeriodicSync(account, "com.myexample.mysampleproject", mySyncExtras, syncInterval);
}
}
SyncService.java :
public class SyncService extends Service {
private static SyncAdapter syncAdapter = null;
private static final Object syncAdapterLock = new Object();
#Override
public void onCreate() {
synchronized (syncAdapterLock) {
if (syncAdapter == null) {
syncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}
#Override
public IBinder onBind(Intent intent) {
return syncAdapter.getSyncAdapterBinder();
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myexample.mysampleproject" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:largeHeap="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".view.MainActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme"
android:label="#string/app_name" >
</activity>
<activity android:name=".view.LoginActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme"
android:label="#string/login_label"/>
........
........
<provider
android:name=".db.MyContentProvider"
android:authorities="com.myexample.mysampleproject"
android:exported="false"
android:syncable="true" />
<service
android:name=".sync.SyncService"
android:exported="true">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/sync_adapter" />
</service>
</application>
</manifest>
sync_adapter.xml :
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter
xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="com.myexample.mysampleproject"
android:accountType="com.myexample.mysampleproject"
android:userVisible="true"
android:supportsUploading="true"
android:allowParallelSyncs="true"
android:isAlwaysSyncable="true" />
SyncAdapter.java :
public class SyncAdapter extends AbstractThreadedSyncAdapter {
ContentResolver contentResolver;
Context context;
String authToken;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
this.context = context;
contentResolver = context.getContentResolver();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
contentResolver = context.getContentResolver();
}
#Override
public void onPerformSync(Account account, final Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
try {
System.out.println("start sync ");
AccountManager manager = AccountManager.get(context);
authToken = manager.peekAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
try {
if(authToken != null) {
if (isOnline()) {
// perform sync....
} else {
Log.d("ATTEMPT SYNC ERROR", "NO NETWORK CONNECTION");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

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>

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.

Function not saving data to file onDestroy() 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);
}

Categories

Resources