I am trying to create a BLE android app, and I've been having a lot of trouble with null pointers that I can't figure out even when using androids sample apps of android-BluetoothAdvertisements and android-BluetoothLEGatt.
This is my code:
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private boolean mScanning;
private ScanCallback mScanCallback;
private Handler mHandler;
private BluetoothDevice mBluetoothGatt;
private String mDeviceName;
private String mDeviceAddress;
private ScanResultAdapter mAdapter;
private BluetoothGattDescriptor mDescriptor;
private BluetoothGattCharacteristic mBluetoothCharacteristic;
private BluetoothDevice device;
private int mConnectionState = STATE_DISCONNECTED;
private BluetoothLeScanner btScanner;
private BluetoothDevice mbluetoothDevice;
Button button;
DrawerLayout dLayout;
private Button ble_scan;
private final static int REQUEST_ENABLE_BT = 1;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
// Stops scanning after 5 seconds.
private static final long SCAN_PERIOD = 5000;
//On entering app protocols
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
//Set View and new Handler
setContentView(R.layout.activity_main);
mHandler = new Handler();
mAdapter = new ScanResultAdapter(this.getApplicationContext(),
LayoutInflater.from(this));
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
//sets up variables to initialize Bluetooth Manager and our Adapter settings
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
//Initializes Navigation Drawer
setNavigationDrawer();
//Checks if Bluetooth adapter is enabled and requests to enable it
if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
//Initializes Scan Button
//addListenerOnButton();
//startScanning();
TextView txtView = (TextView) findViewById(R.id.ScanOut);
txtView.setText(BluetoothDevice.EXTRA_NAME);
//Initializing floating action button
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
/**
* Custom ScanCallback object - adds to adapter on success, displays error on failure.
*/
private class SampleScanCallback extends ScanCallback {
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
for (ScanResult result : results) {
mAdapter.add(result);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
mAdapter.add(result);
mAdapter.notifyDataSetChanged();
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Toast.makeText(MainActivity.this, "Scan failed with error: " + errorCode, Toast.LENGTH_LONG)
.show();
}
}
/**
* Start scanning for BLE Advertisements (& set it up to stop after a set period of time).
*/
public void startScanning() {
if (mScanCallback == null) {
// Will stop the scanning after a set time.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
stopScanning();
}
}, SCAN_PERIOD);
// Kick off a new scan.
mScanCallback = new SampleScanCallback();
mBluetoothLeScanner.startScan(mScanCallback);
Toast.makeText(MainActivity.this, "Started Scan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Already Scanning", Toast.LENGTH_SHORT);
}
}
/**
* Stop scanning for BLE Advertisements.
*/
public void stopScanning() {
// Stop the scan, wipe the callback.
mBluetoothLeScanner.stopScan(mScanCallback);
mScanCallback = null;
// Even if no new results, update 'last seen' times.
mAdapter.notifyDataSetChanged();
}
/* private void scanLeDevice(final boolean enable) {
//mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothLeScanner.startScan(mScanCallback);
} else {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
}
}*/
private void GattConnect() {
BluetoothGatt mBluetoothGatt = mbluetoothDevice.connectGatt(this, false, mGattCallback);
mBluetoothGatt.discoverServices();
List<BluetoothGattService> services = mBluetoothGatt.getServices();
for (BluetoothGattService service : services) {
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
}
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
// this will get called anytime you perform a read or write characteristic operation
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
// this will get called when a device connects or disconnects
}
#Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
// this will get called after the client initiates a BluetoothGatt.discoverServices() call
}
};
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = MainActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText("Unknown Device");
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
/*
Setting up Navigational Drawer that creates other fragments
*/
private void setNavigationDrawer() {
Intent intent = null;
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // initiate a DrawerLayout
NavigationView navView = (NavigationView) findViewById(R.id.navigation); // initiate a Navigation View
// implement setNavigationItemSelectedListener event on NavigationView
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment frag = null; // create a Fragment Object
int itemId = menuItem.getItemId(); // get selected menu item's id
// check selected menu item's id and replace a Fragment Accordingly
if (itemId == R.id.nav_home){
frag = new HomeFragment();
} else if (itemId == R.id.nav_alarms) {
frag = new AlarmFragment();
} else if (itemId == R.id.nav_cues) {
frag = new CueFragment();
} else if (itemId == R.id.nav_data) {
frag = new DataFragment();
} else if (itemId == R.id.nav_settings){
frag = new SettingFragment();
} else if (itemId == R.id.nav_help){
frag = new HelpFragment();
}
// display a toast message with menu item's title
Toast.makeText(getApplicationContext(), menuItem.getTitle(), Toast.LENGTH_SHORT).show();
if (frag != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, frag); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
dLayout.closeDrawers(); // close the all open Drawer Views
return true;
}
return false;
}
});
}
public void addListenerOnButton() {
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//scanLeDevice(true);
}
});
}
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
//What happens on resuming the app
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
//setListAdapter(mLeDeviceListAdapter);
//scanLeDevice(true);
}
#Override
protected void onPause() {
super.onPause();
//scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
I am using the BluetoothLeService class from the Gatt example. Right now I am trying to get my scanning to work so I can find my BLE device to attempt to set up a Gatt connection with it.
I have tried implementing many parts of the examples, and since startLeScan() and stopLeScan() are depreciated, I am attempting to merge the BLE scanning from the bluetooth advertisements example with the BLE Gatt example. The apps examples work fine, but I get a bunch of null pointers when I try to do it myself.
On my onResume function I will get this error: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
Which is weird because I invoke the same method during onCreate without problems.
The thing that hasn't been working at all no matter how I try to invoke it is my startScanning method. I always get this error: 'java.lang.NullPointerException: Attempt to invoke virtual method void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference because it seems like the startScan method never actually works. Maybe I am just doing something horribly wrong.
It's called in a fragment in the example, but I don't think that should affect it and I should be able to use it in my main activity for a base level connection for debugging if I'm not mistaken.
Does anyone have any advice on what I'm doing glaringly wrong?
Related
I am working on an Android app with a steadily growing Code basis; the aim of the app is to scan and process QR Codes and Barcodes on Handheld Devices for Storages (not Smartphones). It hast two Activities that contain major parts of the programmatical logic; hence, I want to store major parts of the Code that contains the Functionality for processing the Scanner input in an external Service, called Scanner Service, implement the methods there and use the methods in other Activites;
however, I have a major issue with the use of Context, getApplicationContext() and the reference of the Activity in the Service and vice versa; although I think I have referenced and initialised the Textviews from the Activity in the Service, the app keeps on crashing with the following error message:
AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
at com.xxxx.ScanService.<clinit>(ScanService.java:16)
I know what it means, but I donĀ“t know how I could access the View
private static TextView content = (TextView) a.findViewById(R.id.content_detail);
in such a way that I can use it in the Service and in the Activity and the app stops crashing.
Therefore, any hints or help would be very much appreciated, thank you in advance.
The MainDetailActivity:
package com.example.xxx_app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.xxx.ScanService.*;
import static com.xxx.SimpleItemRecyclerViewAdapter.TAGG;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public class MainDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
Context context;
private RecyclerView recyclerView;
private RecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
private ListView listView;
public TextView textView4;
public String code;
public static final String TAG = "Barcode ist:" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_detail);
context = this;
//TextView headerView = findViewById(R.id.txt1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
EditText editBarcode = (EditText) findViewById(R.id.editText);
TextView content = (TextView) findViewById(R.id.content_detail);
TextView editTextNumber = findViewById(R.id.editTextNumber);
Button addBooking = findViewById(R.id.button);
Button removeBooking = findViewById(R.id.button2);
removeBooking.setEnabled(false);
spinner.setOnItemSelectedListener(this);
//String selectedItem = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
String scannedCode = getIntent().getStringExtra("scannedCode");
Log.d(TAG, "scannedCode" + scannedCode);
if (scannedCode != null && (content.getText().toString().equals(""))) {
content.setText(scannedCode);
}
Button btn = findViewById(R.id.imageView4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainDetailActivity.this, v);
popup.setOnMenuItemClickListener(MainDetailActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
editBarcode.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "Code ist leer");
}
if (keyCode == KeyEvent.KEYCODE_ENTER && code.length() > 0) {
editBarcode.setText("");
ScanService.checkEnteredCode(code);
return true;
}
return false;
}
});
recyclerView = findViewById(R.id.recyclerview);
recyclerviewAdapter = new RecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
content.setText(receivedCountItems);
RestClient.getPaletteItems(getApplicationContext(),recyclerviewAdapter,receivedPalNo);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
final ArrayList<Items> itemList = new ArrayList<>();
/*
Items[] items = new Items(12345,123456, 200, 500);
itemList.add(items);*/
recyclerviewAdapter.setItemList((ArrayList<Items>) itemList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
RecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
//Toast.makeText(getApplicationContext(),itemList.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task,R.id.edit_task)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
switch (viewID){
case R.id.delete_task:
itemList.remove(position);
finalRecyclerviewAdapter.setItemList(itemList);
break;
case R.id.edit_task:
Toast.makeText(getApplicationContext(),"Edit Not Available",Toast.LENGTH_SHORT).show();
break;
}
}
});
recyclerView.addOnItemTouchListener(touchListener);
class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don"t need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
String text = getIntent().getStringExtra("palNo");
//headerView.setText(text);
if (receivedType != null && receivedType.equals("FE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_blue);
}
if (receivedType != null && receivedType.equals("UFE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_yellow);
}
}
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;
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void newDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Abbrechen" ,Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
dialog.show();
}
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.newcustom_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The ScanService Class:
package com.example.xxx;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
public class ScanService {
private static final String TAG = "Scan Service Tag";
private static Context mContext;
private static Activity a = (MainDetailActivity)mContext;
private static TextView content = (TextView)
a.findViewById(R.id.content_detail);
private static TextView editTextNumber = (TextView)
a.findViewById(R.id.editTextNumber);
public ScanService (Context mContext) {
this.mContext = mContext;
}
public static void checkEnteredCode(String code, Activity a) {
content.setText("");
//PSP-H1-EA-F3
if
(code.matches("PSP-\\p{Upper}\\d\\p{Punct}\\p{Upper}\\" +
"p{Upper}\\p{Punct}\\p{Upper}\\p{Digit}")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("LF-[0-9]*")) {
///LF-(\d+)/gi
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("PAL-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("P-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "Palette");
}
if (code.matches("[0-9][0-9][0-9][0-9].[0-9][0-9].+DB")) {
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
if (code.matches("[0-9A-Z]*[0-9]*")) {
//editBarcode.setText("");
//editBarcode.setText(keyCode);
Log.d(TAG, "xxx");
}
if (code.matches("\\d{13}")) {
//newDialog(MainDetailActivity.this);
//editBarcode.setText("");
//editBarcode.setText(keyCode);
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
else {
Log.d(TAG, "xxx");
};
//editBarcode.setText("");
//editBarcode.setText(code);
/* String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "xxx");
}
//}
checkEnteredCode(code);
//editBarcode.setText("");
return Boolean.parseBoolean(code);*/
Log.d(TAG, code);
}
public static void checkEnteredCode(String code) {
}
}
You cannot access any Views from a Service! Views belong to the Activity. This is the wrong application architecture. A Service performs background processing (file I/O, network I/O, computation, etc.). The Activity is responsible for interacting with the user (inputs, display, etc.). If your Service wants to put data on the screen, you've broken the division of responsibilities. Your Service should simply notify your Activity (or any other component that is interested) when data has changed, and the Activity can then update the View itself. You can share data between the Service and your other components in a number of ways, including: event bus, publish/subscribe, shared preferences, broadcast Intents, SQLite database, etc.
I'm trying to connect to an ble device, so I've implemented a bluetooth ble scan activity for this, but this does not work on my tablet (Archos 70 3G with android 7.0) but works in my phone (Xiaomi Note 8 Pro). I allowed location and bluetooth both devices. What is the problem? The code of the activity:
package myapp
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import myapp.R;
public class BluetoothListActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter;
// private BluetoothAdapter mBtAdapter;
private TextView mEmptyList;
public static final String TAG = "DeviceListActivity";
List<BluetoothDevice> deviceList;
private DeviceAdapter deviceAdapter;
private ServiceConnection onService = null;
Map<String, Integer> devRssiValues;
private static final long SCAN_PERIOD = 10000; //scanning for 10 seconds
private Handler mHandler;
private boolean mScanning;
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] Results) {
if (requestCode == 1) {
Toast.makeText(this, "Git gud", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Toast.makeText(this, "git gud", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_device_list);
android.view.WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.gravity = Gravity.TOP;
layoutParams.y = 200;
mHandler = new Handler();
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "Ble not supported", Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Not supported", Toast.LENGTH_SHORT).show();
finish();
return;
}
populateList();
mEmptyList = (TextView) findViewById(R.id.empty);
Button cancelButton = (Button) findViewById(R.id.btn_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mScanning == false) scanLeDevice(true);
else finish();
}
});
}
private void populateList() {
/* Initialize device list container */
Log.d(TAG, "populateList");
deviceList = new ArrayList<BluetoothDevice>();
deviceAdapter = new DeviceAdapter(this, deviceList);
devRssiValues = new HashMap<String, Integer>();
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(deviceAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
scanLeDevice(true);
}
private void scanLeDevice(final boolean enable) {
final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
cancelButton.setText(R.string.scan);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
cancelButton.setText(R.string.cancel);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
cancelButton.setText(R.string.scan);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addDevice(device, rssi);
}
});
}
};
private void addDevice(BluetoothDevice device, int rssi) {
boolean deviceFound = false;
for (BluetoothDevice listDev : deviceList) {
if (listDev.getAddress().equals(device.getAddress())) {
deviceFound = true;
break;
}
}
devRssiValues.put(device.getAddress(), rssi);
if (!deviceFound) {
deviceList.add(device);
mEmptyList.setVisibility(View.GONE);
deviceAdapter.notifyDataSetChanged();
}
}
#Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
}
#Override
public void onStop() {
super.onStop();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
#Override
public void onDestroy() {
super.onDestroy();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice device = deviceList.get(position);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Bundle b = new Bundle();
b.putString(BluetoothDevice.EXTRA_DEVICE, deviceList.get(position).getAddress());
Intent result = new Intent();
result.putExtras(b);
setResult(Activity.RESULT_OK, result);
Toast.makeText(getApplicationContext(), "Connected to " + deviceList.get(position).getName(), Toast.LENGTH_SHORT).show();
finish();
}
};
public void onPause() {
super.onPause();
scanLeDevice(false);
}
class DeviceAdapter extends BaseAdapter {
Context context;
List<BluetoothDevice> devices;
LayoutInflater inflater;
public DeviceAdapter(Context context, List<BluetoothDevice> devices) {
this.context = context;
inflater = LayoutInflater.from(context);
this.devices = devices;
}
#Override
public int getCount() {
return devices.size();
}
#Override
public Object getItem(int position) {
return devices.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup vg;
if (convertView != null) {
vg = (ViewGroup) convertView;
} else {
vg = (ViewGroup) inflater.inflate(R.layout.device_list_element, null);
}
BluetoothDevice device = devices.get(position);
final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
final TextView tvname = ((TextView) vg.findViewById(R.id.name));
final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);
tvrssi.setVisibility(View.VISIBLE);
byte rssival = (byte) devRssiValues.get(device.getAddress()).intValue();
if (rssival != 0) {
tvrssi.setText("Rssi = " + String.valueOf(rssival));
}
tvname.setText(device.getName());
tvadd.setText(device.getAddress());
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.i(TAG, "device::" + device.getName());
tvname.setTextColor(Color.BLACK);
tvadd.setTextColor(Color.BLACK);
tvpaired.setTextColor(Color.GRAY);
tvpaired.setVisibility(View.VISIBLE);
tvpaired.setText(R.string.paired);
tvrssi.setVisibility(View.VISIBLE);
tvrssi.setTextColor(Color.BLACK);
} else {
tvname.setTextColor(Color.BLACK);
tvadd.setTextColor(Color.BLACK);
tvpaired.setVisibility(View.GONE);
tvrssi.setVisibility(View.VISIBLE);
tvrssi.setTextColor(Color.BLACK);
}
return vg;
}
}
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
I'm using recycleview in google cloud speech api.
And I would like to put the strings in the recycleview into a single edit text.
How do I move a string from a recycleview into a single text?
enter code here
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.android.speech;
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.icu.util.ValueIterator;
import android.os.Bundle;
import android.os.IBinder;
import android.sax.Element;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
MessageDialogFragment.Listener {
static EditText edit1;
static EditText edit2;
static EditText edit3;
static String a1,a2;
static String[] b1,b2;
static int count=0;
Button btn;
private static final String FRAGMENT_MESSAGE_DIALOG = "message_dialog";
private static final String STATE_RESULTS = "results";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 1;
private SpeechService mSpeechService;
private VoiceRecorder mVoiceRecorder;
private final VoiceRecorder.Callback mVoiceCallback = new
VoiceRecorder.Callback() {
#Override
public void onVoiceStart() {
showStatus(true);
if (mSpeechService != null) {
mSpeechService.startRecognizing(mVoiceRecorder.getSampleRate());
}
}
#Override
public void onVoice(byte[] data, int size) {
if (mSpeechService != null) {
mSpeechService.recognize(data, size);
}
}
#Override
public void onVoiceEnd() {
showStatus(false);
if (mSpeechService != null) {
mSpeechService.finishRecognizing();
}
}
};
// Resource caches
private int mColorHearing;
private int mColorNotHearing;
// View references
private TextView mStatus;
private TextView mText;
private ResultAdapter mAdapter;
private RecyclerView mRecyclerView;
private final ServiceConnection mServiceConnection = new
ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName componentName, IBinder
binder) {
mSpeechService = SpeechService.from(binder);
mSpeechService.addListener(mSpeechServiceListener);
mStatus.setVisibility(View.VISIBLE);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mSpeechService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit1=(EditText) findViewById(R.id.edit1);
edit2=(EditText) findViewById(R.id.edit2);
edit3=(EditText) findViewById(R.id.edit3);
btn=(Button)findViewById(R.id.button);
final Resources resources = getResources();
final Resources.Theme theme = getTheme();
mColorHearing = ResourcesCompat.getColor(resources,
R.color.status_hearing, theme);
mColorNotHearing = ResourcesCompat.getColor(resources,
R.color.status_not_hearing, theme);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
mStatus = (TextView) findViewById(R.id.status);
mText = (TextView) findViewById(R.id.text);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final ArrayList<String> results = savedInstanceState == null ? null :
savedInstanceState.getStringArrayList(STATE_RESULTS);
mAdapter = new ResultAdapter(results);
mRecyclerView.setAdapter(mAdapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onStart() {
super.onStart();
// Prepare Cloud Speech API
bindService(new Intent(this, SpeechService.class), mServiceConnection,
BIND_AUTO_CREATE);
// Start listening to voices
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED) {
startVoiceRecorder();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
showPermissionMessageDialog();
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_AUDIO_PERMISSION);
}
}
#Override
protected void onStop() {
// Stop listening to voice
stopVoiceRecorder();
// Stop Cloud Speech API
mSpeechService.removeListener(mSpeechServiceListener);
unbindService(mServiceConnection);
mSpeechService = null;
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mAdapter != null) {
outState.putStringArrayList(STATE_RESULTS, mAdapter.getResults());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
if (permissions.length == 1 && grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startVoiceRecorder();
} else {
showPermissionMessageDialog();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_file:
mSpeechService.recognizeInputStream
(getResources().openRawResource(R.raw.audio));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startVoiceRecorder() {
if (mVoiceRecorder != null) {
mVoiceRecorder.stop();
}
mVoiceRecorder = new VoiceRecorder(mVoiceCallback);
mVoiceRecorder.start();
}
private void stopVoiceRecorder() {
if (mVoiceRecorder != null) {
mVoiceRecorder.stop();
mVoiceRecorder = null;
}
}
private void showPermissionMessageDialog() {
MessageDialogFragment
.newInstance(getString(R.string.permission_message))
.show(getSupportFragmentManager(), FRAGMENT_MESSAGE_DIALOG);
}
private void showStatus(final boolean hearingVoice) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mStatus.setTextColor(hearingVoice ? mColorHearing :
mColorNotHearing);
}
});
}
#Override
public void onMessageDialogDismissed() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_AUDIO_PERMISSION);
}
private final SpeechService.Listener mSpeechServiceListener =
new SpeechService.Listener() {
#Override
public void onSpeechRecognized(final String text, final boolean
isFinal) {
if (isFinal) {
mVoiceRecorder.dismiss();
}
if (mText != null && !TextUtils.isEmpty(text)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (isFinal) {
mText.setText(null);
mAdapter.addResult(text);
mRecyclerView.smoothScrollToPosition(0);
} else {
mText.setText(text);
}
}
});
}
}
};
private static class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_result, parent, false));
text = (TextView) itemView.findViewById(R.id.text);
}
}
private static class ResultAdapter extends
RecyclerView.Adapter<ViewHolder> {
private final ArrayList<String> mResults = new ArrayList<>();
ResultAdapter(ArrayList<String> results) {
if (results != null) {
mResults.addAll(results);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()),
parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.text.setText(mResults.get(position));
}
#Override
public int getItemCount() {
return mResults.size();
}
void addResult(String result) {
mResults.add(0, result);
notifyItemInserted(0);
}
public ArrayList<String> getResults() {
return mResults;
}
}
}
here is java code.
if you know the answer, let me know..
I tried but it doesn't work. The editview doesn't show all of texts in reclycleview...
Create a TextView element outside of that recycle view. Then initialize it onCreate() method.
You need to extract text from that recycle view. I have no idea about that u hold data. Anyhow get a text from that.
Then updateText using textView.setText(...) when that recycleText updated
Define TextView like this in mainActivity and initalize it in onCreate
static TextView recyText;
in
oncreate(){
....
recyText=(TextView) findViewById(R.id.recyText);
}
the update it in below code segment
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.text.setText(mResults.get(position));
recyText.setText(recyText.getText()+ " " +mResults.get(position))
}
So i developed an android news app. A spinner item is available on the toolbar and data reloads according to spinner selection. However, when the data reloads, for some of the items, it directly loads the relevant content but for some others, it loads the previously selected spinner data. Current data for the current item only shows after reloading same spinner data using the swipe refresh functionality which i had implemented. I want the correct data relevant to that selection to load the first time itself without having to refresh all the time.
Below is my MainActivity where all these functions are called.
package com.example.app.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="url" //outputs JSON data
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
prefManager = new PrefManager(MainActivity.this);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if (++check > 1) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
//intent.putExtra("NAME_KEY", itemSelected);
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(myString)) {
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//TODO DONE
String name = prefManager.spinReadString();
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
//TODO DONE
if (spinConstituency.equals(name))
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
//TODO DONE
prefManager.writeString("" + spinConstID);
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position % 2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
I discovered that from API level 3, one can use the onUserInteraction() on an Activity with a boolean value thereby determining the user's interaction.
Find the documentation in the link below.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userInteracts = true;
}
The my adjustment goes as thus in the MainActivity.java
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (IsInteracting) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
I have a class, and I want that this class works in background. I thought I'd put it in a service, but I do not know how to do it. This is my class called DeviceScanActivity.java:
package com.example.giacomob.myapplication;
/**
* Created by Giacomo B on 20/09/2015.
*/
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
class MyService extends Service{
}
public class DeviceScanActivity extends ListActivity {
MyService service = new MyService();
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 2100000000;
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("BLEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
scanLeDevice(true);
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
*/
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
/*
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
*/
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
and I would to insert this class in a Service like this:
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.app.IntentService;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Giacomo B on 20/09/2015.
*/
public class LogService extends IntentService
{
public LogService()
{
super("LogService");
}
#Override
protected void onHandleIntent(Intent i)
{
int n=0;
while(true)
{
Log.i("PROVA SERVICE", "Evento n." + n++);
Toast.makeText(this, "Ho aperto il LogService", Toast.LENGTH_SHORT).show();
// Intent second = new Intent(getApplicationContext(), DeviceScanActivity.class);
// startActivity(second);
try {
Thread.sleep(10000);
}
catch (InterruptedException e)
{ }
}
}
How I can do it? Please, help me. Thanks
To run your scanning in the background, you'll want to put all your scanning code in your IntentService. The onHandleIntent method in your service has a similar logical function to your activity's onCreate method, so you can put your initialization code there.
Your activity will launch your service. To schedule regular scans, use either JobScheduler (preferred) or AlarmManager to send intents to launch your service at specified intervals. Be sure to pass your application context rather than your activity context when launching intents so that scanning may occur when your activity has been destroyed.
P.S. Please do not use an infinite loop and a sleep call. This will cause unnecessary blocking on your service thread and waste resources.