Android - Call method from another class when app is closed (Using AlarmManager) - java

I am trying to call a method in my MainActivity class from another class using an AlarmManager.
I found this question which helped me call the method but when the app is closed, and the AlarmManager is still running it gives a NullPointerException error.
Another solution which would work for me is to have getBatteryLevel() inside my AlarmRec class. When I try this I get the error - Cannot resolve method registerReceiver(null, android.content.IntentFilter).
My MainActivity class:
package com.ds.shutdown;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity {
int userLvl;
int batteryLvl;
static MainActivity mainActivity;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = this;
batteryLvl = getBatteryLevel();
String bat = Integer.toString(batteryLvl);
TextView textViewTwo = (TextView) findViewById(R.id.textBatteryLvl);
textViewTwo.setText("Battery level: " + bat);
userLvl = loadSavedPreferences();
TextView textView = (TextView) findViewById(R.id.textUserLvl);
textView.setText("User entry: " + Integer.toString(userLvl));
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().getBoolean("CALL_METHOD", false)) {
shutdown();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void shutdown() {
Toast.makeText(this, "In shutdown method", Toast.LENGTH_SHORT).show();
batteryLvl = getBatteryLevel();
String bat = Integer.toString(batteryLvl);
TextView textViewTwo = (TextView) findViewById(R.id.textBatteryLvl);
textViewTwo.setText("Battery level: " + bat);
userLvl = loadSavedPreferences();
if (batteryLvl <= userLvl) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});
process.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public int getBatteryLevel() {
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
return level;
}
//OK button onClick
public void btnPress(View v) {
EditText mEditText = (EditText) findViewById(R.id.userLvl); //Look at text box
String userLvlStr = mEditText.getText().toString(); //Take contents and set to string
if (userLvlStr.matches("")){
Toast.makeText(this, "Invalid Entry", Toast.LENGTH_SHORT).show();
return;
}
userLvl = Integer.parseInt(userLvlStr); //Convert that string to an int
saveSavedPreferences(userLvl); //Save that int
setContentView(R.layout.activity_main); //Look at main activity
TextView textView = (TextView) findViewById(R.id.textUserLvl); //Look at text view
textView.setText("User entry: " + userLvlStr); //Change text view to show user entry
batteryLvl = getBatteryLevel();
String bat = Integer.toString(batteryLvl);
TextView textViewTwo = (TextView) findViewById(R.id.textBatteryLvl);
textViewTwo.setText("Battery level: " + bat);
alarmMethod();
}
//Saves variable(s) across app close
private void saveSavedPreferences(int userLvl){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); //Create SharedPreferences object
SharedPreferences.Editor editor= sharedPref.edit(); //Now get editor
editor.putInt("userLvl", userLvl); //Put in variable
editor.commit(); //Save variable(s)
}
//Loads variable(s) across app close
private int loadSavedPreferences() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
userLvl = sharedPrefs.getInt("userLvl", 0);
return userLvl; //Using return since only one variable is needed
}
//Set alarm
private void alarmMethod() {
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); //Create Alarm Manager
Intent intent = new Intent(this, AlarmRec.class); //Set intent
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
//setRepeating() lets you specify a precise custom interval--in this case, 20 seconds
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 10, alarmIntent);
Toast.makeText(MainActivity.this, "Alarm set", Toast.LENGTH_LONG).show();
}
public void cancelAlarm(View v2) {
// If the alarm has been set, cancel it.
if (alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
TextView textView = (TextView) findViewById(R.id.textUserLvl);
textView.setText("User entry: ");
}
public static MainActivity getInstance(){
return mainActivity;
}
}
My Alarm Receiver class:
package com.ds.shutdown;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.widget.Toast;
public class AlarmRec extends BroadcastReceiver {
//#Override
public void onReceive(Context context, Intent intent) {
//Call shutdown
Toast.makeText(MainActivity.getInstance(), "Calling shutdown", Toast.LENGTH_SHORT).show();
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().shutdown();
}
else {
Intent i = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//I also tried i.addFlags
i.putExtra("CALL_METHOD", true);
context.startActivity(i);
}
}
}

Because when your app is closed MainActivity.getInstance() returns null.
You should do methodToCall() in your BroadcastReceiver (if the method doesn't take long) or call Service from there, where you do methodToCall().
Another way is to modify your Receiver like this
Toast.makeText(context, "Calling shutdown", Toast.LENGTH_SHORT).show();
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().methodToCall();
}
else {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("CALL_METHOD", true);
context.startActivity(i);
}
And MainActivity in onCreate check for CALL_METHOD extra;
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().getBoolean("CALL_METHOD", false)) {
methodToCall();
}

Do not expose your main activity through a static method like a singleton.
Your activity getInstance() method will return null because it has probably been popped off the back stack (or if activity has been killed). Do not rely on your activity being present and is reference to be valid after you have backgrounded your app.
I don't understand what functionality you want in that method that the activity defines. You should be able to put that in the broadcast receiver. If you need UI to be shown, launch your activity again (in which case the UI would show up again).

Related

Android Java app fails to send selected file/data via Bluetooth

My current android app can turn on Bluetooth, make itself discoverable, list paired devices, and select a file from the device ( ie an image). However when I attempted to hit "send" the app seems to crash with an error. Not sure if it's refusing to send, or if it's not actually obtaining the file (yesterday I had a problem where it refused to send the selected, saying for me to select a file repeatedly. I will post the crash results and my mainActivity code. If anyone suggestions or ideas, please let me know.
Error: Debugging device
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluetooth_demoproject, PID: 17593
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=300, data=null} to activity {com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4107)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.bluetooth_demoproject.MainActivity.onActivityResult(MainActivity.java:350)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4103)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6120) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
Here is my MainActivity
package com.example.bluetooth_demoproject;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_BLU = 1;
// private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mDiscoverableButton, mPairedDevices, mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText)findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
// mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_BLU);
}
}
});
// off button click
// mOffButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (mBlueAdapter.isEnabled()) {
// showToast("Turning Bluetooth off...");
// // intent to turn off bluetooth
// mBluetoothIcon.setImageResource(R.drawable.action_off);
// }
// else{
// showToast("Bluetooth is already off");
// }
//
// }
//});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() + "," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
// #Override
// protected void onPrepareDialog(int id, Dialog dialog) {
// super.onPrepareDialog(id, dialog);
// switch (id) {
// case CUSTOM_DIALOG_ID:
// ListDir(curFolder);
// break;
// }
// }
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("Select Files");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
else if (selected.isFile()) {
getSelectedFile(selected);
}
else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...", Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file", Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);// STOPPED HERE-----------------------------------------------------------------
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
//CHECK BLUETOOTH available or not------------------------------------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found", Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// Toast.makeText(this, "**********************************\nDeveloper: www.santoshkumarsingh.com\n**********************************", Toast.LENGTH_LONG).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}
You have trouble with file exchange not with BLE.
Did you ever read Android FileUriExposedException?

passing a variable to classes

i can not figure out how to pass the results from onActivityResult to resultBreakdown. I know there is a get/set and I've looked at a few tutorials, but I'm just not getting it. Or, Is there a better way? The program runs fine up if i comment out */ the resultBreakdown Class
Side note, I just started with java/android. I'm a better learner at doing then reading. I know my code is a little clumsy. Thanks for the help
Note: i edited code to reflect suggested changes
package com.example.spdwiz18.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import java.text.DateFormat;
import java.time.*;
import java.time.temporal.*;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class GrindLogActivity extends AppCompatActivity {
TextView barcodeResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gringlogactivity);
// this is how to set id's from the xml file with vNames. (julianDate)
TextView bcc = (Textview)findViewById(R.id.bccheck);
TextView pc = (Textview)findViewById(R.id.pcode);
TextView pd = (Textview)findViewById(R.id.pdate);
// TextView en = (Textview)findViewById(R.id.estnum);
TextView sn = (Textview)findViewById(R.id.seqnum);
TextView nw = (Textview)findViewById(R.id.nweight);
barcodeResult = (TextView) findViewById(R.id.barcode_result);
TextView julianDate = (TextView) findViewById(R.id.datecode);
TextView td1 = (TextView) findViewById(R.id.todaydate1);
// this is how you get a julian/original date for android
LocalDate now = LocalDate.now();
int julian = now.get(ChronoField.DAY_OF_YEAR);
// this how to set you current date for android
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
// this is how to set your vNames to your method variables
julianDate.setText(Integer.toString(julian));
td1.setText(stringDate);
}
/*add click event to the scan barcode button */
public void scanBarcode(View v) {
Intent intent = new Intent(this, ScanBarcodeActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(String result) {
if (result.length() == 44) {
pc.setText(result.CharSequence(2,10));
pd.setText(result.CharSequence(13,18));
sn.setText(result.CharSequence(21,27));
nw.setText(result.CharSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}
The code posted needs a lot of work - so this answer most likely is just partial
(1) TextView initialization in wrong place
The TextViews declared as class instance variables cannot also be initialized at that point. So leave the declarations there (where bardcodeResult is declared):
TextView barcodeResult;
TextView bcc;
TextView pc;
TextView pd;
TextView sn;
TextView nw;
but move the initialization to the onCreate method in the same manner barcodeResult.
// in onCreate
barcodeResult = (TextView) findViewById(R.id.barcode_result);
bcc = (TextView)findViewById(R.id.bccheck);
pc = (TextView)findViewById(R.id.pcode);
pd = (TextView)findViewById(R.id.pdate);
sn = (TextView)findViewById(R.id.seqnum);
nw = (TextView)findViewById(R.id.nweight);
(2) The syntax is of resultsBreakdown is invalid and the functionality is wrong (need to invoke setText)- try:
public void resultsBreakdown(String result) {
if (result.length() == 44) {
pc.setText(result.CharSequence(2,10));
pd.setText(result.CharSequence(13,18));
sn.setText(result.CharSequence(21,27));
nw.setText(result.CharSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}
(3) Actually invoke the resultsBreakdown method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
//-- THIS LINE WAS ADDED TO CALL METHOD
resultsBreakdown(barcode.displayValue.toString());
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
I think there should be resultCode instead of requestCode in requestCode == CommonStatusCodes.SUCCESS
 #Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
resultsBreakdown(barcode.displayValue)
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(String barcodeData){
if (barcodeData.length == (44)) {
pc = (barcodeData.CharSequence(2,10);
pd = (barcodeData.CharSequence(13,18);
sn = (barcodeData.CharSequence(21,27);
nw = (barcodeData.CharSequence(13,18);
)else(
bcc = "invalid barcode";
}
)
}
resultBreakdown neither a class nor a method.İt isn't even compile. You change your resultBreakDown to Method:
public void resultsBreakdown(Barcode barcodeResult){
if (barcodeResult.length == (44)) {
pc = (barcodeResult.CharSequence(2,10);
pd = (barcodeResult.CharSequence(13,18);
sn = (barcodeResult.CharSequence(21,27);
nw = (barcodeResult.CharSequence(13,18);
} else{
bcc = "invalid barcode";
}
and later in onActivityResult call your method with Barcode parameters.
The code is incomplete as you have not placed ScanBarcodeActivity java file. Well... I am placing a small code in my project which will clear your concept and even you can use it.
Here suppose i am in Activity MyClassA.java where is a button and when it is clicked it will start another activity MyClassB.java, Remember it will start that activity along with layout.. from that activity you have to finish it on certain event and when it is finished your MyClassA.java will collect its result...
From Activity MyClassA.java on button click i want to start a activity
MyClassB.java for result:
ContactsBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
ContactsBtn.setEnabled(false);
Intent intent = new Intent(MyClassA.this, MyClassB.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
Where REQUEST_CODE should be declared in MyClassA class as public static final int REQUEST_CODE = 1;
Now From Activity MyClassB.java on particular event say on click of a button you want to close this activity and want to send result to previous activity :
SelectContactsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.putStringArrayListExtra("WhitelistNames", (ArrayList<String>) WhitelistNames);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
Here i am placing WhitelistNames array list as result to be sent to calling activity.
Now From Activity MyClassA.java again you have to collect the result with :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
ArrayList<String> WhitelistNames = data.getStringArrayListExtra("WhitelistNames");
Log.d("ContactsContracts", "\nPREVIOUS LIST : "+ContactsNumbers);
}
}
}
Remember onActivityResult method should be part of your MyClassA.java class and should not be in onCreate nor in some other existing standard methods of this class.
Hope it helps
Thank you for everyones help. This one worked as needed
package com.example.spdwiz18.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import java.text.DateFormat;
import java.time.*;
import java.time.temporal.*;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class GrindLogActivity extends AppCompatActivity {
TextView barcodeResult;
TextView bcc;
TextView pc;
TextView pd;
TextView sn;
TextView nw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gringlogactivity);
bcc = (TextView)findViewById(R.id.bccheck);
pc = (TextView)findViewById(R.id.pcode);
pd = (TextView)findViewById(R.id.pDate);
// TextView en = (TextView)findViewById(R.id.estnum);
sn = (TextView)findViewById(R.id.seqnum);
nw = (TextView)findViewById(R.id.nweight);
barcodeResult = (TextView) findViewById(R.id.barcode_result);
TextView julianDate = (TextView) findViewById(R.id.datecode);
TextView td1 = (TextView) findViewById(R.id.todaydate1);
// this is how to set id's from the xml file with vNames. (julianDate)
// this is how you get a julian/original date for android
LocalDate now = LocalDate.now();
int julian = now.get(ChronoField.DAY_OF_YEAR);
// this how to set you current date for android
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
// this is how to set your vNames to your method variables
julianDate.setText(Integer.toString(julian));
td1.setText(stringDate);
}
/*add click event to the scan barcode button */
public void scanBarcode(View v) {
Intent intent = new Intent(this, ScanBarcodeActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
resultsBreakdown(barcode.displayValue.toString());
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(CharSequence result) {
if (result.length() == 44) {
pc.setText(result.subSequence(2,10));
pd.setText(result.subSequence(13,18));
sn.setText(result.subSequence(21,27));
nw.setText(result.subSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}}

Bluetooth application

I am making bluetooth application in which I want to send data using bluetooth. That task I am able to do. But after that I want open any particular file from device. Then How can I do it? I have written the code below.
package com.example.blue;
import java.io.File;
import java.util.List;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int DISCOVER_DURATION=300;
private static final int REQUEST_BLU=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path="/storage/emulated/0/DCIM/Camera/20141018_152852.jpg";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().indexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file),type);
startActivity(intent);
}
public void sendViaBluetooth(View v){
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null)
{
Toast.makeText(this,"Bluetooth not supported" , Toast.LENGTH_LONG).show();
}else
{
enableBluetooth();
}
}
public void enableBluetooth(){
Intent discoveryIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
File f = new File(Environment.getExternalStorageDirectory(),"md5sum.txt");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
PackageManager pm = getPackageManager();
List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0);
if(appsList.size()>0)
{
String packageName = null;
String className = null;
boolean found = false;
for(ResolveInfo info : appsList)
{
packageName = info.activityInfo.packageName;
if(packageName.equals("com.android.bluetooth"))
{
className = info.activityInfo.name;
found = true;
break;
}
}
if(!found){
Toast.makeText(this,"Bluetooth haven't been found" , Toast.LENGTH_LONG).show();
}else
{
intent.setClassName(packageName, className);
startActivity(intent);
}
}
}else{
Toast.makeText(this,"Bluetooth is cancelled" , Toast.LENGTH_LONG).show();
}
}
}

Barcode scanner with outpan database

I want to develop a barcode scanner app in android, I tried using zxing library.
the zxing scanner reads a barcode very well and then asks user for websearch or product search thru google and displays google results.
Here is what I am doing up till now:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class ScanCodeActivity extends Activity {
private Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scancodelayout);
scan= (Button)findViewById(R.id.scan_button);
Button scanBtn = (Button)findViewById(R.id.scan_button);
final TextView formatTxt = (TextView)findViewById(R.id.scan_format);
final TextView contentTxt = (TextView)findViewById(R.id.scan_content);
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(ScanCodeActivity.this);
scanIntegrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
if (scanningResult != null) {
final TextView formatTxt = (TextView)findViewById(R.id.scan_format);
final TextView contentTxt = (TextView)findViewById(R.id.scan_content);
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
Toast toast = Toast.makeText(this, "Content:" + scanContent + " Format:" + scanFormat , Toast.LENGTH_LONG);
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
//we have a result
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
Log.i("App","Scan unsuccessful");
}
}
}
#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;
}
}
What I want to achieve is I want to query a non commercial database. I have found this link:
http://www.outpan.com/developers-get-product-data.php
Can anyone tell me how to use it in android?
I want to scan a particular code and query outpan database with it so that I parse the results into Strings and display them in my android app. User's will know which product the barcode represents..

Using Media Player inside my app

I am running a Text To Speech code, but now my new requirement is to provide "Pause" facility. I read number of SO questions and found I have to write data into a file and have to use media player class to play the file. Below is my code.
public void speak(String text)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, map,"ttsFile.wav");
//tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
Here I have 2 questions.
I do not want to open media player to play the file, file should be played inside the app with the media player controls (just like how you can set videoView.setMediaController(); to VideoView). How can I do this? any example please?
Is there any "Cache" place to save the above file so it will be deleted once the app is closed?
You can do something like this:
Create a video player in your application :
VideoPlayerActivity.java:
package com.camera.manual;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoPlayerActivity extends Activity {
private boolean mResumed = false;
private boolean mFocused = false;
private boolean mControlResumed = false;
private VideoView videoView = null;
private int stopPosition = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_TransparentVideo);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setContentView(R.layout.video_view);
videoView =(VideoView)findViewById(R.id.myvideoview);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri=Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.slow);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
#Override
public void onPause() {
super.onPause();
mResumed = false;
if (mControlResumed) {
if (null != videoView)
videoView.pause();
stopPosition = videoView.getCurrentPosition();
mControlResumed = false;
}
}
#Override
public void onResume() {
super.onResume();
mResumed = true;
if (mFocused && mResumed && !mControlResumed) {
if(null != videoView) {
//videoView.resume();
videoView.seekTo(stopPosition);
videoView.start();
}
mControlResumed = true;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mFocused = hasFocus;
if (mFocused && mResumed && !mControlResumed) {
if (null != videoView) {
//videoView.resume();
videoView.seekTo(stopPosition);
videoView.start();
}
mControlResumed = true;
}
}
}
You can call it like this:
Intent intent = new Intent();
intent.setClass(mContext, VideoPlayerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intent);

Categories