[Q] Sending GPS location via IOIO - Android Q&A, Help & Troubleshooting

Hi everyone
I'm fairly sure this is the right place to put this, but please correct me if I'm wrong.
I'm trying to create an app that take GPS coordinates from the inbuilt system and output it via an IOIO board (just a board that allows the phone to have digital and analogue output) so that it can be transmitted via a separate module to a receiver. The system will then be used to track a balloon.
I made some headway, I can send "Hello World" easily, but simply can't make the LocationManager work for me as using that just stops everything from working. My Java skills leave a lot to be desired, so I was hoping someone could check over my code and look for a fundamental mistake. The problem appears LocationUpdateHandler class, as relying on that to generate the 'stuff' variable simply halts the entire program.
It is based on two pieces of sample code that came with the IOIO board, but the GPS part is my own.
Code:
package ioio.examples.hello;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ToggleButton;
import ioio.lib.api.Uart;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
/**
* This is the main activity of the HelloIOIO example application.
*
* It displays a toggle button on the screen, which enables control of the
* on-board LED. This example shows a very simple usage of the IOIO, by using
* the {@link IOIOActivity} class. For a more advanced use case, see the
* HelloIOIOPower example.
*/
public class MainActivity extends IOIOActivity {
private ToggleButton button_;
private LocationManager locationManager;
String provider;
String stuff;
/**
* Called when the activity is first created. Here we normally initialize
* our GUI.
*/
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button_ = (ToggleButton) findViewById(R.id.button);
//Sets up the location manager and listener. I feel this section is the root of my problems
LocationListener locationListener = new LocationUpdateHandler();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, new LocationUpdateHandler());
}
//Should, in theory, set the global variable 'stuff' to be the location of the phone stored as a string
public class LocationUpdateHandler implements LocationListener {
public void onLocationChanged(Location loc) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
stuff = Double.toString(lat) + "$" + Double.toString(lng) + "&";
}
[user=439709]@override[/user]
public void onProviderDisabled(String provider) {}
[user=439709]@override[/user]
public void onProviderEnabled(String provider) {}
[user=439709]@override[/user]
public void onStatusChanged(String provider, int status,
Bundle extras) {}
}
/**
* This is the thread on which all the IOIO activity happens. It will be run
* every time the application is resumed and aborted when it is paused. The
* method setup() will be called right after a connection with the IOIO has
* been established (which might happen several times!). Then, loop() will
* be called repetitively until the IOIO gets disconnected.
*/
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
Uart uart;
OutputStream outGPS;
/**
* Called every time a connection with IOIO has been established.
* Typically used to open pins.
*
* [user=948141]@Throw[/user]s ConnectionLostException
* When IOIO connection is lost.
*
* [user=690402]@see[/user] ioio.lib.util.AbstractIOIOActivity.IOIOThread#setup()
*/
[user=439709]@override[/user]
public void setup() throws ConnectionLostException {
led_ = ioio_.openDigitalOutput(0, true);
uart = ioio_.openUart(3,4, 9600, Uart.Parity.NONE, Uart.StopBits.ONE);
outGPS = uart.getOutputStream();
}
public void loop() throws ConnectionLostException {
led_.write(!button_.isChecked());
byte[] GPSCoordinate = null;
//If I set stuff to "Hello World" here the IOIO board succesfully transmits hello world
try {
GPSCoordinate = stuff.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outGPS.write(GPSCoordinate);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
[user=439709]@override[/user]
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Thank you for your help,
Spanners.

and sorry about the code dump, but I think pretty much all of the code is important to understand the program.
Thanks.

Related

[Q] Linking Strings between Activities and WebViews

Hello XDA,
So I've not found anyone properly discussing this. If they do, please link me to the page and don't flame
I've been making an app for my school and so far, I've been doing alright. But now I have run into a problem which seems to be very hard to solve for me alone.
Namely, I have an EditText and a Button in one Activity and a WebView as a different Activity.
I'm trying to get the EditText String into the WebView URL (String being variable, Button initiating the WebView), but get a lot of errors, some not even related to that.
I would really appreciate it if someone could have a look at the code and help me with this
MyWebView.java:
Code:
package bas.sie.Antonius;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebView extends Activity {
WebView mWebView;
EditText mEtxtStudentNum;
static String StudentNumFromHome = bas.sie.Antonius.Home.StudentNum;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl("http://carmelcollegegouda.nl/site_ant/roosters/standaardroosters/Lee1_" + StudentNumFromHome + ".htm");
}
}
Home.java (Homescreen):
Code:
package bas.sie.Antonius;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Home extends Activity {
Button mBtnStSchedule;
static EditText mEtxtStudentNum;
static final String StudentNum = mEtxtStudentNum.getText().toString();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.BtnStSchedule);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MyWebView.class);
startActivityForResult(myIntent, 0);
}
});
// TODO Auto-generated method stub
}
}
AntoniusActivity.java (Main):
Code:
package bas.sie.Antonius;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TabHost;
public class AntoniusActivity extends TabActivity {
WebView mWebView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Home.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("home").setIndicator("Home",
res.getDrawable(R.drawable.ic_tab_home))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, External.class);
spec = tabHost.newTabSpec("external").setIndicator("External",
res.getDrawable(R.drawable.ic_tab_external))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Contact.class);
spec = tabHost.newTabSpec("contact").setIndicator("Contact",
res.getDrawable(R.drawable.ic_tab_contact))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(2);
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
In AntoniusActivity, the private class HelloWebViewClient is underlined with yellow (never used), specifically the bit "HelloWebViewClient".
It's also throwing FC's at startup, and errors in LogCat, but I'll post those later on, as it's 10.30 PM here, and school goes on
Thanks in advance,
bassie1995
No suggestions yet?
How you doin'? Greetings from my GT-I9000!

Q> HELP Connection andrdoid to pc Programming

this is my server code
i am getting an error on my android phone when i clicked the device address
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class ServerSide {
//private static LocalDevice localDevice;
static LocalDevice localDevice;
DiscoveryAgent agent;
private void startServer() throws IOException{
UUID uuid = new UUID("112f8dbf1e46442292b6796539467bc9", false);
String connectionString = "btspp://localhost:" + uuid
+";name=SampleSPPServer";
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
System.out.println("\nServer Started. Waiting for clients to
connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address:
"+dev.getBluetoothAddress());
System.out.println("Remote device name:
"+dev.getFriendlyName(true));
}
public static void main(String[] args) {
//display local device address and name
try{
localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
try{
ServerSide sampleSPPServer=new ServerSide();
sampleSPPServer.startServer();
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
}
}
**************************************************************
and this is my client(android) code
package client.side;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ClientSideActivity extends Activity {
int REQUEST_ENABLE_BT = 0;
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mArrayAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button)findViewById(R.id.button1);
Button btn2 = (Button)findViewById(R.id.button2);
final ListView lv1 = (ListView)findViewById(R.id.listView1);
final TextView out = (TextView)findViewById(R.id.textView1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mArrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
}
out.setText(null);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
out.setText("Paired Devices");
Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
mArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
}
lv1.setAdapter(mArrayAdapter);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
out.setText("Discovered Devices");
mBluetoothAdapter.startDiscovery();
Toast msg = Toast.makeText(ClientSideActivity.this, "Discovering
Devices please wait.", Toast.LENGTH_LONG);
msg.show();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show
in a ListView
mArrayAdapter.add(device.getAddress());
} }
};
// Register the BroadcastReceiver
IntentFilter filter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister
during onDestroy
}
});
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,long id)
{
out.setText(arg0.getItemAtPosition(position).toString());
BluetoothDevice remoteDev = (BluetoothDevice)
arg0.getItemAtPosition(position);
ConnectThread conDev = new ConnectThread(remoteDev);
conDev.start();
}
});
}
public class ConnectThread extends Thread {
private final UUID MY_UUID =
UUID.fromString("112f8dbf1e46442292b6796539467bc9");
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to
mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
try {
// MY_UUID is the app's UUID string, also used by the
server code
tmp =
device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the
connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will
block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate
thread)
}
/** Will cancel an in-progress connection, and close the
socket */
}
}

activity doesn't wait untill alertdialog completes

Note: Text content in the code blocks is automatically word-wrapped
package com.connection.phonedetails;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class Test extends Activity {
private static final int REQUEST_CODE = 10;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert);
DatabaseHandler db = new DatabaseHandler(this);
Intent intent = new Intent(this,AlertDialogExample.class);
startActivityForResult(intent,REQUEST_CODE);
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("TYPE");
Toast.makeText(getApplicationContext(),"Your sim type iss POST paidddddddddd", Toast.LENGTH_LONG).show();
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(),"Your sim type iss PREEEEE paidddddddddd", Toast.LENGTH_LONG).show();
}
}
}
}
this is alert dialog activity.
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
package com.connection.phonedetails;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AlertDialogExample extends Activity {
// this context will use when we work with Alert Dialog
final Context context = this;
// just for test, when we click this button, we will see the alert dialog.
private Button button;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert);
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Select Your SIM Type"); //Set Alert dialog title here
//alert.setMessage("Enter your Name Here"); //Message here
alert.setPositiveButton("Post Paid", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// String value = input.getText().toString();
// Do something with value!
//You will get input data in this variable.
Toast.makeText(getApplicationContext(),"Post Paid", Toast.LENGTH_LONG).show();
//db.addContact(new SimDetails( telephonyManager.getSimSerialNumber(), telephonyManager.getNetworkOperatorName(),"Post"));
Intent returnIntent = new Intent();
returnIntent.putExtra("TYPE","POST Paid");
setResult(RESULT_OK,returnIntent);
finish();
}
});
alert.setNegativeButton("Pre Paid", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(getApplicationContext(),"Pre Paid", Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("TYPE","PRE Paid");
setResult(RESULT_CANCELED,returnIntent);
finish();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
}
/*
@override
public void finish() {
Intent data = new Intent();
// Return some hard-coded values
data.putExtra("TYPE", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
setResult(RESULT_OK, data);
super.finish();
}*/
}
this is working fine.Anyway if added the below two line end Oncreate method of the main activity it doesn't wait untill the alert dialog finishes.it goes to contact activity .So i don't have chance to select option from alert dialog.how to avoid this situation?
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
Intent contact = new Intent(getApplicationContext(),Contacts.class);
startActivity(contact);

First App dev. help

Hello I'm Trying to learn my firsy app (Flash Lifght app) ..
I understand that i need to give app permissions etc.
Can some one expaine me how do i need to do that when im opening new project.
I what is code or the file i need to paste the code..
Sorry for bad english and thanks for helping!
natan.p said:
Hello I'm Trying to learn my firsy app (Flash Lifght app) ..
I understand that i need to give app permissions etc.
Can some one expaine me how do i need to do that when im opening new project.
I what is code or the file i need to paste the code..
Sorry for bad english and thanks for helping!
Click to expand...
Click to collapse
You need to set the permissions in the AndroidManifest.xml file add a uses permission and under that class an android:name= *camera*
Regards
MasterAwesome
MasterAwesome said:
You need to set the permissions in the AndroidManifest.xml file add a uses permission and under that class an android:name= *camera*
Regards
MasterAwesome
Click to expand...
Click to collapse
I have an error i found tutorial how create flash light app i cop all codes ti manifest etc files but i have error with the java file........
the error: The public type FlashlightActivity must be defined in its own file.
the code: Press Control + F and search this line public class FlashlightActivity extends Activity {
PHP:
package com.natan.flashlight;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.widget.ToggleButton;
/**
* @author Prabu
* July 30 2013
* @version 1.0
*
*/
public class FlashlightActivity extends Activity { // <--------------------------------------- There are the error..
private Camera camera;
private ToggleButton button;
private final Context context = this;
//@see android.app.Activity#onStop()
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.flashlight);
button = (ToggleButton) findViewById(R.id.togglebutton);
final PackageManager pm = context.getPackageManager();
if(!isCameraSupported(pm)){
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera");
alertDialog.setMessage("The device's doesn't support camera.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's doesn't support camera.");
}
});
alertDialog.show();
}
camera = Camera.open();
}
public void onToggleClicked(View view) {
PackageManager pm=context.getPackageManager();
final Parameters p = camera.getParameters();
if(isFlashSupported(pm)){
boolean on = ((ToggleButton) view).isChecked();
if (on) {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
} else {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
}
}else{
button.setChecked(false);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera Flash");
alertDialog.setMessage("The device's camera doesn't support flash.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's camera doesn't support flash.");
}
});
alertDialog.show();
}
}
/**
* @param packageManager
* @return true <b>if the device support camera flash</b><br/>
* false <b>if the device doesn't support camera flash</b>
*/
private boolean isFlashSupported(PackageManager packageManager){
// if device support camera flash?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
return true;
}
return false;
}
/**
* @param packageManager
* @return true <b>if the device support camera</b><br/>
* false <b>if the device doesn't support camera</b>
*/
private boolean isCameraSupported(PackageManager packageManager){
// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
}
return false;
}
}
public class MainActivity extends ActionBarActivity {
@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();
}
}
@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;
}
}
}
natan.p said:
I have an error i found tutorial how create flash light app i cop all codes ti manifest etc files but i have error with the java file........
the error: The public type FlashlightActivity must be defined in its own file.
the code: Press Control + F and search this line public class FlashlightActivity extends Activity {
PHP:
package com.natan.flashlight;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.widget.ToggleButton;
/**
* @author Prabu
* July 30 2013
* @version 1.0
*
*/
public class FlashlightActivity extends Activity { // <--------------------------------------- There are the error..
private Camera camera;
private ToggleButton button;
private final Context context = this;
//@see android.app.Activity#onStop()
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.flashlight);
button = (ToggleButton) findViewById(R.id.togglebutton);
final PackageManager pm = context.getPackageManager();
if(!isCameraSupported(pm)){
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera");
alertDialog.setMessage("The device's doesn't support camera.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's doesn't support camera.");
}
});
alertDialog.show();
}
camera = Camera.open();
}
public void onToggleClicked(View view) {
PackageManager pm=context.getPackageManager();
final Parameters p = camera.getParameters();
if(isFlashSupported(pm)){
boolean on = ((ToggleButton) view).isChecked();
if (on) {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
} else {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
}
}else{
button.setChecked(false);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera Flash");
alertDialog.setMessage("The device's camera doesn't support flash.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's camera doesn't support flash.");
}
});
alertDialog.show();
}
}
/**
* @param packageManager
* @return true <b>if the device support camera flash</b><br/>
* false <b>if the device doesn't support camera flash</b>
*/
private boolean isFlashSupported(PackageManager packageManager){
// if device support camera flash?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
return true;
}
return false;
}
/**
* @param packageManager
* @return true <b>if the device support camera</b><br/>
* false <b>if the device doesn't support camera</b>
*/
private boolean isCameraSupported(PackageManager packageManager){
// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
}
return false;
}
}
public class MainActivity extends ActionBarActivity {
@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();
}
}
@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;
}
}
}
Click to expand...
Click to collapse
You can't have 2 public class in the same file.. Create a new class
Regards
MasterAwesome
MasterAwesome said:
You can't have 2 public class in the same file.. Create a new class
Regards
MasterAwesome
Click to expand...
Click to collapse
What you mean two public classes?
Sent from my Nexus 5 using Tapatalk
natan.p said:
What you mean two public classes?
Sent from my Nexus 5 using Tapatalk
Click to expand...
Click to collapse
Main activity and flashlight.. Just remove the public for flashlight
Regards
MasterAwesome

hELP- .getSpeed();

HELLO , HOW CAN I FIND SPEED AND DISTANCE TRAVELED? HOW CAN I MARK THE DISPLACEMENT ON THE MAP ?
….
therricately I could find it that way with this function..... but it's okay, it's ignored.
Code:
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
float v= location.getSpeed();
}
api 19
Code:
package com.example.mps;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
public class MapsActivity extends FragmentActivity
implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// TODO: Before enabling the My Location layer, you must request
// location permission from the user. This sample does not include
// a request for location permission.
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}

Categories

Resources