firsly i want to say i use the 2 Intents i refer in each to change activity between them and i can also move to this class with an intent but when i try to startactivty from this class it crashes .
this is the class where i get the error.
package com.example.wince.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
/**
* Created by Wince on 31.05.2016.
*/
public class RotaGoster extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
final Intent rotaIntent = new Intent(this, com.example.wince.myapplication.Rota.class);
final Intent kayitIntent = new Intent(this, com.example.wince.myapplication.RotaKayit.class);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rota);
String isim = getIntent().getExtras().getString("DB_name");
VeriTabani VT = new VeriTabani(this);
Button Kayit = (Button) findViewById(R.id.button6);
Button Rota = (Button) findViewById(R.id.button7);
int i = 0;
ArrayList<Yer> yerler = new ArrayList<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2);
mapFragment.getMapAsync(this);
yerler.addAll(VT.getAllYer());
for (i = 0; i < yerler.size(); i++) {
if (yerler.get(i).equals(isim)) {
mMap.addMarker(new MarkerOptions().position(new LatLng(VT.getYer(i).getLat(), VT.getYer(i).getLng())).title(i + "'inci nokta"));
}
}
Kayit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(kayitIntent);
finish();
}
});
Rota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(rotaIntent);
finish();
}
});
//dbden verileri çekmek gerek
// db işlemleri ve gösterim burda yapılıcak.
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
}
}
this is the android manifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".RotaKayit"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Rota"></activity>
<activity android:name=".RotaGoster"></activity>
</application>
this is the logcat for error
06-05 15:51:55.032 10275-10275/com.example.wince.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wince.myapplication, PID: 10275
android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.example.wince.myapplication.Rota}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1636)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1430)
at android.app.Activity.startActivityForResult(Activity.java:3532)
at android.app.Activity.startActivityForResult(Activity.java:3493)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at android.app.Activity.startActivity(Activity.java:3735)
at android.app.Activity.startActivity(Activity.java:3703)
at com.example.wince.myapplication.RotaGoster$2.onClick(RotaGoster.java:55)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19274)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
changing the code like this ; putting intent declarations in the oncreate method seems to solve the problem
package com.example.wince.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
/**
* Created by Wince on 31.05.2016.
*/
public class RotaGoster extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rota);
String isim = getIntent().getExtras().getString("DB_name");
VeriTabani VT = new VeriTabani(this);
Button Kayit = (Button) findViewById(R.id.button6);
Button Rota = (Button) findViewById(R.id.button7);
int i = 0;
final Intent rotaIntent = new Intent(this, Rota.class);
final Intent kayitIntent = new Intent(this, RotaKayit.class);
ArrayList<Yer> yerler = new ArrayList<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2);
mapFragment.getMapAsync(this);
yerler.addAll(VT.getAllYer());
for (i = 0; i < yerler.size(); i++) {
if (yerler.get(i).equals(isim)) {
mMap.addMarker(new MarkerOptions().position(new LatLng(VT.getYer(i).getLat(), VT.getYer(i).getLng())).title(i + "'inci nokta"));
}
}
Kayit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(kayitIntent);
finish();
}
});
Rota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(rotaIntent);
finish();
}
});
//dbden verileri çekmek gerek
// db işlemleri ve gösterim burda yapılıcak.
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
}
}
You have a reference to this outside of the instance, so you can only declare the Intents as fields, but you must initialize them in onCreate or later.
They also don't need to be final.
Related
I'm developing an app which can read data from a Bluetooth RFID Reader, but everytime i start the BluetoothActivity (it's a tabbed activity), it always shows a ClassCastException, below is my code..
BluetoothActivity class:
package com.siscaproject.sisca.Activity;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.siscaproject.sisca.Fragment.RegisterFragment;
import com.siscaproject.sisca.Fragment.SearchFragment;
import com.siscaproject.sisca.R;
import com.siscaproject.sisca.Utilities.FamsModel;
import com.siscaproject.sisca.Utilities.TSLBluetoothDeviceActivity;
import com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import com.uk.tsl.rfid.asciiprotocol.responders.LoggerResponder;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class BluetoothActivity extends TSLBluetoothDeviceActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
#BindView(R.id.viewpager_bluetooth) ViewPager mViewPager;
#BindView(R.id.toolbar_bluetooth) Toolbar mToolbar;
#BindView(R.id.tab_bluetooth) TabLayout mTabLayout;
private FamsModel mModel;
public AsciiCommander getCommander(){
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);
AsciiCommander commander = getCommander();
// Add the LoggerResponder - this simply echoes all lines received from the reader to the log
// and passes the line onto the next responder
// This is added first so that no other responder can consume received lines before they are logged.
commander.addResponder(new LoggerResponder());
// Add a synchronous responder to handle synchronous commands
commander.addSynchronousResponder();
}
private void setupViewPager(ViewPager viewPager){
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RegisterFragment(), "REGISTER");
adapter.addFragment(new SearchFragment(), "SEARCH");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_item_reconnect_reader) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bluetooth, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
private ArrayList<String> fragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title ){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
TSLBluetoothDeviceActivity class:
package com.siscaproject.sisca.Utilities;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.siscaproject.sisca.BuildConfig;
import com.uk.tsl.rfid.DeviceListActivity;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import java.util.Timer;
import java.util.TimerTask;
public class TSLBluetoothDeviceActivity extends AppCompatActivity {
// Debugging
private static final String TAG = "TSLBTDeviceActivity";
private static final boolean D = BuildConfig.DEBUG;
// 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;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mDevice = null;
protected AsciiCommander getCommander() {
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Create the AsciiCommander to talk to the reader (if it doesn't already exist)
if (getCommander() == null) {
try {
TSLBluetoothDeviceApplication app = (TSLBluetoothDeviceApplication) getApplication();
AsciiCommander commander = new AsciiCommander(getApplicationContext());
app.setCommander(commander);
} catch (Exception e) {
fatalError("Unable to create AsciiCommander!");
}
}
}
// Terminate the app with the given message
private void fatalError(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
finish();
}
}, 1800);
}
protected void bluetoothNotAvailableError(String message) {
fatalError(message);
}
#Override
public void onStart() {
super.onStart();
// If no other attempt to connect is ongoing try to connect to last used reader
// Note: When returning from the Device List activity
if (mBluetoothAdapter.isEnabled()) {
if (mDevice == null) {
// Attempt to reconnect to the last reader used
Toast.makeText(this, "Reconnecting to last used reader...", Toast.LENGTH_SHORT).show();
getCommander().connect(null);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
#Override
public void onStop() {
super.onStop();
getCommander().disconnect();
mDevice = null;
}
protected void connectToDevice(Intent deviceData, boolean secure) {
Toast.makeText(this.getApplicationContext(), "Connecting...", Toast.LENGTH_LONG).show();
// Get the device MAC address
String address = deviceData.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
mDevice = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
if (mDevice != null) {
getCommander().connect(mDevice);
} else {
if (D) Log.e(TAG, "Unable to obtain BluetoothDevice!");
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (D)
Log.d(TAG, "selectDevice() onActivityResult: " + resultCode + " for request: " + requestCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectToDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectToDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode != Activity.RESULT_OK) {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
bluetoothNotAvailableError("Bluetooth was not enabled\nApplication Quitting...");
}
}
}
public void selectDevice() {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
}
public void disconnectDevice() {
mDevice = null;
getCommander().disconnect();
}
public void reconnectDevice() {
getCommander().connect(null);
}
}
The error log:
11-21 14:47:54.836 18956-18956/com.siscaproject.sisca E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siscaproject.sisca, PID: 18956
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.siscaproject.sisca/com.siscaproject.sisca.Activity.BluetoothActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication
at com.siscaproject.sisca.Activity.BluetoothActivity.getCommander(BluetoothActivity.java:51)
at com.siscaproject.sisca.Utilities.TSLBluetoothDeviceActivity.onCreate(TSLBluetoothDeviceActivity.java:45)
at com.siscaproject.sisca.Activity.BluetoothActivity.onCreate(BluetoothActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5411)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
I've followed this code from an app that works fine, but when I implemented it in my project it always shows this error, I'm not sure what I'm doing wrong.
---EDIT---
TSLBluetoothDeviceApplication class:
package com.siscaproject.sisca.Utilities;
import android.app.Application;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
public class TSLBluetoothDeviceApplication extends Application {
private static AsciiCommander commander = null;
/// Returns the current AsciiCommander
public AsciiCommander getCommander() {
return commander;
}
/// Sets the current AsciiCommander
public void setCommander(AsciiCommander _commander) {
commander = _commander;
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.siscaproject.sisca">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<activity
android:name=".Activity.LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.BluetoothTestActivity"
android:theme="#style/StandardTheme" />
<activity
android:name=".Activity.HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/AppTheme" />
<meta-data
android:name="com.google.android.gms.vision.DEPENDENCIES"
android:value="barcode" />
<activity android:name=".Activity.QRActivity" />
<activity
android:name=".Activity.BluetoothActivity"
android:label="#string/title_activity_bluetooth"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
getApplication() inside an activity returns an object of type Application. In your case you are trying to cast this object into TSLBluetoothDeviceApplication which, as defined by you, is an Activity type class.
As I see, you are trying to call getCommander() which is defined already in your TSL activity class. I assume you want getCommander() method from another class.. Make sure which one is.
public AsciiCommander getCommander(){
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
This method is already inside TSLBluetoothDeviceApplication class.. I don't know what are you trying to achieve by trying to call same method which is already in your current class.
EDIT:
After the edited post, we noticed that the class was properly implemented, just forgot to add
android:name="com.path.to.ApplicationClass" into the Manifestfile under <application/> tag.
I will let the above answer also, because it may help others
Happy coding <3
It's clear that your application class is not used. You need to add it to your xml Application tag like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name="com.siscaproject.sisca.Utilities. TSLBluetoothDeviceApplication"
android:theme="#style/AppTheme"
tools:replace="android:icon">
and the only change is adding android:name="com.siscaproject.sisca.Utilities. TSLBluetoothDeviceApplication" to the Application tag as your customized class.
I want to programing app for data track in background , so I use service .
I want to write a program that monitors all data sent and received by the device, and when the total volume of received or received messages reaches a specified value, the Internet device is turned off.
So I used the following code to monitor the data:
mStartRX = TrafficStats.getTotalRxBytes ();
mStartTX = TrafficStats.getTotalTxBytes ();
And I used the services to work on the background in the background.
To specify the download or upload limit from the user with edittext, I requested this limit in mainactivity and send this value to the service.
The problem is when: When I destroy the program, I will restart the service and get the NULL value and the program crashes.
My application code:
Main Activity :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static Handler mHandler = new Handler();
public static long UPP;
public static long DLL;
Button startService,stopService;
public Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (FirstService.mStartRX == TrafficStats.UNSUPPORTED || FirstService.mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
startService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText UP = (EditText) findViewById(R.id.UP);
String UPPP = UP.getText().toString();
UPP=Long.parseLong(UPPP);
EditText DL = (EditText) findViewById(R.id.DL);
String DLLL = DL.getText().toString();
DLL=Long.parseLong(DLLL);
Intent intent = new Intent(getApplicationContext(), FirstService.class);
String myString = DLLL;
intent.putExtra("StringName", myString);
startService(intent);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(),FirstService.class));
}
});
}
public final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
RX.setText(Long.toString(FirstService.rxBytes));
TX.setText(Long.toString(FirstService.txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
Service :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.widget.TextView;
import android.widget.Toast;
public class FirstService extends Service{
public static long mStartRX ;
public static long mStartTX ;
public static long rxBytes ;
public static long txBytes ;
public long dl=MainActivity.DLL;
Context context=this;
private final Runnable mRunnable = new Runnable() {
public void run() {
rxBytes = (TrafficStats.getTotalRxBytes()- mStartRX)/1048576;
txBytes = (TrafficStats.getTotalTxBytes()- mStartTX)/1048576;
if (rxBytes==2) {
stopService(new Intent(getBaseContext(),FirstService.class));
Intent i = new Intent(context,MainActivity.class);
context.startActivity(i);
// WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// wifiManager.setWifiEnabled(false);
//معرفی توست برای نمایش یک پیام کوتاه به کاربر در هنگام خاموش کردن وای فای
Toast.makeText(FirstService.this, "هشدار", Toast.LENGTH_LONG).show();
}
mHandler.postDelayed(mRunnable, 1000);
}
};
private Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"staart",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
mHandler.postDelayed(mRunnable, 1000);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
TrafficStats.clearThreadStatsTag();
Toast.makeText(this,"FirstService Stoped",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
super.onDestroy();
}
}
AndroidManifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.alexandre9009.service">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirstService"
>
</service>
</application>
</manifest>
please help me ...
The problem is with this line
public long dl=MainActivity.DLL;
You're referring to a variable in the Activity, surly when the Activity is destroyed, this variable is no longer in scope, thus you get Null Exception.
You must get this value using the intent.
The other problem is that you can't prevent any service from being killed by the system except foreground services which need to show a notification to the user. But this is not suitable for your situation.
Therefore, the best approach for you is to check whether intent is null or not. If it is not null, you get the value and save it into Preferences or Database or somewhere, if it is null, you retrieve the value from where you stored it before.
Whenever I try to click on a button and switch activities, it always gives me the error and stays on the same activity without doing anything:
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6d42940, error=EGL_SUCCESS
I thought that it was something in my manifest file, but I can't find anything. I've tried changing many things around and inserting different filters and such and nothing solves this problem.
My code is:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.robertmonks.mytestapp" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name="Main_Activity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="Login_Activity"
android:label="#string/title_activity_login_"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name="Register_Activity"
android:label="#string/title_activity_register_"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
</application>
</manifest>
Main_Activity
package com.example.robertmonks.mytestapp;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.app.AlertDialog;
public class Main_Activity extends AppCompatActivity {
android.widget.Button logoutButton;
android.widget.EditText password;
android.widget.EditText username;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login_);
password = (android.widget.EditText) findViewById( R.id.etPassword );
username = (android.widget.EditText) findViewById( R.id.etEmailAddress );
logoutButton = (android.widget.Button) findViewById( R.id.blogin);
logoutButton.setOnClickListener(new android.widget.Button.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.blogin) {
logoutButtonClicked();//move action to new method to keep code clean
}
}
});
}
private void logoutButtonClicked()
{
android.content.Intent loginintent = new android.content.Intent(Main_Activity.this, Login_Activity.class);
Main_Activity.this.startActivity(loginintent);
android.util.Log.d("Logout", "Attempted");
}
}
Login_Activity
package com.example.robertmonks.mytestapp;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.app.AlertDialog;
public class Login_Activity extends AppCompatActivity {
android.widget.Button loginButton;
android.widget.Button registerButton;
android.widget.EditText password;
android.widget.EditText username;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login_);
password = (android.widget.EditText) findViewById( R.id.etPassword );
username = (android.widget.EditText) findViewById( R.id.etEmailAddress );
loginButton = (android.widget.Button) findViewById( R.id.blogin);
registerButton = (android.widget.Button) findViewById( R.id.bregister);
loginButton.setOnClickListener(new android.widget.Button.OnClickListener(){
#Override
public void onClick(View v) {
if(v.getId() == R.id.blogin) {
loginButtonClicked();//move action to new method to keep code clean
}
if(v.getId() == R.id.bregister) {
registerButtonClicked();
}
}
});
registerButton.setOnClickListener(new android.widget.Button.OnClickListener(){
#Override
public void onClick(View v) {
if(v.getId() == R.id.bregister) {
registerButtonClicked();
}
}
});
}
private void loginButtonClicked()
{
//startActivity(Main_Activity.class);
android.util.Log.d("Login", "Attempted");
}
private void registerButtonClicked()
{
android.content.Intent registerintent = new android.content.Intent(Login_Activity.this, Register_Activity.class);
Login_Activity.this.startActivity(registerintent);
android.util.Log.d("New User", "Attempted");
}
}
Registration_Activity
package com.example.robertmonks.mytestapp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class Register_Activity extends AppCompatActivity {
android.widget.Button createAccountButton;
android.widget.Button LoginPageButton;
android.widget.EditText password1;
android.widget.EditText password2;
android.widget.EditText FirstName;
android.widget.EditText LastName;
android.widget.EditText EmailAddress;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login_);
password1 = (android.widget.EditText) findViewById( R.id.etFirstPassword );
password2 = (android.widget.EditText) findViewById( R.id.etSecondPassword );
FirstName = (android.widget.EditText) findViewById( R.id.etFirstName );
LastName = (android.widget.EditText) findViewById( R.id.etLastName );
createAccountButton = (android.widget.Button) findViewById( R.id.blogin);
LoginPageButton = (android.widget.Button) findViewById( R.id.bregister);
EmailAddress = (android.widget.EditText) findViewById( R.id.etEmailAddress);
createAccountButton.setOnClickListener(new android.widget.Button.OnClickListener(){
#Override
public void onClick(View v) {
if(v.getId() == R.id.blogin) {
createAccountButtonClicked();//move action to new method to keep code clean
}
}
});
LoginPageButton.setOnClickListener(new android.widget.Button.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.bregister) {
LoginPageButtonClicked();
}
}
});
}
private void createAccountButtonClicked()
{
android.util.Log.d("Create Account", "Attempted");
}
private void LoginPageButtonClicked()
{
android.util.Log.d("Login Page", "Attempted");
android.content.Intent loginintent = new android.content.Intent(this, Login_Activity.class);
startActivity(loginintent);
}
}
For all the buttons, try changing the onclicklistener.
e.g. For the register button,
registerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I hope this helps. Cheers :)
Your code looks ok... i think problem is your emulator configuration.
only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
Tools > Android > AVD Manager > Edit the virtual device and the Use Host GPU setting is found there.
for more detail.. click
I've been going at this for a while. I've searched and tried everything I've seen. I cannot get this damn activity to event be declared. I have a MarkerActivity for creating markers on my map. When clicked, I want them to open an activity and pass a variable. I've tried everything and keep crashing with a NullPointerException. Code below:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tapmap.app.tapmapapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" /><meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAksheZLMAALUfLHKWOsfTFCz7iP_KwpCE" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BarBrewry"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_bar_brewry"
android:theme="#style/FullscreenTheme" >
</activity>
<activity
android:name=".MarkerActivity"
android:label="#string/title_activity_marker">
</activity>
</application>
</manifest>
Marker.java:
package com.tapmap.app.tapmapapp;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
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;
import com.google.android.gms.common.api.GoogleApiClient;
public class MarkerActivity extends android.support.v4.app.FragmentActivity implements GoogleMap.OnMarkerClickListener {
public Marker myMarker;
public LatLng latLng;
public String venueid;
public String venuename;
public String[] taps;
public String address;
public Integer markid;
public void setUpMap() {
MapsActivity.mMap.setOnMarkerClickListener(this);
//googleMap.setOnInfoWindowClickListener(listener);
myMarker = MapsActivity.mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(venuename)
.snippet("Check Taps/Get Directions")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.tmico))
);
}
#Override
public boolean onMarkerClick(final Marker marker) {
Log.i("RetrieveFeedTask", MarkerActivity.this + "Marker Clicked" + MapsActivity.venues.get(markid).venuename);
try {
Intent bar = new Intent(MarkerActivity.this, BarBrewry.class);
// bar.putExtra("venuename", venuename);
//this.startActivity(bar);
} catch(Exception vo) {
Log.i("RetrieveFeedTask", "Error opening: " + vo.getMessage());
}
return true;
}
}
Stack trace:
9153-9153/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3662)
at com.tapmap.app.tapmapapp.MarkerActivity.onMarkerClick(MarkerActivity.java:50)
at com.google.android.gms.maps.GoogleMap$10.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzn$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:347)
at com.google.android.gms.maps.internal.bd.a(SourceFile:84)
at com.google.maps.api.android.lib6.d.as.b(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.c.e.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.av.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.be.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.bd.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.bt.d(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.ak.onSingleTapConfirmed(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.h.g.onSingleTapConfirmed(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.h.i.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
MapsActivity
package com.tapmap.app.tapmapapp;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
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.LatLng;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public static final String TAG = MapsActivity.class.getSimpleName();
public static List<MarkerActivity> venues = new ArrayList<MarkerActivity>();
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
try {
setUpMap();
} catch(IOException ioe){
//nothing
}
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()throws IOException {
mMap.setMyLocationEnabled(true);
Log.i("MapsActivity","calling get locs");
try {
Log.i("RetrieveFeedTask", "Starting Call");
new RetrieveFeedTask().execute("http://fltapmap.com/get-locs.php");
} catch (Exception alle) {
Log.i("RetrieveFeedTask", "Error" + alle.getMessage());
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(10);
mMap.animateCamera(zoom);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
BarBrewry is bar barebones right now just for testing
package com.tapmap.app.tapmapapp;
import com.tapmap.app.tapmapapp.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class BarBrewry extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Perhaps you need to implement the public void onCreate(Bundle savedInstanceState) method..
It is because you use a wrong context in that line:
Intent bar = new Intent(MarkerActivity.this, BarBrewry.class);
bar.putExtra("venuename", venuename);
this.startActivity(bar);
this is not a valid context in an inner class there. Try to use:
MarkerActivity.this.startActivity(bar);
Additionally you have to implement onCreate in your MarkerActivity, otherwise there would never exist an instance of this activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
I don't exactly know what you want to achieve with MarkerActivity but like Daniel Nugent mentioned in the comments, you should consider merging your MarkerActivity with MapsActivity.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I switched over from eclipse to android studio and I'm trying to add an activity to my manifest file, I dont know the code I'm supposed to use and my app keeps crashing heres the code from my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="penis.jason.payday" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="settings"
android:label="Pay Day!!">
</activity>
<activity android:name="statistics"
android:label="Pay Day!!">
</activity>
</application>
what i have it doing is when the user pushes the settings button than it takes the to that class and new xml. heres the code i used to send the intent
Settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent GoToSettings = new Intent(getApplicationContext(), settings.class);
startActivity(GoToSettings);
finish();
}
});
heres my logcat
08-24 10:41:52.098 21750-21750/penis.jason.payday E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: penis.jason.payday, PID: 21750
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{penis.jason.payday/penis.jason.payday.settings}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2259)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$900(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1986)
at penis.jason.payday.settings.<init>(settings.java:23)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
this is the whole settings class
package penis.jason.payday;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import java.util.Calendar;
#SuppressWarnings("unused")
public class settings extends Activity {
boolean FullScreen;
Button SaveAndExit = (Button) findViewById(R.id.SaveAndExit);
Button Save = (Button) findViewById(R.id.Save);
Button Cls = (Button) findViewById(R.id.Cls);
CheckBox FullScreenOnOff = (CheckBox) findViewById(R.id.fullScreen);
CheckBox SaveWarningOnOff = (CheckBox) findViewById(R.id.SaveWarningOnOff);
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month= cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DATE);
String FullDate = (" "+month+"/"+day+"/"+year);
String Date=(String.valueOf(FullDate));
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settings);
FullScreen = getSharedPreferences("Settings",MODE_PRIVATE).getBoolean("FullScreen",false);
if(FullScreen==true){
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.settings);
}
SaveAndExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent GoToMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(GoToMain);
finish();
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Cls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
if(FullScreenOnOff.isChecked()){
FullScreen = true;
SharedPreferences FullScreenSave = getSharedPreferences("Settings", Context.MODE_PRIVATE);
SharedPreferences.Editor FullScreenE = FullScreenSave.edit();
FullScreenE.putBoolean("FullScreen", FullScreen);
FullScreenE.commit();
}
}
}
_______UPDATE______
i found the problem!
i had to change the way i declared my button varables to this
boolean FullScreen;
Button SaveAndExit,Save,Cls;
CheckBox FullScreenOnOff,SaveWarningOnOff;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month= cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DATE);
String FullDate = (" "+month+"/"+day+"/"+year);
String Date=(String.valueOf(FullDate));
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settings);
FullScreen = getSharedPreferences("Settings",MODE_PRIVATE).getBoolean("FullScreen",false);
if(FullScreen==true){
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.settings);
}
SaveAndExit = (Button) findViewById(R.id.SaveAndExit);
Save = (Button) findViewById(R.id.Save);
Cls = (Button) findViewById(R.id.Cls);
FullScreenOnOff = (CheckBox) findViewById(R.id.fullScreen);
SaveWarningOnOff = (CheckBox) findViewById(R.id.SaveWarningOnOff);
}
From the looks of your class name it should be as below, case is important.
<activity android:name=".Settings"
android:label="Pay Day!!">
</activity>
<activity android:name=".Statistics"
android:label="Pay Day!!">
</activity>
Declare <uses-sdk android:minSdkVersion="minimum_integer_value" android:targetSdkVersion="your_target_integer_value" /> in your manifest. May be your trying to run it on lower version using API's of higher level