In Android Project, Single File has R errors [duplicate] - java

This question already has answers here:
Why are my resources suddenly unresolved in my Android project?
(2 answers)
Closed 9 years ago.
I have a project working perfectly on Windows in Eclipse. As most of my work is now on a Mac at my job, I'm switching over to Eclipse for Mac.
I have fixed all of the build path errors across the project, and all that remains are the "this_xml_name cannot be resolved or is not a field", in theory resulting in an error when building my R file.
However, this is the first I have encountered this problem appearing only in a single file, and it is not just id's or layouts. It happens in R.layout, R.id, R.menu, and R.drawable. All other references throughout my project are perfectly fine, only errors are found at each of the R. references in the linked file.
MapActivity.java
package com.example.android;
import java.util.Timer;
import java.util.TimerTask;
import android.R;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends FragmentActivity {
FragmentActivity activity = this;
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
protected GoogleMap mMap;
String locAddr;
String locName;
Double locLongitude;
Double locLatitude;
final Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
locAddr = extras.getString("address");
locName = extras.getString("name");
locLongitude = extras.getDouble("longitude");
locLatitude = extras.getDouble("latitude");
activity.setTitle(locName);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable()
{
public void run()
{
LatLng coordinates = new LatLng(locLatitude, locLongitude);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 14.0f));
Marker marker = mMap.addMarker(new MarkerOptions()
.position(coordinates)
.title(locName)
.snippet(locAddr)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker)));
marker.showInfoWindow();
/*mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(MapActivity.this, DetailsActivity.class);
intent.putExtra("userkey", "MattCoker");
intent.putExtra("geolat", "29.7530");
intent.putExtra("geolong", "geozip");
intent.putExtra("clientid", "0");
intent.putExtra("siteid", "0");
startActivity(intent);
}
});*/
}
});
}
}, 3000);
} else {
Toast.makeText(activity, "Something went wrong displaying this location!", Toast.LENGTH_LONG).show();
}
}
}
else {
setContentView(R.layout.no_available_maps);
}
//Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, activity, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(activity, "Can't connect to Google Play Services", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag = null;
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
#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);
// Associate searchable configuration with the SearchView
/*SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));*/
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int selectedMenuItem = item.getItemId();
if (selectedMenuItem == R.id.action_settings) {
Intent settingsIntent = new Intent(activity, SettingsActivity.class);
startActivity(settingsIntent);
return true;
} else if (selectedMenuItem == R.id.send_feedback) {
Intent sendFeedback = new Intent(android.content.Intent.ACTION_SEND);
sendFeedback.setType("message/rfc822");
sendFeedback.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"usersupport#example.com"});
sendFeedback.putExtra(android.content.Intent.EXTRA_SUBJECT, "Feedback on example...");
startActivity(Intent.createChooser(sendFeedback, "Send Email"));
//TODO: Create Feedback Activity to send email
return true;
}
return false;
}
}

If you have errors in your resource files R.java will not be generated. Fix those errors and clean and build.
Looking at the code you have
import android.R;
Replace it with
import com.example.android.R;

Related

Insert class for scanning ble devices into a Service, to make it work in background in Android

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.

How to create a Login task in OnClickListener?

How to create a task with OnClickListener???
I Tryed with two methods (AsyncTask & Runnable/Thread):
I have test the AsyncTask Method:
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask(getActivity()).execute("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
}
});
return rootView;
}
}
}
class LoginTask extends AsyncTask<String, Integer, Long> {
private FragmentActivity activity;
public LoginTask(FragmentActivity activity) {
this.activity = activity;
}
protected Long doInBackground(String... urls) {
try{
URL oracle = new URL(urls[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(activity, "Failed", Toast.LENGTH_LONG).show();
}
return (long) 0;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
and i have tested a Runnable Method
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Runnable run = new Runnable() {
#Override
public void run() {
try{
URL oracle = new URL("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(getActivity(), "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
};
Thread t = new Thread(run);
t.start();
}
});
return rootView;
}
}
}
but this two Methods dosent works.
I noticed, that you called Toast.makeText(...).show() from doInBackground(). It will not work. I wish I could write this as a comment, but I don't have enough reputation...
Also, URLEncoder.encode() is deprecated. Try encode with encoding as the second argument.
And in the end, usually, network operations are implemented using HttpUrlConnection or DefaultHttpClient (the first is preferable). Here you can find a code snippet.

Speech recognition input screen same for all in android

I have a problem with my android app with speech recognition.My problem is that I want to show the same speech recognition input screen as is shown from the jellybean keyboard. If I invoke the Speech recognition intent from code, it does not keep listening and stops prematurely.
There must be a simple way to do this, but I can't find it.
here is my code
package com.bsdcservices.recognitiontest;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String TAG = "RecognitionTest";
private final int SPEECHRECOGNITION_RESULTCODE = 0;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.textbox);
Button recognize = (Button) findViewById(R.id.recognize);
recognize.setOnClickListener(buttonClickListener);
}
public OnClickListener buttonClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
startSpeechRecognitionActivity();
}
};
#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;
}
void startSpeechRecognitionActivity(){
// MyApplication.speechRecognitionActive = true;
// main.startSpeechRecognizer(TABSPEAK);
try{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().toString());
startActivityForResult(intent, SPEECHRECOGNITION_RESULTCODE);
} catch (ActivityNotFoundException error) {
Toast.makeText(getBaseContext(), "Speech recognition is not supported by your device" , Toast.LENGTH_LONG).show();
} catch( RuntimeException error ) {
Toast.makeText(getBaseContext(), error.getMessage() , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try
{
if (requestCode == SPEECHRECOGNITION_RESULTCODE) {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
editText.append(text.get(0));
}
}
} catch( RuntimeException error ) {
Toast.makeText(getBaseContext(), error.getMessage() , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
}

MediaRecorder.getMaxAmplitude returns always 0

I'm new in Java and my English isn't the best too.
I want to write an app which meassures the Amplitude of a record. The app works except for the fact, that the amplitude is always 0. I have now read several websites, but didn't found an answer. I would be realy glad if somebody helps me.
package com.example.volumeswitcher;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnInfoListener {
WindowManager.LayoutParams lp;
Button messe;
MediaRecorder micro;
int ampli;
TextView tv1;
TextView tv2;
String amplitext;
Vibrator vibr;
Environment e;
String mFileName;
int i;
Boolean recording;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(R.layout.activity_main);
micro = null;
}
#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;
}
public void onBtnClicked(View v) {
startRecording();
}
protected void startRecording() {
if (micro == null){
i ++;
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecord"+ i +".3gp";
micro = new MediaRecorder();
micro.setAudioSource(MediaRecorder.AudioSource.MIC);
micro.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
micro.setOutputFile(mFileName);
micro.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
micro.setMaxDuration(2000);
try {
micro.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "IllegalStateException called", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "prepare() failed", Toast.LENGTH_LONG).show();
}
micro.start();
micro.getMaxAmplitude();
ampli = micro.getMaxAmplitude();
tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText(Integer.toString(ampli));
}
micro.setOnInfoListener(new OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
micro.stop();
recording = false;
micro.release();
micro = null;
}
}
});
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
}
}
Thank you for your help!
I have the same issue, and oddly enough if you change the time interval when your trying to get the max amplitude, to greater then one second, it works normally, but i don't know what's causing it ...

Using reflection in Android for backwards compatibility

I was reading over at the Android development website about using reflections. But I'm really not grasping how to use it. I need this Java file to run on a 1.5 (SDK3) device but just ignore the new code and it works fine on a 2.0 (SDK5) or later phone. I have this Activity (posted below) and it's a simple webview. However, I want to have geolocation enabled (even if it is only for 2.0 and later phones), since these APIs weren't introduced until SDK 5, and I would like the webview to be able to, at the very least, to load on a 1.5 phone rather than just crashing. How do I take my code and set it up using reflections?
package com.my.app;
import com.facebook.android.R;
//NEEDS TO BE IGNORED**********************************************************
import android.webkit.GeolocationPermissions;
import android.webkit.GeolocationPermissions.Callback;
//END**************************************************************************
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
//GeolocationPermissionsCallback NEEDS TO BE IGNORED**********************************************************
public class Places extends Activity implements GeolocationPermissions.Callback {
private ProgressDialog progressBar;
public WebView webview;
private static final String TAG = "Main";
String geoWebsiteURL = "http://google.com";
#Override
public void onStart()
{
super.onStart();
CookieSyncManager.getInstance().sync();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new testClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.loadUrl("http://google.com");
progressBar = ProgressDialog.show(Places.this, "", "Loading Page...");
//START GROUP OF CODE THAT NEEDS TO BE IGNORED************************************************************
webview.getSettings().setGeolocationEnabled(true);
GeoClient geo = new GeoClient();
webview.setWebChromeClient(geo);
}
public void invoke(String origin, boolean allow, boolean remember) {
}
final class GeoClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
//END OF CODE THAT NEEDS TO BE IGNORED************************************************
}
private class testClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
if (url.startsWith("mailto:") || url.startsWith("geo:") ||
url.startsWith("tel:")) {
Intent intent = new Intent
(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
}
}
//What's here????
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
Intent z = new Intent(this, Search.class);
startActivity(z);
}
return super.onKeyDown(keyCode, event);
}
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent m = new Intent(this, Home.class);
startActivity(m);
return true;
case R.id.refresh:
webview.reload();
Toast.makeText(this, "Refreshing...", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void onStop()
{
super.onStop();
CookieSyncManager.getInstance().sync();
}
}
Step #1: Do not implement GeolocationPermissions.Callback on the activity. Use some other object for GeolocationPermissions.Callback, one implemented in a public Java class that you would not load if you are running on older versions of the OS.
Step #2: Read the answers and comments on the question you asked previously, which covers what you need to know for the rest. Notably, you would make GeoClient be a public Java class in its own file, so you can avoid loading it on older versions of the OS. Personally, I like the Stephen C answer, and I demonstrate its use here.

Categories