Upon opening the first activity of my app in Android Studio, app opens fine. I copied and pasted the same main activity code to open the journal activity, and changed the variable names that were needed, but app crashes upon opening the journal up.
here is the code for opening up the journal:
public class Activity2 extends AppCompatActivity {
private Button buttonJournal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
buttonJournal = (Button) findViewById(R.id.buttonJournal);
buttonJournal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJournalActivity();
}
});
}
public void openJournalActivity () {
Intent intent = new Intent(this, JournalActivity.class);
startActivity(intent);
}
}
The journal activity I am opening up: (This might be my problem)
public class JournalActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.add_note){
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
ListView listView = findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.anxty", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if(set == null) {
notes.add("Example note");
} else{
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId",i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
new AlertDialog.Builder(getApplicationContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.anxty", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(JournalActivity.notes);
sharedPreferences.edit().putStringSet("notes",set).apply();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
}
LogCat when app crashes:
-06-11 11:55:55.744 6677-6677/com.example.anxty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anxty, PID: 6677
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anxty/com.example.anxty.JournalActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.anxty.JournalActivity.onCreate(JournalActivity.java:79)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.anxty">
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/anxty_logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/anxty_logo"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".NoteEditorActivity"></activity>
<activity android:name=".JournalActivity" />
<activity
android:name=".ui.login.LoginActivity"
android:label="#string/title_activity_login" />
<activity
android:name=".Activity2"
android:label="#string/title_activity_2"
android:theme="#style/AppTheme.NoActionBar" /> <!-- Main Activity -->
<activity
android:name=".MainActivity"
android:screenOrientation="portrait" /> <!-- Splash Screen Activity -->
<activity
android:name=".SplashScreen"
android:noHistory="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Related
I had built the app 3 days ago and the app was working fine.
yesterday I updated the Kotlin plugin to 1.3.71-studio3.6-1
after that when I build my app and run it on my phone then after login, the main activity does not launch and the app stops working but I am getting a successful login in my Firebase.
If I try to reopen the app, it does not open.
all other activities are working fine but main_activity does not.
the code of main activity was not modified
this is my manifest file
<application
android:allowBackup="false"
android:icon="#mipmap/g_c"
android:label="#string/app_name"
android:roundIcon="#mipmap/g_c_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".otp" />
<activity android:name=".Register" />
<activity android:name=".Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</application>
</manifest>
logcat error
03-30 01:40:05.051 6724-6724/com.trackerbin.guardchecker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.trackerbin.guardchecker, PID: 6724
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.trackerbin.guardchecker/com.trackerbin.guardchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
at com.trackerbin.guardchecker.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
MainActivity
public class MainActivity extends AppCompatActivity {
private Button mreport;
private Button mon;
private Button msignout;
private FirebaseAuth fAuth;
private Spinner mtower;
private ProgressBar mBar;
//AD
private AdView mAdView;
// Access a Cloud Firestore instance from your Activity
private final FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mreport = findViewById(R.id.button);
mon = findViewById(R.id.onn);
fAuth = FirebaseAuth.getInstance();
mtower = findViewById(R.id.tower);
msignout = findViewById(R.id.signout);
mBar = findViewById(R.id.bar);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adViewR);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (fAuth.getCurrentUser() == null) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
final String email = fAuth.getCurrentUser().getEmail();
final String phone = fAuth.getCurrentUser().getPhoneNumber();
mreport.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mBar.setVisibility(View.VISIBLE);
String tower = mtower.getSelectedItem().toString();
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Map<String, Object> values = new HashMap<>(); values.put(currentTime,email + phone);
db.collection("tower").document(tower)
.collection(currentDate).document("duty")
.collection("off").document(currentTime).set(values);
mBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "THANK YOU FOR REPORTING !", Toast.LENGTH_SHORT).show();
}
});
mon.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mBar.setVisibility(View.VISIBLE);
String tower = mtower.getSelectedItem().toString();
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Map<String, Object> values = new HashMap<>(); values.put(currentTime,email + phone);
db.collection("tower").document(tower)
.collection(currentDate).document("duty")
.collection("on").document(currentTime).set(values);
mBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "THANK YOU FOR REPORTING !", Toast.LENGTH_SHORT).show();
}
});
msignout.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
fAuth.signOut();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
);
}
#Override
public void onBackPressed() {
finishAffinity();
}
}
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
insert your own admob app id inside value="XXXXXXX"/>
I am trying to accomplish a task and even if I have read other topics on the same, I am experiencing extreme difficulty.
Situation
I have a program built from a navigation template and I am trying to add search functionality. I have accomplish this task with an app using activities but I haven't been able to recreate this with fragments.
Problem
When I try to search I get the error.
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{.MySearchableActivity}:
java.lang.ClassCastException:
.MySearchableActivity
cannot be cast to android.app.Activity
I believe this is getting done because I am calling an intent in a fragment, however I am unsure of how else I can accomplish that.
public class MySearchableActivity extends Fragment {
RequestQueue requestQueue;
List<NumberResults> storiesList = new ArrayList<>();
private RecyclerView recycle;
private static final String TAG = "junk";
private Toolbar toolbar;
private ListView myList;
// final Context context = this;
// #Override
//protected void onCreate(Bundle savedInstanceState)
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
// setContentView(R.layout.fragment_ministry_numbers);
// toolbar = (Toolbar) findViewById(R.id.app_bar);
// setSupportActionBar(toolbar);
Log.i(TAG, "in MySearchableActivity");
View layout = inflater.inflate(R.layout.fragment_ministry_numbers, container, false);
recycle = (RecyclerView) layout.findViewById(R.id.drawrList);
recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
recycle.setHasFixedSize(true);
Intent intent = getActivity().getIntent();
handleIntent(intent);
return layout;
}
private void handleIntent(Intent intent) {
// get the query out of the intent
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String searchQuery = intent.getStringExtra(SearchManager.QUERY);
doSearchQuery(searchQuery);
}
}
/*
#Override
protected void onNewIntent(Intent intent) {
Log.i(TAG, "in onNewIntent");
getActivity().setIntent(intent);
handleIntent(intent);
}
*/
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.searchActionBarItem);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
}
private void doSearchQuery(String query) {
final MinNumAdapters rvAdapter = new MinNumAdapters(storiesList);
recycle.setAdapter(rvAdapter);
requestQueue = Volley.newRequestQueue(getActivity());
String url = "http://werver.com/searchablewho.php?owner=" + query;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
if (response.length() > 0) {
storiesList.clear();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
NumberResults stories = new NumberResults();
if (!jsonObject.isNull("number")) {
stories.name = jsonObject.getString("number");
}
if (!jsonObject.isNull("owner")) {
stories.age = jsonObject.getString("owner");
}
storiesList.add(i, stories);
}
rvAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something
}
});
requestQueue.add(jsonArrayRequest);
}
}
Stack Trace
11-17 17:15:00.308 18802-18802/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: technologies.mirage.prigovdirectory, PID: 18802
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{technologies.mirage.prigovdirectory/technologies.mirage.prigovdirectory.MinNumResults.MySearchableActivity}: java.lang.ClassCastException: technologies.mirage.prigovdirectory.MinNumResults.MySearchableActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassCastException: technologies.mirage.prigovdirectory.MinNumResults.MySearchableActivity cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Call to Search
#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);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchActionBarItem = menu.findItem(R.id.searchActionBarItem);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchActionBarItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
return true;
}
App Manifest
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value=".MinNumResults.MySearchableActivity"/>
</activity>
<activity
android:name=".MinNumResults.MySearchableActivity"
android:label="#string/app_name"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/search_config"/>
</activity>
</application>
Naming fragment as activity wouldn't work: you can't use fragment as activity and as searchable in AndroidManifest.
You must read that thread. Hope, this will help you to find the correct way. GL
I am having a problem with my Android Flashlight App. The app crashes when I try to press the home button of the device while the app is opened then resuming (by clicking the app icon on home screen not recent apps button). After I terminate the app from the recent apps list then opening again, it does not crash anymore using the same instructions above.
Please see code below.
public class MainActivity extends Settings {
public Camera camera;
public Camera.Parameters parameters;
public ImageButton flashLightButton;
boolean isFlashLightOn = false;
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flashLightButton = (ImageButton)findViewById(R.id.flashlight_button);
flashLightButton.setOnClickListener(new FlashOnOffListener());
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
mySound = MediaPlayer.create(this, R.raw.balloon_snap);
if (isFlashSupported()) {
camera = Camera.open();
parameters = camera.getParameters();
} else {
showNoFlashAlert();
}
Settings.active = false;
//super.onCreate(savedInstanceState);
//Set layout we created
//setContentView(R.layout.activity_main);
//Register the receiver which triggers event
//when battery charge is changed
}
public void settings(View view)
{
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
this.finish();
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
//When Event is published, onReceive method is called
public void onReceive(Context c, Intent i) {
//Get Battery %
int level = i.getIntExtra("level", 0);
//Find the progressbar creating in main.xml
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
//Set progress level with battery % value
pb.setProgress(level);
//Find textview control created in main.xml
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText("" + Integer.toString(level) + "");
}
};
public class FlashOnOffListener implements View.OnClickListener{
SharedPreferences sharedPrefs = getSharedPreferences("VibrateSettings", MODE_PRIVATE);
Boolean vibration = sharedPrefs.getBoolean("VibrateSet", false);
SharedPreferences sharedPrefs2 = getSharedPreferences("SoundSettings", MODE_PRIVATE);
Boolean sound = sharedPrefs2.getBoolean("SoundSet", false);
#Override
public void onClick(View v) {
if(isFlashLightOn){
flashLightButton.setImageResource(R.drawable.flashlight_off);
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isFlashLightOn = false;
if(vibration == true){
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(20);
}
else {
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(00);
}
if (sound == true){
mySound.start();
}
}else{
flashLightButton.setImageResource(R.drawable.flashlight_on);
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isFlashLightOn = true;
if(vibration == true){
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(20);
}
else {
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(00);
}
if (sound == true){
mySound.start();
}
}
}
}
private void showNoFlashAlert() {
new AlertDialog.Builder(this)
.setMessage("Your device hardware does not support flashlight!")
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error")
.setPositiveButton("Ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).show();
}
private boolean isFlashSupported() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
#Override
protected void onDestroy() {
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
super.onDestroy();
}}
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/btn_switch_on"
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="#string/app_name">
</activity>
</application>
logcat
E/AndroidRuntime(22941): FATAL EXCEPTION: main
E/AndroidRuntime(22941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.johncarlo.flashlight/com.example.johncarlo.flashlight.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime(22941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
E/AndroidRuntime(22941): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
E/AndroidRuntime(22941): at android.app.ActivityThread.access$600(ActivityThread.java:145)
E/AndroidRuntime(22941): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
E/AndroidRuntime(22941): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(22941): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(22941): at android.app.ActivityThread.main(ActivityThread.java:5099)
E/AndroidRuntime(22941): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(22941): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(22941): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
E/AndroidRuntime(22941): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
E/AndroidRuntime(22941): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(22941): Caused by: java.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime(22941): at android.hardware.Camera.native_setup(Native Method)
E/AndroidRuntime(22941): at android.hardware.Camera.<init>(Camera.java:365)
E/AndroidRuntime(22941): at android.hardware.Camera.open(Camera.java:338)
E/AndroidRuntime(22941): at com.example.johncarlo.flashlight.MainActivity.onCreate(MainActivity.java:49)
E/AndroidRuntime(22941): at android.app.Activity.performCreate(Activity.java:5117)
E/AndroidRuntime(22941): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
E/AndroidRuntime(22941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
E/AndroidRuntime(22941): ... 11 more
W/ActivityManager( 786): Force finishing activity com.example.johncarlo.flashlight/.MainActivity
Remove below line from onCreate and write it in onResume and it might not crash after doing so.
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
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
SplashActivity .java
public class SplashActivity extends Activity {
private static String TAG = SplashActivity.class.getName();
private static long SLEEP_TIME = 4; // Time to display the splash image for
// in seconds.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes
setContentView(R.layout.activity_splash);
Log.d("man", "Starting app");
testHttp test = new testHttp();
test.test();
}
Here is the Manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.rhino68mobileapp.SplashActivity"
android:label="#string/title_activity_splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
When I run my app on my device this is what the logs read:
03-06 06:12:16.819: D/man(2105): Starting app
03-06 06:12:16.819: D/TEST(2105): Starting test
03-06 06:12:16.869: D/TEST(2105): make request
03-06 06:12:16.869: D/man(2105): Starting app
03-06 06:12:16.869: D/TEST(2105): Starting test
03-06 06:12:16.869: D/TEST(2105): make request
Try this for your splash screen:
public class Splash extends Activity implements Runnable {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(this, 1500); // SLEEP_TIME in milis
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
public void run(){
startActivity(new Intent(this, Main.class)); // Call the after splash screen
finish();
}
}