My android app crashed on startup - java

I have followed this for making my app. When I run it on my android 2.1, the app gets stuck. Can you help me? What can I do to make my app working?
MainActivity.java
public class MainActivity extends Activity {
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://check.be?v=1";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<webView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="be.moviechecker.bioscoopprogramma"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<activity
android:name="be.moviechecker.bioscoopprogramma.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>
</application>
</manifest>

In your activity_main.xml file you've used 'webView' instead of using 'WebView' hence it is not getting recognized. Please change it to to WebView and check the result. It will work.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>

#user3142817. Welcome. I've made below code make it work for you. Please check
public class MainActivity extends Activity {
private WebView view;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) this.findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("http://www.google.com");
view.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if (url != null && url.startsWith("http://"))
{
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
else
{
return false;
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK && view.canGoBack()){
view.canGoBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

Related

Android WebView Progress bar + Swipe Refresh

I am new on Android JAVA programming, trying to make this code to work. I tried all the combinations from StackOverflow, and this is the best I got. I manage to get webView and SwipeRefresh to work, but the horizontal progress bar doesn't work, and I don't know why. It just doesn't show when I refresh. Here is the code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="#+id/progressbar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="3dp" />
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefreshlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
MainActivity.java
package com.example.test;
import android.graphics.Bitmap;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
SwipeRefreshLayout swipeRefreshLayout;
ProgressBar progressBar;
WebView webView;
String url = "https://www.google.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
progressBar = findViewById(R.id.progressbar);
webView = findViewById(R.id.webView);
//setting webviewclient
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//To open hyperlink in existing WebView
view.loadUrl(request.getUrl().toString());
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
}
});
//setting webchromeclient
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView webView, int newProgress) {
progressBar.setProgress(newProgress);
}
});
//setting other settings
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl(url);
//setting swiperefreshlistener
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
}
public void onBackPressed (){
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<uses-permission
android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:usesCleartextTraffic="true"
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"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thanks
Your progressbar is behind the webview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefreshlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<ProgressBar
android:id="#+id/progressbar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="3dp"
android:visibility="gone"
tools:visibility="visible" />
</RelativeLayout>

Android Webiew App show image before loading site

I'm fresh for Android App. I done my first Webview app. Now want to add Loading Image(.jpg), before the website load. I don't know anything. Just explain clearly. Image may add in app or image from another source.
My activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
AndroidManifest.xml is below,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.steptoinstall.steptoinstall" >
<application
android:allowBackup="true"
android:icon="#mipmap/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>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
MainActivity.java is below,
package com.steptoinstall.steptoinstall;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("http://www.steptoinstall.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
I think the easiest way to do it is to place an imageView over the webView and then when the site loaded, hide it.
First of all u must change your xml like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/activity_main_imageview"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</FrameLayout>
and add this line to your main activity
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// hide your imageView
}
});
just let me know if u wanted more details.
Update 2:
In your MainActivity, after setContentView, add this:
final ImageView mImageView = (ImageView)findViewById(R.id.activity_main_imageview);
after that u can set image to this imageView in xml or in code:
in xml change your ImageView:
<ImageView
android:id="#+id/activity_main_imageview"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:src="#drawable/img" />
and your MainActivity should be this:
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("http://www.steptoinstall.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
mImageView.setVisibility(View.GONE);
}
});
To add Splash screen before loading main activity. then add this
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.example.tabs.R;
public class Splash extends Activity implements Runnable
{
Thread mThread;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mThread = new Thread(this);
mThread.start();
}
#Override
public void run()
{
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
startActivity(new Intent(Splash.this, MainActivity.class));
finish();
}
}
}
and xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/splash" >
</LinearLayout>

Adding more buttons

I'm working on a app. Past days i'm trying to get more then one button to work on my page. But i can't figur it out. Can some one help? I'm new to Development :)
Layout (xml)
Activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.rust.rustapp.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button"
android:onClick="button1Click"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="38dp"
android:text="Button"
android:onClick="button1Click"
/>
</RelativeLayout>
Java:
MainActivty:
package com.rust.rustapp;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
private void button1Click()
{
startActivity(new Intent(MainActivity.this, Intro.class));
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button1:
button1Click();
break;
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Intro.xml (Button1 is opening this page)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/test"
>
</LinearLayout>
Intro.java
package com.rust.rustapp;
import android.app.Activity;
import android.os.Bundle;
public class Intro extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rust.rustapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<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=".Intro"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
The new layout name is: FunPage
Thx!
From the code you pasted for MainActivity, it looks like you are mixing two different ways to handle button clicks.
If you can to register the click listener from your layout xml, the method corresponding to the onClick attribute needs to be public and not declared as a method inside your button1 listener.
An alternative is to listen to click events solely with your Java code. If you do this, then remove the onClick attribute from your layout XML for that button. There are many, many examples out there.
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
//TODO -- In your case, start the "Intro" activity
}
}
It might help if you extract that method to start the Intro activity to a method outside of the click listener (i.e., as a method of MainActivity).

Android Getting Runtime Error While Starting App

I'm trying to launch my app but i'm getting runtime error all the time.
Definition of the program is: App starts when user clicks button , button will be invisible and count down starts after countdown finish Menu.java will open.
Here is my code below:
Main.java
public class Main extends Activity {
TextView countDown;
int counter;
Intent menuIntent;
Button appStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menuIntent = new Intent("com.example.project_21.MENU");
counter = 5;
countDown = (TextView) findViewById(R.id.countDown);
appStartButton = (Button) findViewById(R.id.appStartButton);
appStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setVisibility(View.GONE);
while (counter != 0) {
sleep(1000);
counter--;
countDown.setText(counter + " seconds");
}
startActivity(menuIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sleep(long mill) {
try {
Thread.sleep(mill);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.project_21"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.project_21.Main"
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="com.example.project_21.Menu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.project_21.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/android2"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Main" >
<TextView
android:id="#+id/startsInfo"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:gravity="center"
android:text="#string/welcome"
android:textSize="30sp" />
<TextView
android:id="#+id/countDown"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/countDown"
android:textSize="45sp" />
<Button
android:id="#+id/appStartButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/appStartButton"
android:textSize="35sp" />
</LinearLayout>
ERROR LOG
The error message states that you are making a call to system services, before they are available. This is because you are calling them in the onCreate() method. Move the calls you are making in your Menu.java class (not included here, so can't tell you exactly which calls you are making) to another lifecycle method - onCreateView() is probably best for an Activity (onAttach() is a good one for Fragments).

Errors in my torch app

I'm trying to create an app for turning a torch on and off on android and I'm getting a few errors I cant work out. The errors only seem to come up in the java activity, and seem to be something to do with the 'cam' activity I made. At the bottom of my java cam.release when I hover it says 'Add cast'.
Thanks for your help in advanced.
MainActivity.java
public class MainActivity extends Activity implements OnCheckedChangeListener {
Camera cam;
ToggleButton mTorch;
Parameters camParams;
private Context context;
AlertDialog.Builder builder;
AlertDialog alertDialog;
private final int FLASH_NOT_SUPPORTED = 0;
private final int FLASH_TORCH_NOT_SUPPORTED = 1;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
mTorch = (ToggleButton) findViewById(R.id.toggleButton1);
} else {           
 showDialog(MainActivity.this,FLASH_NOT_SUPPORTED);
}
}
private void showDialog(MainActivity mainActivity, int fLASH_NOT_SUPPORTED2) {
// TODO Auto-generated method stub
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mTorch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#SuppressWarnings("deprecation")
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
try {
if (cam != null) {
cam = Camera.open();
}
camParams = cam.getParameters();
List<String> flashModes = camParams
.getSupportedFlashModes();
if (isChecked) {
if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
} else {           
 showDialog(MainActivity.this,FLASH_NOT_SUPPORTED);
}
} else {
camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
}
cam.setParameters(camParams);
cam.startPreview();
} catch (Exception e) {
e.printStackTrace();
cam.stopPreview();
cam.release();
}
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (cam == null) {
cam = Camera.open();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (cam != null) {
cam.release();
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
cam.release();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.t.torch"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature
android:name="android.hardware.Camera"
android:required="true" >
</uses-feature>
<uses-feature
android:name="android.hardware.camera.FLASHLIGHT"
android:required="true" >
</uses-feature>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.t.torch.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>
</application>
</manifest>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="20dip"
android:text="#string/app_name"
android:textSize="25sp" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dip"
android:text="ToggleButton" >
</ToggleButton>
</LinearLayout>
Your primary problem is that cam is never being set. You're probably getting NullPointerExceptions on any line related to that variable.
The cause is:
if (cam != null) {
cam = Camera.open();
}
Which should of course be:
if (cam == null) {
cam = Camera.open();
}
Also note that cam may be null during the invocation of onStop().

Categories