I can't figure out why my onClick method for my buttons are not working. Everytime I click the button, my logcat says ViewPostImeInputStage Action_Down.
I appreciate any help!
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
BluetoothConnect fragment = new BluetoothConnect();
transaction.add(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
And this is my fragment.
public class BluetoothConnect extends Fragment {
//For debugging purposes
private static final String TAG = "BluetoothConnect";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
//Main buttons
private Button shareButton;
private Button listenButton;
private TextView test;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
listenButton = (Button) view.findViewById(R.id.listen);
shareButton = (Button) view.findViewById(R.id.share);
test = (TextView) view.findViewById(R.id.test);
}
#Override
public void onStart() {
super.onStart();
//If BT is not on, request that it be enabled
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
setupButtons();
}
}
#Override
public void onDestroy() {
super.onDestroy();
//Figure out what to do if we need to destroy
}
#Override public void onResume() {
super.onResume();
//figure out what to do if person pauses out of app
}
public void setupButtons() {
Log.d(TAG, "setupButtons()");
//Initialize the music buttons
listenButton.setOnClickListener(new ButtonOnClickListener("listen"));
Log.d(TAG, "finished listenButton");
shareButton.setOnClickListener(new ButtonOnClickListener("share"));
}
private class ButtonOnClickListener implements View.OnClickListener {
String type;
public ButtonOnClickListener(String button) {
Log.d(TAG, this.type);
this.type = button;
}
public void onClick(View view) {
if (this.type == "listen") {
listenMusic();
} else {
shareMusic();
}
}
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private void listenMusic() {
Log.d(TAG, "OMG ITS WORKING");
}
private void shareMusic() {
Log.d(TAG, "OMG ITS WORKING");
}
}
Thanks so much!
have a look here
https://stackoverflow.com/a/32016362/5281187
Wrap your layout over the one you already have
Related
I have created simple chatting application and it contains some ListView which handles all chat messages, but every ListView is defined in another class. I want to clear my list items from Clear Chat from an overflow menu, which is present in main activity. How can I achieve this?
Here is my main activity called WiFiServiceDiscoveryActivity:
public class WiFiServiceDiscoveryActivity extends AppCompatActivity implements
DeviceClickListener, Handler.Callback, MessageTarget,
ConnectionInfoListener {
public static final String TAG = "wifidirectdemo";
// TXT RECORD properties
public static final String TXTRECORD_PROP_AVAILABLE = "available";
public static final String SERVICE_INSTANCE = " ";
public static final String SERVICE_REG_TYPE = "_presence._tcp";
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MY_HANDLE = 0x400 + 2;
private WifiP2pManager manager;
static final int SERVER_PORT = 4545;
private final IntentFilter intentFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
private WifiP2pDnsSdServiceRequest serviceRequest;
private Handler handler = new Handler(this);
private WiFiChatFragment chatFragment;
private WiFiDirectServicesList servicesList;
private TextView statusTxtView;
Toolbar toolbar;
private String friend;
private WiFiP2pService service;
WiFiChatFragment listView;
WiFiChatFragment.ChatMessageAdapter a;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toolbar=(Toolbar)findViewById(R.id.toolbar);
statusTxtView = (TextView) findViewById(R.id.status_text);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
startRegistrationAndDiscovery();
servicesList = new WiFiDirectServicesList();
getFragmentManager().beginTransaction()
.add(R.id.container_root, servicesList, "services").commit();
setSupportActionBar(toolbar);
}
#Override
protected void onRestart() {
Fragment frag = getFragmentManager().findFragmentByTag("services");
if (frag != null) {
getFragmentManager().beginTransaction().remove(frag).commit();
}
super.onRestart();
}
#Override
protected void onStop() {
if (manager != null && channel != null) {
manager.removeGroup(channel, new ActionListener() {
#Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
#Override
public void onSuccess() {
}
});
}
super.onStop();
}
/**
* Registers a local service and then initiates a service discovery
*/
private void startRegistrationAndDiscovery() {
Map<String, String> record = new HashMap<String, String>();
record.put(TXTRECORD_PROP_AVAILABLE, "visible");
WifiP2pDnsSdServiceInfo service = WifiP2pDnsSdServiceInfo.newInstance(
SERVICE_INSTANCE, SERVICE_REG_TYPE, record);
manager.addLocalService(channel, service, new ActionListener() {
#Override
public void onSuccess() {
//appendStatus("Added Local Service");
}
#Override
public void onFailure(int error) {
// appendStatus("Failed to add a service");
}
});
discoverService();
}
private void discoverService() {
/*
* Register listeners for DNS-SD services. These are callbacks invoked
* by the system when a service is actually discovered.
*/
manager.setDnsSdResponseListeners(channel,
new DnsSdServiceResponseListener() {
#Override
public void onDnsSdServiceAvailable(String instanceName,
String registrationType, WifiP2pDevice srcDevice) {
// A service has been discovered. Is this our app?
if (instanceName.equalsIgnoreCase(SERVICE_INSTANCE)) {
// update the UI and add the item the discovered
// device.
WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager()
.findFragmentByTag("services");
if (fragment != null) {
WiFiDevicesAdapter adapter = ((WiFiDevicesAdapter) fragment
.getListAdapter());
service = new WiFiP2pService();
service.device = srcDevice;
service.instanceName = instanceName;
service.serviceRegistrationType = registrationType;
adapter.add(service);
adapter.notifyDataSetChanged();
Log.d(TAG, "onBonjourServiceAvailable "
+ instanceName);
}
}
}
}, new DnsSdTxtRecordListener() {
/**
* A new TXT record is available. Pick up the advertised
* buddy name.
*/
#Override
public void onDnsSdTxtRecordAvailable(
String fullDomainName, Map<String, String> record,
WifiP2pDevice device) {
Log.d(TAG,
device.deviceName + " is "
+ record.get(TXTRECORD_PROP_AVAILABLE));
}
});
// After attaching listeners, create a service request and initiate
// discovery.
serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
manager.addServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
// appendStatus("Added service discovery request");
}
#Override
public void onFailure(int arg0) {
appendStatus("Failed adding service discovery request");
}
});
manager.discoverServices(channel, new ActionListener() {
#Override
public void onSuccess() {
//appendStatus("Service discovery initiated");
}
#Override
public void onFailure(int arg0) {
appendStatus("Service discovery failed");
}
});
}
#Override
public void connectP2p(WiFiP2pService service) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = service.device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
if (serviceRequest != null)
manager.removeServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int arg0) {
}
});
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Connecting to service");
}
#Override
public void onFailure(int errorCode) {
appendStatus("Failed connecting to service");
}
});
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
(chatFragment).pushMessage("Friend :" + readMessage);
break;
case MY_HANDLE:
Object obj = msg.obj;
(chatFragment).setChatManager((ChatManager) obj);
}
return true;
}
#Override
public void onResume() {
super.onResume();
receiver = new HomeActivity(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo) {
Thread handler = null;
if (p2pInfo.isGroupOwner) {
Log.d(TAG, "Connected as group owner");
try {
handler = new GroupOwnerSocketHandler(
((MessageTarget) this).getHandler());
handler.start();
} catch (IOException e) {
Log.d(TAG,
"Failed to create a server thread - " + e.getMessage());
return;
}
} else {
Log.d(TAG, "Connected as peer");
handler = new ClientSocketHandler(
((MessageTarget) this).getHandler(),
p2pInfo.groupOwnerAddress);
handler.start();
}
chatFragment = new WiFiChatFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container_root, chatFragment).commit();
statusTxtView.setVisibility(View.GONE);
}
public void appendStatus(String status) {
String current = statusTxtView.getText().toString();
statusTxtView.setText(current + "\n" + status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
.show();
break;
case R.id.clean:
Toast.makeText(this, "Clear Chat", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
}
And another class which has the ListView called WiFiChatFragment:
public class WiFiChatFragment extends Fragment {
private View view;
private ChatManager chatManager;
private TextView chatLine;
private ListView listView;
ChatMessageAdapter adapter = null;
private List<String> items = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_chat, container, false);
chatLine = (TextView) view.findViewById(R.id.txtChatLine);
listView = (ListView) view.findViewById(android.R.id.list);
adapter = new ChatMessageAdapter(getActivity(), android.R.id.text1,
items);
listView.setAdapter(adapter);
view.findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (chatManager != null) {
chatManager.write(chatLine.getText().toString()
.getBytes());
pushMessage("Me: " + chatLine.getText().toString());
chatLine.setText("");
chatLine.clearFocus();
}
}
});
return view;
}
public interface MessageTarget {
public Handler getHandler();
}
public void setChatManager(ChatManager obj) {
chatManager = obj;
}
public void pushMessage(String readMessage) {
adapter.add(readMessage);
adapter.notifyDataSetChanged();
}
/**
* ArrayAdapter to manage chat messages.
*/
public class ChatMessageAdapter extends ArrayAdapter<String> {
List<String> messages = null;
public ChatMessageAdapter(Context context, int textViewResourceId,
List<String> items) {
super(context, textViewResourceId, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_1, null);
}
String message = items.get(position);
if (message != null && !message.isEmpty()) {
TextView nameText = (TextView) v
.findViewById(android.R.id.text1);
if (nameText != null) {
nameText.setText(message);
if (message.startsWith("Me: ")) {
nameText.setBackgroundResource(R.drawable.bubble_b );
nameText.setTextAppearance(getActivity(),
R.style.normalText);
} else {
nameText.setBackgroundResource(R.drawable.bubble_a );
nameText.setTextAppearance(getActivity(),
R.style.boldText);
}
}
}
return v;
}
}
}
Hey Adesh you could do this when the overflow item is clicked:
Call setListAdapter() again. This time with an empty ArrayList.
Hope it helps !
I am using the library barcodescanner from https://github.com/dm77/barcodescanner.
Currently the scanner displays a rectangle and a laser across the middle.
that looks similar to:
I am looking to make this view into a square since I am only scanning QR codes and to remove the laser and would appreciate some help.
My code that I have written so far for the scanner fragment is below
public class ScannerFragment extends Fragment implements
ZBarScannerView.ResultHandler
{
private static final String FLASH_STATE = "FLASH_STATE";
private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
private static final String CAMERA_ID = "CAMERA_ID";
private ZBarScannerView mScannerView;
private boolean mFlash;
private boolean mAutoFocus;
private ArrayList<Integer> mSelectedIndices;
private int mCameraId = -1;
Communicator messenger;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
messenger=(Communicator) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
mScannerView = new ZBarScannerView(getActivity());
if (state != null) {
mFlash = state.getBoolean(FLASH_STATE, false);
mAutoFocus = state.getBoolean(AUTO_FOCUS_STATE, true);
mSelectedIndices = state.getIntegerArrayList(SELECTED_FORMATS);
mCameraId = state.getInt(CAMERA_ID, -1);
} else {
mFlash = false;
mAutoFocus = true;
mSelectedIndices = null;
mCameraId = -1;
}
setupFormats();
return mScannerView;
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem menuItem;
if (mFlash) {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_on);
} else {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_off);
}
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.menu_flash:
mFlash = !mFlash;
if (mFlash) {
item.setTitle(R.string.flash_on);
} else {
item.setTitle(R.string.flash_off);
}
mScannerView.setFlash(mFlash);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(FLASH_STATE, mFlash);
outState.putBoolean(AUTO_FOCUS_STATE, mAutoFocus);
outState.putIntegerArrayList(SELECTED_FORMATS, mSelectedIndices);
outState.putInt(CAMERA_ID, mCameraId);
}
#Override
public void handleResult(Result rawResult) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification);
r.play();
}
catch (Exception e) {
}
}
}).start();
QRResults scanResult = QRResults.getInstance();
scanResult.Extract(rawResult.getContents());
if (scanResult.dataExtractedOK)
{
if (scanResult.canPerformElectricityComparison() || scanResult.canPerformGasComparison())
{
messenger.updateTextView("Found Code");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(getActivity(), SearchResult.class);
startActivity(i);
}
}, 2000);
}
}
else
{
messenger.updateTextView("Invalid Code");
// Restart Camera after 2 second delay
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mScannerView.startCamera();
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
messenger.updateTextView("Finding code...");
}
}, 2000);
}
}
public void onFormatsSaved(ArrayList<Integer> selectedIndices) {
mSelectedIndices = selectedIndices;
setupFormats();
}
public void setupFormats() {
List<BarcodeFormat> formats = new ArrayList<BarcodeFormat>();
formats.add(BarcodeFormat.QRCODE);
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
I think I need to extend a class from the library and override some of the methods in it but I'm not sure how to do this and have the overridden methods used in my scanner class.
Thank you for your time.
Add library module in a project (not as a dependency). Here is a tutorial how to add a library module in Android Studio.
Go to library module and find in ViewFinderView.java class drawLaser(Canvas canvas) method (draws the line in the middle).
i'm a beginner and i have some trouble with my android app. my app have 2 activities. the first is PlayerActivity.java it will list all song in sdcard by a listView and when i click on a item then the PlaysongActivity will appear.It's OK but when i press back button i'll show listview of song again but when i click on an item again then it open a new activity while the old one still playing. now i have 2 songs are playing at the same time. how can i solve this trouble? here is my code.
public class PlayerActivity extends Activity {
String pathToFile = new String("");
private List song = new ArrayList();
ListView listSong;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listSong = (ListView) findViewById(R.id.list);
listAllSong();
}
private void listAllSong() {
String end = ".mp3";
File myMp3Dir = new File("/sdcard/");
final File[] filelist = myMp3Dir.listFiles();
for (File f : filelist) {
if (!f.isDirectory()) {
if (f.getName().toLowerCase().contains(end)) {
song.add(f.getName());
}
}
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, song);
listSong.setAdapter(adapter);
listSong.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String path = parent.getItemAtPosition(position).toString();
Intent myIntent = new Intent(getApplicationContext(),
PlaysongActivity.class);
myIntent.putExtra("pathOfSong", path);
startActivity(myIntent);
finish();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.player, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
return rootView;
}
}
}
/and PlaysongActivity/
public class PlaysongActivity extends Activity {
MediaPlayer mp1;
SeekBar seekBar;
Boolean isPaused=false;
Handler mHandler=new Handler();
Boolean isMovingSeekBar=false;
ImageButton button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playsong);
TextView tvPlaysong=(TextView) findViewById(R.id.tv);
mp1=new MediaPlayer();
seekBar=(SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (isMovingSeekBar) {
mp1.seekTo(progress);
}
}
});
button=(ImageButton) findViewById(R.id.btnPlay);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp1.isPlaying()) {
mp1.pause();
button.setImageResource(android.R.drawable.ic_media_play);
} else if (isPaused) {
mp1.start();
button.setImageResource(android.R.drawable.ic_media_pause);
}
}
});
Intent i=getIntent();
String path=i.getStringExtra("pathOfSong");
tvPlaysong.setText(path);
if(mp1.isPlaying()) mp1.stop();
playSong(path);
}
private void playSong(String path) {
seekBar.setProgress(0);
if(mp1!=null) mp1.stop();
try {
mp1.setDataSource("/sdcard/" + path);
mp1.prepare();
mp1.start();
seekBar.setMax(mp1.getDuration());
updateSeekBar();
isPaused = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
button.setImageResource(android.R.drawable.ic_media_pause);
}
private void updateSeekBar() {
mHandler.postDelayed(getTimeTask, 1000);
}
private Runnable getTimeTask=new Runnable() {
public void run() {
long duration=mp1.getDuration();
long currentPosition=mp1.getCurrentPosition();
seekBar.setProgress((int) currentPosition);
mHandler.postDelayed(this, 1000);
}
};
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.playsong, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_playsong,
container, false);
return rootView;
}
}
}
In PlaysongActivity, override onStop() and call release() on the MediaPlayer.
This will stop playback (and release resources) when you exit that activity.
I am using the class SpeechRecognizer by calling the method startListening when a button is pressed, but I get an error. First the callback methods onReadyForSpeech, onBeginningOfSpeech, onEndofSpeech are called (immediately) and at the end onError with the errorcode 2 "ERROR_NETWORK" is called. When I call the intent directly by using startActivityForResult, it works. But I want to get rid of the time consuming popup dialog.
I have the RECORD_AUDIO permission set.
I am not sure, but perhaps the intent want to load something from the internet. For that, I tried to add the INTERNET-Permission, but it did not work either.
Here the code:
public class MainActivity extends ActionBarActivity implements RecognitionListener
{
private SpeechRecognizer speechRecognizer;
public void onReadyForSpeech(Bundle params)
{
AddLog("onReadyForSpeech called.");
}
public void onBeginningOfSpeech()
{
AddLog("onBeginningOfSpeech called.");
}
public void onRmsChanged(float rmsdB)
{
AddLog("onRmsChanged called.");
}
public void onBufferReceived(byte[] buffer)
{
AddLog("onBufferReceived called.");
}
public void onEndOfSpeech()
{
AddLog("onEndOfSpeech called.");
}
public void onError(int error)
{
AddLog(String.format("onError called with id: %d.", error));
}
public void onResults(Bundle results)
{
String str = new String();
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for(int i = 0; i < data.size(); i++)
{
str += data.get(i);
}
final String strAnswer = str;
AddLog(String.format("Answer is %s", strAnswer));
}
public void onPartialResults(Bundle psrtialResults)
{
AddLog("onPartialResults called.");
}
public void onEvent(int eventType, Bundle params)
{
AddLog("onEvent called.");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(this);
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
public PlaceholderFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public void AddLog(final String text)
{
TextView txtLogView = (TextView) findViewById(R.id.textViewLog);
if (txtLogView != null)
{
txtLogView.append(text + "\n");
}
}
// Only for test
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK)
{
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
AddLog(matches.get(0));
}
super.onActivityResult(requestCode, resultCode, data);
}
public void Start(View view)
{
AddLog("Start pressed.");
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
// Only for test
//startActivityForResult(intent, 1);
speechRecognizer.startListening(intent);
AddLog("startListening called.");
}
}
I solved it by myself. The problem was, that the language pack for US had an update. I had to load it by hand (in the language settings of my mobile). After that the error ERROR_NETWORK disappeared.
I have a trouble with getting Activity(Nullpointerexception) after that I have rotate screen and received callback from AsyncTask to update my views of the fragment. If I wont change orientation then everything is OK(but not all the time, sometimes this bug appears)
My main activity:
public class MainActivity extends SherlockFragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pager_layout);
fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(this);
session = new SessionManager(getApplicationContext());
if (session.isAuthorizated()) {
disableTabs();
FragmentTransaction ft = fm.beginTransaction();
if (session.termsAndConditions()) {
ft.replace(android.R.id.content, new TermsAndConditionsFragment(), "terms-and-conditions").commit();
}
}
} else {
enableTabs();
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(actionBar.newTab().setText("Log in"), LoginFragment.class, null);
mTabsAdapter.addTab(actionBar.newTab().setText("Calculator"), CalculatorFragment.class, null);
}
}
That`s my fragment:
public class TermsAndConditionsFragment extends SherlockFragment implements OnClickListener, OnTouchListener, OnEditorActionListener, ValueSelectedListener, AsyncUpdateViewsListener {
private static final String TAG = "TermsAndConditionsFragment";
private TermsAndConditionsManager termsAndConditionsM;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prepareData();
}
public void prepareData() {
if (getSherlockActivity() == null)
Log.d(TAG, "Activity is null");
termsAndConditionsM = new TermsAndConditionsManager(getSherlockActivity().getApplicationContext());
termsAndConditions = termsAndConditionsM.getTermsAndConditions();
...
// some stuff
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = init(inflater, container);
return rootView;
}
private View init(LayoutInflater inflater, ViewGroup container) {
rootView = inflater.inflate(R.layout.fragment_terms_and_conditions, container, false);
//bla bla bla
return rootView;
}
public void updateTermsAndConditionsView() {
//update views here
}
#Override
public void onClick(View v) {
ft = fm.beginTransaction();
switch (v.getId()) {
case R.id.etHowMuch:
d = NumberPaymentsPickerFragment.newInstance(getSherlockActivity(), Integer.valueOf(howMuch.replace("£", "")), 0);
d.setValueSelectedListener(this);
d.show(getFragmentManager(), Const.HOW_MUCH);
break;
}
}
#Override
public void onValueSelected() {
Bundle args = new Bundle();
...
ExecuteServerTaskBackground task = new ExecuteServerTaskBackground(getSherlockActivity());
task.setAsyncUpdateViewsListener(this);
task.action = ServerAPI.GET_TERMS_AND_CONDITIONS;
task.args = args;
task.execute();
}
#Override
public void onUpdateViews() {
prepareData();
updateTermsAndConditionsView();
}
}
My AsyncTask with callback:
public class ExecuteServerTaskBackground extends AsyncTask<Void, Void, Void> {
private static final String TAG = "ExecuteServerTaskBackground";
Activity mActivity;
Context mContext;
private AsyncUpdateViewsListener callback;
public ExecuteServerTaskBackground(Activity activity) {
this.mActivity = activity;
this.mContext = activity.getApplicationContext();
}
public void setAsyncUpdateViewsListener(AsyncUpdateViewsListener listener) {
callback = listener;
}
#Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(mContext);
if (!args.isEmpty())
msg = server.serverRequest(action, args);
else
msg = server.serverRequest(action, null);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
callback.onUpdateViews();
}
}
Why does it behave so? How can I get activity correctly if I change orientation.
EDIT:
As I understand correctly nullpointer appears after orientation changed and asynctask executed due to wrong reference between asyctask and Activity. Recreated activity doesnt have this reference thats why when I receive callback I use wrong activity reference which isn`t exist anymore. But how can I save current activity reference?
EDIT:
I have decided to try realize my task throughout Service and that`s what I have done.
Activity:
public class MainFragment extends Fragment implements ServiceExecutorListener, OnClickListener {
private static final String TAG = MainFragment.class.getName();
Button btnSend, btnCheck;
TextView serviceStatus;
Intent intent;
Boolean bound = false;
ServiceConnection sConn;
RESTService service;
ProgressDialog pd = new ProgressDialog();
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
intent = new Intent(getActivity(), RESTService.class);
getActivity().startService(intent);
sConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(TAG, "MainFragment onServiceConnected");
service = ((RESTService.MyBinder) binder).getService();
service.registerListener(MainFragment.this);
if (service.taskIsDone())
serviceStatus.setText(service.getResult());
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "MainFragment onServiceDisconnected");
bound = false;
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
serviceStatus = (TextView) rootView.findViewById(R.id.tvServiceStatusValue);
btnSend = (Button) rootView.findViewById(R.id.btnSend);
btnCheck = (Button) rootView.findViewById(R.id.btnCheck);
btnSend.setOnClickListener(this);
btnCheck.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSend:
pd.show(getFragmentManager(), "ProgressDialog");
service.run(7);
service.run(2);
service.run(4);
break;
case R.id.btnCheck:
if (service != null)
serviceStatus.setText(String.valueOf(service.taskIsDone()) + service.getTasksCount());
break;
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "Bind service");
getActivity().bindService(intent, sConn, 0);
}
#Override
public void onPause() {
super.onDestroy();
Log.d(TAG, "onDestroy: Unbind service");
if (!bound)
return;
getActivity().unbindService(sConn);
service.unregisterListener(this);
bound = false;
}
#Override
public void onComplete(String result) {
Log.d(TAG, "Task Completed");
pd.dismiss();
serviceStatus.setText(result);
}
}
Dialog:
public class ProgressDialog extends DialogFragment implements OnClickListener {
final String TAG = ProgressDialog.class.getName();
public Dialog onCreateDialog(Bundle savedInstanceState) {
setRetainInstance(true);
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle("Title!")
.setPositiveButton(R.string.yes, this)
.setNegativeButton(R.string.no, this)
.setNeutralButton(R.string.maybe, this)
.setCancelable(false)
.setMessage(R.string.message_text)
.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
return adb.create();
}
public void onClick(DialogInterface dialog, int which) {
int i = 0;
switch (which) {
case Dialog.BUTTON_POSITIVE:
i = R.string.yes;
break;
case Dialog.BUTTON_NEGATIVE:
i = R.string.no;
break;
case Dialog.BUTTON_NEUTRAL:
i = R.string.maybe;
break;
}
if (i > 0)
Log.d(TAG, "Dialog 2: " + getResources().getString(i));
}
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "Dialog 2: onDismiss");
// Fix to avoid simple dialog dismiss in orientation change
if ((getDialog() != null) && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
Log.d(TAG, "Dialog 2: onCancel");
}
}
Service:
public class RESTService extends Service {
final String TAG = RESTService.class.getName();
MyBinder binder = new MyBinder();
ArrayList<ServiceExecutorListener> listeners = new ArrayList<ServiceExecutorListener>();
Handler h = new Handler();
RequestManager mRequest;
ExecutorService es;
Object obj;
int time;
StringBuilder builder;
String result = null;
public void onCreate() {
super.onCreate();
Log.d(TAG, "RESTService onCreate");
es = Executors.newFixedThreadPool(1);
obj = new Object();
builder = new StringBuilder();
}
public void run(int time) {
RunRequest rr = new RunRequest(time);
es.execute(rr);
}
class RunRequest implements Runnable {
int time;
public RunRequest(int time) {
this.time = time;
Log.d(TAG, "RunRequest create");
}
public void run() {
Log.d(TAG, "RunRequest start, time = " + time);
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Log.d(TAG, "RunRequest obj = " + obj.getClass());
} catch (NullPointerException e) {
Log.d(TAG, "RunRequest error, null pointer");
}
builder.append("result " + time + ", ");
result = builder.toString();
sendCallback();
}
}
private void sendCallback() {
h.post(new Runnable() {
#Override
public void run() {
for (ServiceExecutorListener listener : listeners)
listener.onComplete();
}
});
}
public boolean taskIsDone() {
if (result != null)
return true;
return false;
}
public String getResult() {
return result;
}
public void registerListener(ServiceExecutorListener listener) {
listeners.add(listener);
}
public void unregisterListener(ServiceExecutorListener listener) {
listeners.remove(listener);
}
public IBinder onBind(Intent intent) {
Log.d(TAG, "RESTService onBind");
return binder;
}
public boolean onUnbind(Intent intent) {
Log.d(TAG, "RESTService onUnbind");
return true;
}
public class MyBinder extends Binder {
public RESTService getService() {
return RESTService.this;
}
}
}
As you mention in your edit, the current Activity is destroyed and recreated on orientation change.
But how can I save current activity reference?
You shouldn't. The previous Activity is no longer valid. This will not only cause NPEs but also memory leaks because the AsyncTask might hold the reference to old Activity, maybe forever.
Solution is to use Loaders.