Android SeekBar NullPointerException - java

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 .
`

Related

Attempt to invoke virtual method 'void android.view.View.setAlpha(float) [duplicate]

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);

Android Studio App crashes on Activity Start with Bluetooth Code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I just added A new code to my app which is supposed to cennct via bluetooth to an arduino to control it... Im fairly new to programming java. Compiling has not shown any errors so far so I booted it up on my device and it crashes as soon as I open the Activity with the bluetooth code in it. Below you will find my Activity and my error logcat:
I hope someone can help :)
BT_Classic.java:
package com.car.bluetooth.bluetoothcar;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BT_Classic extends AppCompatActivity {
private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
private ProgressDialog progress;
ListView listView;
BluetoothSocket bluetoothSocket;
BluetoothDevice bluetoothDevice;
private final static UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
private ArrayList<String> mDeviceList = new ArrayList<String>();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
//BLUETOOTH VERBINDUNG
private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;
private class ConnectingThread extends Thread {
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
BluetoothDevice bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
btAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt__classic);
pairedButton = (Button) findViewById(R.id.pairedButton);
discoveredButton = (Button) findViewById(R.id.discoveredButton);
btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = btAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
//Pairing Button
pairedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<String>();
for (BluetoothDevice bt : pairedDevices){
devices.add(bt.getName());
devices.add(bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
listView.setAdapter(arrayAdapter);
}
});
discoveredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!btAdapter.isDiscovering()){
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(bton, REQUEST_DISCOVERABLE);
}
}
});
btonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bton, REQUEST_ENABLED);
}
});
btoffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.disable();
}
});
}
}
Error Logcat:
2018-09-18 17:48:10.947 31085-31085/com.car.bluetooth.bluetoothcar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.car.bluetooth.bluetoothcar, PID: 31085
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.car.bluetooth.bluetoothcar/com.car.bluetooth.bluetoothcar.BT_Classic}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.car.bluetooth.bluetoothcar.BT_Classic.onCreate(BT_Classic.java:121)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6592) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 
You never initialized your listView variable.
Make sure it's initialized under onCreate():
listView = (ListView) findViewById(R.id.whateveryourlistviewis);

I'm building a media player app, my application is getting a fatal exception

I don't know what to do now, I'm new to Android.
package com.example.macbookpro.myplayer;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class AudioPlayer extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {
ImageView btn_play;
Button btn_pause;
ImageView btn_next;
ImageView btn_prev;
ImageView btn_forward;
ImageView btn_backward;
TextView song_title;
int currentsongindex;
int seekForwardTime = 5000;
int seekBackwardTime = 5000;
private Utilities utilities;
Handler mHandler1=new Handler();
SeekBar song_progressbar;
final ArrayList<File> arrayList = new ArrayList<File>();
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
btn_play = (ImageView) findViewById(R.id.btn_play);
btn_next = (ImageView) findViewById(R.id.btn_next);
btn_prev = (ImageView) findViewById(R.id.btn_prev);
btn_forward = (ImageView) findViewById(R.id.btn_forward);
btn_backward = (ImageView) findViewById(R.id.btn_backwrd);
song_title = (TextView) findViewById(R.id.tw);
song_progressbar=(SeekBar)findViewById(R.id.song_progressbar);
song_progressbar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
try {
PlaySongtwo(getIntent().getStringExtra("index"));
} catch (IOException e) {
e.printStackTrace();
}
final String[] sec = getIntent().getStringArrayExtra("index2");
currentsongindex = Integer.parseInt((getIntent().getStringExtra("positionofcurrentsong")));
utilities = new Utilities();
// Button for playing the song
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
btn_play.setImageResource(R.drawable.button_play);
} else {
if (mp != null) {
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
}
}
} else {
if (mp != null) {
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
}
}
}
});
// Button for the next song in the list
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("currenttt song is ",currentsongindex+"");
if(currentsongindex < (sec.length-1)){
int cc=currentsongindex+1;
Log.e("value in cc",cc+"");
try {
PlaySongtwo(sec[cc]);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("next song number is ",cc +"");
currentsongindex = currentsongindex +1;
}else {
try {
PlaySongtwo(sec[0]);
} catch (IOException e) {
e.printStackTrace();
}
currentsongindex = 0;
}
}
});
//Button for the previous song in the list
btn_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentsongindex > 0){
int prevsong= currentsongindex-1;
try {
PlaySongtwo(sec[prevsong]);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("prev song",prevsong+"");
currentsongindex = prevsong;
}else {
try {
PlaySongtwo(String.valueOf((sec.length-1)));
} catch (IOException e) {
e.printStackTrace();
}
currentsongindex = sec.length-1;
}
}
});
//Button for fast-forwarding the song
btn_forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition + seekForwardTime <= mp.getDuration() ){
mp.seekTo(currentPosition + seekForwardTime);
}else {
mp.seekTo(mp.getDuration());
}
}
});
//Button for fast-backwarding the song
btn_backward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int currentPostion = mp.getCurrentPosition();
if(currentPostion - seekBackwardTime >= 0){
mp.seekTo(currentPostion - seekBackwardTime);
}else {
mp.seekTo(0);
}
}
});
}
private void PlaySongtwo(String path) throws IOException {
try {
String songname = path.substring(path.lastIndexOf("/") + 1);
song_title.setText(songname);
mp.reset();
Uri myUri = Uri.parse(path);
mp.setDataSource(AudioPlayer.this, myUri);
mp.prepare();
mp.start();
btn_play.setImageResource(R.drawable.button_pause);
song_progressbar.setProgress(0);
song_progressbar.setMax(100);
updateProgressBar1();
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateProgressBar1() {
mHandler1.postDelayed(mUpdateTimeTask1,100);
}
private Runnable mUpdateTimeTask1=new Runnable() {
#Override
public void run() {
long totalDuration = mp.getDuration();
long currentDuration=mp.getCurrentPosition();
int progress=(int)(utilities.getProgresspercentage(currentDuration,totalDuration));
song_progressbar.setProgress(progress);
mHandler1.postDelayed(this,100);
}
};
#Override
protected void onDestroy ()
{
super.onDestroy();
mp.release();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler1.removeCallbacks(mUpdateTimeTask1);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler1.removeCallbacks(mUpdateTimeTask1);
int totalDuration=mp.getDuration();
int currentPosition=utilities.progressToTimer(seekBar.getProgress(),totalDuration);
mp.seekTo(currentPosition);
updateProgressBar1();
}
#Override
public void onCompletion(MediaPlayer mp1) {
enter code here
}
}
This is the error I'm facing.
11-06 13:30:03.935 1060-1060/com.example.macbookpro.myplayer E/MediaPlayer: Should have subtitle controller already set
11-06 13:30:04.031 1060-1060/com.example.macbookpro.myplayer E/MediaPlayer: Should have subtitle controller already set
11-06 13:30:22.260 1060-1060/com.example.macbookpro.myplayer D/AndroidRuntime: Shutting down VM
11-06 13:30:22.261 1060-1060/com.example.macbookpro.myplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.macbookpro.myplayer, PID: 1060
java.lang.IllegalStateException
at android.media.MediaPlayer.getDuration(Native Method)
at com.example.macbookpro.myplayer.AudioPlayer$6.run(AudioPlayer.java:220)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
My guess is that you are trying to getDuration before your MediaPlayer is ready to be used.
Make sure you're setting all controls that interact with the mediaplayer.

Android Wear Step Counter crashing app

I was writing an app to read heart rate and step count using an android wear device. The heart rate sensor works properly but the step count is causing an issue. However, on commenting the listener for Step Counter and registering a null in onResume() the app works with heart rate sensor. I'm not getting any log regarding this otherwise I would have posted it here. Here's the code that I'm using
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.nio.ByteBuffer;
import java.util.List;
public class MainActivity extends Activity {
private SensorManager mSensorManager;
private TextView mTextViewHeart, mTextViewStep;
private Sensor mHeartRateSensor, mStepCounterSensor;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextViewHeart = (TextView) stub.findViewById(R.id.value_heart);
mTextViewStep = (TextView) stub.findViewById(R.id.value_step);
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(heartListener, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(stepListener, mStepCounterSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(heartListener, mHeartRateSensor);
}
SensorEventListener heartListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
if (event.values.length > 0) {
if (event.values[0] > 0.0f) {
mTextViewHeart.setBackgroundResource(android.R.color.holo_green_light);
mTextViewHeart.setText(Float.toString(event.values[0]));
sendToHandheld(Math.round(event.values[0]), Sensor.TYPE_HEART_RATE);
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
SensorEventListener stepListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
if (event.values.length > 0) {
mTextViewStep.setBackgroundResource(android.R.color.holo_green_light);
mTextViewStep.setText(Float.toString(event.values[0]));
sendToHandheld(Math.round(event.values[0]), Sensor.TYPE_STEP_COUNTER);
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
private void sendToHandheld(final int val, final int type) {
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i = 0; i < nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/" + type, ByteBuffer.allocate(4).putInt(val).array());
Log.d("Sending", type + ":" + val);
}
}
}
});
}
}
Update
Got the log somehow
06-15 11:46:02.342 3355-3355/com.hsc.fit E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.hsc.fit, PID: 3355
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setBackgroundResource(int)' on a null object reference
at com.hsc.fit.MainActivity$3.onSensorChanged(MainActivity.java:92)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:405)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Fixed it. The WatchViewStub's setOnLayoutInflatedListener() is called after onResume(), and my Sensor gets registered in onResume(). Since my text view is used in the listener of the sensor, and it wasn't assigned a refrence yet, I was getting a NullPointerException. I moved the sensor registertion inside WatchViewStub's listener and it works now.

ProgressDialog not updating after Configuration Change (orientation turns to horizontal)

ProgressDialog quits updating when orientation of screen changes. I have put into place a fix that salvages the asynctask and sets the activity of the asynctask to the new activity after it is destroyed and rebuilt. The percentage complete on the progressdialog stays at the percentage it was at before the orientation change.
What am I missing?
package net.daleroy.fungifieldguide.activities;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Toast;
import net.daleroy.fungifieldguide.R;
import net.daleroy.fungifieldguide.fungifieldguideapplication;
public class FungiFieldGuide extends Activity {
//static final int PROGRESS_DIALOG = 0;
//ProgressThread progressThread;
private final static String LOG_TAG = FungiFieldGuide.class.getSimpleName();
fungifieldguideapplication appState;
private DownloadFile mTask;
public boolean mShownDialog;
ProgressDialog progressDialog;
private final static int DIALOG_ID = 1;
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if ( id == DIALOG_ID ) {
mShownDialog = true;
}
}
private void onTaskCompleted() {
Log.i(LOG_TAG, "Activity " + this + " has been notified the task is complete.");
//Check added because dismissDialog throws an exception if the current
//activity hasn't shown it. This Happens if task finishes early enough
//before an orientation change that the dialog is already gone when
//the previous activity bundles up the dialogs to reshow.
if ( mShownDialog ) {
dismissDialog(DIALOG_ID);
Toast.makeText(this, "Finished..", Toast.LENGTH_LONG).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_ID:
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading Database (only first run)...");
return progressDialog;
default:
return super.onCreateDialog(id);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
appState = ((fungifieldguideapplication)this.getApplication());
Object retained = getLastNonConfigurationInstance();
if ( retained instanceof DownloadFile ) {
Log.i(LOG_TAG, "Reclaiming previous background task.");
mTask = (DownloadFile) retained;
mTask.setActivity(this);
//showDialog(DIALOG_ID);
}
else {
if(!appState.service.createDataBase())
{
Log.i(LOG_TAG, "Creating new background task.");
//showDialog(DIALOG_ID);
mTask = new DownloadFile(this);
mTask.execute("http://www.codemarshall.com/Home/Download");
}
}
//showDialog(PROGRESS_DIALOG);
View btn_Catalog = findViewById(R.id.btn_Catalog);
btn_Catalog.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Cat_Genus.class);//new Intent(this, Total.class);
startActivity(i);
}
});
View btn_Search = findViewById(R.id.btn_Search);
btn_Search.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Search.class);//new Intent(this, Total.class);
startActivity(i);
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
mTask.setActivity(null);
return mTask;
}
#Override
public void onDestroy()
{
super.onDestroy();
//progressDialog.dismiss();
//progressDialog = null;
appState.service.ClearSearchParameters();
}
private class DownloadFile extends AsyncTask<String, Integer, Boolean>{
private FungiFieldGuide activity;
private boolean completed;
private String Error = null;
private String Content;
private DownloadFile(FungiFieldGuide activity) {
this.activity = activity;
}
#Override
protected void onPreExecute()
{
showDialog(DIALOG_ID);
}
#Override
protected Boolean doInBackground(String... urlarg) {
int count;
try {
URL url = new URL(urlarg[0]);
URLConnection conexion = url.openConnection();
conexion.setDoInput(true);
conexion.setUseCaches(false);
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(conexion.getInputStream());
OutputStream output = new FileOutputStream("/data/data/net.daleroy.fungifieldguide/databases/Mushrooms.db");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)total*100/lenghtOfFile);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.i(LOG_TAG, e.getMessage());
}
return null;
}
#Override
public void onProgressUpdate(Integer... args){
progressDialog.setProgress(args[0]);
}
#Override
protected void onPostExecute(Boolean result)
{
completed = true;
notifyActivityTaskCompleted();
}
private void notifyActivityTaskCompleted() {
if ( null != activity ) {
activity.onTaskCompleted();
}
}
private void setActivity(FungiFieldGuide activity) {
this.activity = activity;
if ( completed ) {
notifyActivityTaskCompleted();
}
}
}
}
This is not a real solution but to prevent this I just disabled orientation changes during the life of the AsyncTask with adding first:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
and when the job is done:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
Hope this helps.

Categories