Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an Android app. This app has 12 activities, the first activity is the Splash Screen and sec activity is the intropage and 3rd activity is main and etc When I run the app, it doesn't enter the main activity and the app closes. The error is as follows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setAlpha(float)' on a null object reference
at com.github.hujiaweibujidao.wava.BaseViewAnimator.reset(BaseViewAnimator.java:78)
at com.github.hujiaweibujidao.wava.BaseViewAnimator.start(BaseViewAnimator.java:55)
at com.github.hujiaweibujidao.wava.YoYo$Builder.start(YoYo.java:128)
at com.github.hujiaweibujidao.wava.YoYo$Builder.playOn(YoYo.java:115)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:108)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Thank you for your answers, but the solutions you gave me did not help. I checked, but it still gave me the same error. I put three-activated codes for you. Can you help me, please?
this my main activity java code:
package com.example.myapplication;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.akshay.library.CurveBottomBar;
import com.github.hujiaweibujidao.wava.Techniques;
import com.github.hujiaweibujidao.wava.YoYo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.mxn.soul.flowingdrawer_core.ElasticDrawer;
import com.mxn.soul.flowingdrawer_core.FlowingDrawer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;
public class MainActivity extends AppCompatActivity {
CurveBottomBar cbb;
FlowingDrawer mDrawer;
ImageView img_icon,imgtest,img_music,img_night,img_main,img_setting;
TextView txt;
String patch;
boolean read=false,music=true,night_mode;
Button btn_fehrest,btn_last_story,btn_fav;
SharedPreferences sharedP;
LinearLayout lin_main;
Toast exit;
boolean show_intropage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbb = findViewById(R.id.cbb);
mDrawer = findViewById(R.id.drawerlayout);
img_icon = findViewById(R.id.img_icon);
imgtest = findViewById(R.id.imgtest);
txt = findViewById(R.id.txt);
btn_fehrest = findViewById(R.id.btn_fehrest);
img_music = findViewById(R.id.img_music);
lin_main = findViewById(R.id.lin_main);
img_night = findViewById(R.id.img_night);
img_main = findViewById(R.id.img_main);
btn_last_story = findViewById(R.id.btn_last_story);
btn_fav = findViewById(R.id.btn_fav);
img_setting = findViewById(R.id.img_setting);
cbb.inflateMenu(R.menu.menu_scrolling);
sharedP = getSharedPreferences(Items.SETTINGS, Context.MODE_PRIVATE);
show_intropage = sharedP.getBoolean(Items.INTROPAGE,true);
cbb.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.img_setting:
// kary ke mikhaym anjam bedim
break;
case R.id.img_music:
//
break;
}
return false;
}
});
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fehrest);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_last_story);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(btn_fav);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_music);
YoYo.with(Techniques.ZoomInDown).duration(1000).playOn(img_setting);
get_night();
permission();
//createFile();
if (show_intropage){
taptarget();
}
img_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawer.openMenu(true);
}
});
mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
mDrawer.setBackgroundColor(Color.WHITE);
mDrawer.setOnDrawerStateChangeListener(new ElasticDrawer.OnDrawerStateChangeListener() {
#Override
public void onDrawerStateChange(int oldState, int newState) {
if (newState == ElasticDrawer.STATE_CLOSED) {
Log.i("MainActivity", "Drawer STATE_CLOSED");
}
}
#Override
public void onDrawerSlide(float openRatio, int offsetPixels) {
Log.i("MainActivity", "openRatio=" + openRatio + " ,offsetPixels=" + offsetPixels);
}
});
}
public void createFile(){
try {
patch = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mbook/";
File mfile = new File(patch);
if (!mfile.exists()) {
mfile.mkdir();
mfile.createNewFile();
CopyDB(getBaseContext().getAssets().open("Mbook.db"), new FileOutputStream(patch+"/Mbook.db"));
//Toast.makeText(this, patch+"", Toast.LENGTH_LONG).show();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void CopyDB (InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int file_length;
while ((file_length = inputStream.read(buffer))>0){
outputStream.write(buffer,0,file_length);
}
inputStream.close();
outputStream.close();
}
public void fehrest_intent(View view) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(800).playOn(btn_fehrest);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fehrest");
startActivity(intent);
}
},1500);
}
private void permission(){
Dexter.withContext(MainActivity.this)
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
createFile();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response !=null && response.isPermanentlyDenied()){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
}
Toast.makeText(MainActivity.this, "جهت استفاده از برنامه دادن اجازه دسترسی ضروریست", Toast.LENGTH_SHORT).show();
alert();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, final PermissionToken token) {
alert();
}
}).check();
}
public void alert(){
AlertDialog.Builder Hoshdar = new AlertDialog.Builder(MainActivity.this);
Hoshdar.setTitle("توجه");
Hoshdar.setMessage("جهت استفاده از برنامه دادن اجازه دسترسی ضروریست لطفا درقسمت تنظیمات اجازه دسترسی را فعال کنید");
Hoshdar.setCancelable(false);
Hoshdar.setPositiveButton("رفتن به تنظیمات", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",getPackageName(),null));
startActivity(intent);
}
});
Hoshdar.create().show();
}
public void fav_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_fav);
mDrawer.closeMenu(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Fehrest.class);
intent.putExtra("button","fav");
intent.putExtra("activity","main");
startActivity(intent);
}
},1500);
}
public void text_intent(View view) {
YoYo.with(Techniques.Pulse).duration(600).playOn(btn_last_story);
if (read){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent_movies = new Intent(getBaseContext(), Text_activity.class);
intent_movies.putExtra("activity","main");
startActivity(intent_movies);
}
},1500);
}else {
Toast.makeText(this, "هنوز هیچ داستانی مطالعه نکردید!", Toast.LENGTH_SHORT).show();
}
}
public void setting_intent(MenuItem item) {
mDrawer.closeMenu(true);
YoYo.with(Techniques.Pulse).duration(600).playOn(img_setting);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,Setting.class));
}
},1500);
}
public void set_music(MenuItem item) {
YoYo.with(Techniques.Pulse).duration(600).playOn(img_music);
if (music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
music=false;
sharedP.edit().putBoolean(Items.MUSIC, false).apply();
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
music=true;
sharedP.edit().putBoolean(Items.MUSIC, true).apply();
}
}
public void get_night(){
music = sharedP.getBoolean(Items.MUSIC,true);
night_mode = sharedP.getBoolean(Items.NIGHT_MODE,false);
read = sharedP.getBoolean(Items.READ,false);
if (night_mode){
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
}else {
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
}
if (!music){
stopService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_off_icon);
}else {
startService(new Intent(MainActivity.this,PlayMusic.class));
img_music.setBackgroundResource(R.drawable.music_on_icon);
}
}
public void set_night(View view){
YoYo.with(Techniques.RotateIn).duration(800).playOn(img_night);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (night_mode){
lin_main.setBackgroundResource(0);
img_night.setBackgroundResource(R.drawable.moon_icon);
img_main.setBackgroundResource(R.drawable.main);
sharedP.edit().putBoolean(Items.NIGHT_MODE, false).apply();
night_mode=false;
}else {
lin_main.setBackgroundResource(R.color.Black0);
img_night.setBackgroundResource(R.drawable.sun_icon);
img_main.setBackgroundResource(R.drawable.main2);
sharedP.edit().putBoolean(Items.NIGHT_MODE, true).apply();
night_mode=true;
}
}
},800);
}
#Override
protected void onResume() {
super.onResume();
get_night();
}
#Override
protected void onDestroy() {
stopService(new Intent(MainActivity.this,PlayMusic.class));
super.onDestroy();
}
public void finish(View view) {
mDrawer.closeMenu(true);
finish();
}
#SuppressLint("ResourceAsColor")
private void taptarget(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_night)
.setPrimaryText("فعال کردن حالت شب")
.setSecondaryText("با زدن این دکمه میتوانید حالت مطالعه در شب را فعال یا غیر فعال کنید")
//.setPrimaryTextColour(Color.parseColor("#13dc74"))
// .setSecondaryTextColour(Color.parseColor("#13dc74"))
.setFocalColour(R.color.mycolorGray)
.setBackButtonDismissEnabled(false)
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED|| state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "اولی", Toast.LENGTH_SHORT).show();
txt_target();
}
}
})
.show();
}
private void txt_target(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_icon)
.setFocalColour(R.color.mycolorGray)
.setPrimaryText("منوی کشویی")
.setSecondaryText("با زدن این دکمه منوی کشویی برنامه باز خواهد شد که شامل آیتم های مختلفی می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target3();
}
}
})
.show();
}
private void target3(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_music)
.setPrimaryText("فعال/غیرفعال موزیک")
.setSecondaryText("با زدن این دکمه میتوانید موزیک پس زمینه حین مطالعه را پخش یا قطع کنید")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
target4();
}
}
})
.show();
}
private void target4(){
new MaterialTapTargetPrompt.Builder(MainActivity.this)
.setTarget(R.id.img_setting)
.setPrimaryText("تنظیمات")
.setSecondaryText("با زدن این دکمه بخش تنظیمات باز خواهد شد که شامل تغییر فونت متن ، سایز متن و ... می باشد")
.setBackgroundColour(Color.parseColor("#635B5B"))
.setPromptStateChangeListener(new MaterialTapTargetPrompt.PromptStateChangeListener()
{
#Override
public void onPromptStateChanged(MaterialTapTargetPrompt prompt, int state)
{
if (state == MaterialTapTargetPrompt.STATE_FOCAL_PRESSED || state==MaterialTapTargetPrompt.STATE_NON_FOCAL_PRESSED)
{
// User has pressed the prompt target
//Toast.makeText(MainActivity.this, "دومی", Toast.LENGTH_SHORT).show();
sharedP.edit().putBoolean(Items.INTROPAGE, false).apply();
}
}
})
.show();
}
#Override
public void onBackPressed() {
if (!(exit ==null)){
super.onBackPressed();
//MainActivity.this.finish();
}else {
exit = Toast.makeText(this,"برای خروج دوباره بزنید",Toast.LENGTH_LONG);
exit.show();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit= null;
}
},3000);
}
}
this my main activity xml code:
Splash Screen Activity Run enters Intro Page. After clicking the reject or complete button, the program will not enter the activity menu and the program will close.
Please follow the below options. Hope your problem will be solved.
1) Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"
<activity
android:name=".MainActivity" >
</activity>
2) Clean and rebuilt the project and Hope it will work.
You forgot find view btn_last_story add it to onCreate
btn_last_story = findViewById(R.id.btn_last_story);
I have a probleme with my code. When I lunch my program i have a crash.
On the Android monitor i can see :
04-04 20:21:10.369 2042-2042/com.led.led E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.led.led, PID: 2042
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.led.led/com.led.led.ledControlSeekBar}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
at com.led.led.ledControlSeekBar.onCreate(ledControlSeekBar.java:76)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
And there is my class :
package com.led.led;
import android.bluetooth.BluetoothDevice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.SeekBar;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import java.io.IOException;
import java.util.UUID;
import java.lang.String;
public class ledControlSeekBar extends AppCompatActivity {
Button btnDis;
SeekBar seek_r, seek_g, seek_b;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ConnectBT bt = new ConnectBT();
String phraseAEnvoyer = "000000000";
String phraseTemp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//receive the address of the bluetooth device
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS);
bt.execute();
//view of the ledControl layout
setContentView(R.layout.activity_led_control);
//call the widgtes
btnDis = (Button)findViewById(R.id.button_disconnect);
seek_r = (SeekBar)findViewById(R.id.seekBar_r);
seek_g = (SeekBar)findViewById(R.id.seekBar_g);
seek_b = (SeekBar)findViewById(R.id.seekBar_b);
seek_r.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Rouge : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(3, 9);
phraseAEnvoyer = progressChanged + phraseTemp;
envoyerPhrase(phraseAEnvoyer);
}
});
seek_g.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Vert : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(6, 9);
phraseAEnvoyer = phraseAEnvoyer.substring(0, 3);
phraseAEnvoyer = phraseAEnvoyer + progressChanged + phraseTemp;
envoyerPhrase(phraseAEnvoyer);
}
});
seek_b.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
msg("Bleu : " + progressChanged);
phraseTemp = phraseAEnvoyer.substring(0, 6);
phraseAEnvoyer = phraseTemp + progressChanged;
envoyerPhrase(phraseAEnvoyer);
}
});
btnDis.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void envoyerPhrase(String phrase)
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(phraseAEnvoyer.getBytes());
msg(phraseAEnvoyer);
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControlSeekBar.this, "Connecting...", "Please wait!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
I don't finish and some lines are useful sorry.
If someone can help me I will happy.
Thank you.
I have also the same error . I resolved this error by defining a function outside the onCreate() method. Inside that function you need to call the different seek bar findViewByid method . Like this
private void initializeVariables() {
// Showing progress dialog
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
seekBar = (SeekBar) findViewById(R.id.seekBarprice);
seekBarKilometer = (SeekBar) findViewById(R.id.seekBarDis);
}
Declare pDialog first private ProgressDialog pDialog;
call the initializeVariables() method inside the oncreate method , here i mention my seekbar names replace these names with your code .
`
Hi I followed I followed a tutorial here and wrote out the code, I tested it but the flashlight does not turn on and I cant figure out what's gone wrong.
I left out the parts where there was sound because I preferred there not to be any.
package net.netne.benpaterson35;
import android.app.*;
import android.os.*;
import android.hardware.*;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity
{
Button mainButton1;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainButton1 = (Button) findViewById(R.id.mainButton1);
hasFlash = getApplicationContext().getPackageManager().
hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Sorry");
alert.setMessage("This device doesn't have flash a flash light");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
finish();
}
});
alert.show();
return;
}
getCamera();
mainButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if (isFlashOn){
turnOffFlash();}
else {
turnOnFlash();
}
};
});
}
private void getCamera(){
if (camera == null){
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Failed to open camera", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!isFlashOn){
if (camera == null || params == null){
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash() {
if (isFlashOn){
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
}
#Override
protected void onPause()
{
super.onPause();
turnOffFlash();
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
protected void onResume()
{
super.onResume();
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart()
{
super.onStart();
getCamera();
}
#Override
protected void onStop()
{
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
Thanks for reading :)
if you are working on new device the code you followed wont work on newer devices i made it work on Lollipop device by following this code give it a try
mCam = Camera.open();
Camera.Parameters p = mCam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCam.setParameters(p);
mPreviewTexture = new SurfaceTexture(0);
try {
mCam.setPreviewTexture(mPreviewTexture);
} catch (IOException ex) {
// Ignore
}
mCam.startPreview();
Did you add
<uses-permission android:name="android.permission.CAMERA" />
to your AndroidManifest?
Highly suspect you didn't add the permission.
I am really new to Android Programming. I am working on a simple app: FlashLight for Android.
I need the app to continue run in background if the user presses the menubutton or locks the screen. The light should not stop until the user presses the button the stop the light.
Below is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity
extends Activity {
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if(camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch(RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if(!isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if(isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage() {
if(isFlashOn) {
btnSwitch.setImageResource(R.drawable.btn_switch_on);
} else {
btnSwitch.setImageResource(R.drawable.btn_switch_off);
}
}
/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound() {
if(isFlashOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash) {
turnOnFlash();
}
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if(camera != null) {
camera.release();
camera = null;
}
}
}
You;re turning off the light in onPause. When the screen is locked or the app is minimized, onPause is called. If you don't want that to happen, don't call it there.
I think you are searching for Services: http://developer.android.com/guide/components/services.html
They are very similar to an Activity but do dot provide a user interface and can run in the background.
I have 300 MB videos on my http server...I'm trying to make good simple code to play (in 3G mode) these videos remotely in my application - sd storing or local storing is not a option. Of course I started from demo source in SDK android-17 (MediaPlayerDemo_Video, VideoViewDemo...) and in 3G mode my video doesn't play (I'm testing on Samsung Galaxy Nexus). After that I made new try in next code:
/**
* Listing 15-4: Initializing and assigning a Surface View to a Media Player
*/
import java.io.IOException;
import mobile.dariknews.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
public class SurfaceViewVideoViewActivity extends Activity
implements SurfaceHolder.Callback {
static final String TAG = "SurfaceViewVideoViewActivity";
private MediaPlayer mediaPlayer;
public void surfaceCreated(SurfaceHolder holder) {
try {
// When the surface is created, assign it as the
// display surface and assign and prepare a data
// source.
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("http://snimkitevi-bg.com/darik/1.MP4");
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
Log.e(TAG, "Illegal Argument Exception", e);
} catch (IllegalStateException e) {
Log.e(TAG, "Illegal State Exception", e);
} catch (SecurityException e) {
Log.e(TAG, "Security Exception", e);
} catch (Exception e) {
Log.e(TAG, "IO Exception", e);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfaceviewvideoviewer);
// Create a new Media Player.
mediaPlayer = new MediaPlayer();
// Get a reference to the Surface View.
final SurfaceView surfaceView =
(SurfaceView)findViewById(R.id.surfaceView);
// Configure the Surface View.
surfaceView.setKeepScreenOn(true);
// Configure the Surface Holder and register the callback.
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
// Connect a play button.
Button playButton = (Button)findViewById(R.id.buttonPlay);
playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.start();
}
});
// Connect a pause button.
Button pauseButton = (Button)findViewById(R.id.buttonPause);
pauseButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.pause();
}
});
// Add a skip button.
Button skipButton = (Button)findViewById(R.id.buttonSkip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.seekTo(mediaPlayer.getDuration()/2);
}
});
/**
* Listing 15-5: Controlling playback using the Media Controller
*/
MediaController mediaController = new MediaController(this);
mediaController.setMediaPlayer(new MediaPlayerControl() {
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
public void start() {
mediaPlayer.start();
}
});
}
}
after that new try in
import android.app.Activity;
import android.app.Application;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.widget.MediaController;
import android.widget.VideoView;
public class PlayerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videoplayer);
new LoadOutbox().execute();
}
/**
* Background Async Task to Load all OUTBOX messages by making HTTP Request
* */
class LoadOutbox extends AsyncTask<String, String, String> {
int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting Outbox JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
VideoView videoView = (VideoView) findViewById(R.id.videoView1);
videoView.setKeepScreenOn(true);
// Attach a Media Controller MediaController mediaController = new
// MediaController( this); videoView.setMediaController(
// mediaController);
MediaController mediaController = new MediaController(
PlayerActivity.this);
videoView.setMediaController(mediaController);
Uri uri = Uri.parse("http://snimkitevi-bg.com/darik/1.MP4");
videoView.setVideoURI(uri);
videoView.start();
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public static Bitmap getLocalImageBitmap(String url) {
return MainNewsActivities.getLocalImageBitmap(url);
}
}
After that I played with 50 other tests with MediaPlayer and VIewVideo... All results are same - slow and freezed video playing. My need is pretty simple - I have big video files (mp4) on my website and I want to play them on my app. So I'm here - what is the right formula for playing of large remote files in android application?
PS: Of course I tried to use GStreamer but this framework is not compatible with last android environment - I played with in 2 days...My video is OK - in wifi mode I play http://snimkitevi-bg.com/darik/1.MP4
So could you give me some good advases, examples, tutorials how MediaPlayer could play normally, buffered and fastly big video files in 3G internet connection?