the mediaPlayer in my timer keeps crushing the app - java

when i run this code :
package com.example.eggtimer;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView timeLft;
SeekBar timer;
public void start(View view) {
CountDownTimer countDownTimer = new CountDownTimer(timer.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long l) {
updateTimer((int) l / 1000);
}
#Override
public void onFinish() {
Log.i("state", "done");
MediaPlayer hi = MediaPlayer.create(getApplicationContext(),R.raw.sound);
hi.start();
}
}.start();
}
public void updateTimer(int secLft) {
int min = secLft/60;
int sec = secLft - (min*60);
String secS = Integer.toString(sec);
if (sec <= 9) {
secS = "0" + sec;
}
timeLft.setText(Integer.toString(min) + ":" + secS);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = findViewById(R.id.timer);
timeLft = findViewById(R.id.timeLft);
timer.setMax(600);
timer.setProgress(30);
timer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
updateTimer(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
without the mediaPlayer the code runs ok, but when i run it with the mediaPlayer it crushs, and these errors appear in the run section :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eggtimer, PID: 10017
android.content.res.Resources$NotFoundException: File res/raw/sound.MP3 from drawable resource ID #0x7f0c0000
at android.content.res.ResourcesImpl.openRawResourceFd(ResourcesImpl.java:296)
at android.content.res.Resources.openRawResourceFd(Resources.java:1292)
at android.media.MediaPlayer.create(MediaPlayer.java:965)
at android.media.MediaPlayer.create(MediaPlayer.java:948)
at com.example.eggtimer.MainActivity$1.onFinish(MainActivity.java:27)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
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:767)
Caused by: java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed
at android.content.res.AssetManager.openNonAssetFdNative(Native Method)
at android.content.res.AssetManager.openNonAssetFd(AssetManager.java:487)
at android.content.res.ResourcesImpl.openRawResourceFd(ResourcesImpl.java:294)
at android.content.res.Resources.openRawResourceFd(Resources.java:1292) 
at android.media.MediaPlayer.create(MediaPlayer.java:965) 
at android.media.MediaPlayer.create(MediaPlayer.java:948) 
at com.example.eggtimer.MainActivity$1.onFinish(MainActivity.java:27) 
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
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:767)
what does this mean?

Related

Error inflating class androidx.leanback.widget.BrowseFrameLayout

I'm testing the new support library leanback to design apps for TV, and i have a error ever android try to inflate the BrowseFragment and it throws this exception and don't know how to solve it. Thank you so much for your help.
Error -
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.directsportsnetwork.tv/com.directsportsnetwork.tv.ui.TeamSclActivity}: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Field.get(java.lang.Object)' on a null object reference
at uk.co.chrisjenx.calligraphy.ReflectionUtils.getValue(ReflectionUtils.java:29)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(CalligraphyLayoutInflater.java:203)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(CalligraphyLayoutInflater.java:20)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:302)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at androidx.leanback.app.BrowseFragment.onCreateView(BrowseFragment.java:1318)
at android.app.Fragment.performCreateView(Fragment.java:2505)
at android.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManager.java:1491)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1274)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1486)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1728)
E/AndroidRuntime: at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3562)
at android.app.FragmentController.onCreateView(FragmentController.java:104)
at android.app.Activity.onCreateView(Activity.java:7112)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:229)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:303)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at android.transition.Scene.enter(Scene.java:182)
at com.android.internal.policy.PhoneWindow.transitionTo(PhoneWindow.java:522)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:453)
at android.app.Activity.setContentView(Activity.java:3468)
at androidx.activity.ComponentActivity.setContentView(ComponentActivity.java:448)
at com.directsportsnetwork.tv.ui.TeamSclActivity.onCreate(TeamSclActivity.java:55)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
My Activity code is -
package com.directsportsnetwork.tv.ui;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.DeviceLogManager;
import com.directsportsnetwork.tv.api.Utils;
import org.json.JSONArray;
import java.util.HashMap;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class TeamSclActivity extends FragmentActivity {
private String TAG = TeamSclActivity.class.getSimpleName();
private ImageView topShelfImg, topShelfMask;
private TeamSclFragment mTeamSclFragment;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teamscl);
IntentFilter filter = new IntentFilter();
filter.addAction("com.directsportsnetwork.tv.STOP");
registerReceiver(broadcastReceiver, filter);
DeviceLogManager.instance().sendTeamSelectionPageData(TeamSclActivity.this);
topShelfImg = (ImageView) findViewById(R.id.top_shelf_image);
topShelfMask = (ImageView) findViewById(R.id.top_shelf_mask);
Intent intent = getIntent();
if (intent != null) {
try {
String channelData = intent.getStringExtra(Utils.EXTRA_CHANNEL_RESPONSE);
HashMap<String, Integer> teamTrnMap = (HashMap<String, Integer>) intent.getSerializableExtra(Utils.EXTRA_TEAM_TRN_MAP);
mTeamSclFragment = (TeamSclFragment) getFragmentManager().findFragmentById(R.id.main_browse_fragment);
mTeamSclFragment.onResponseData(new JSONArray(channelData), teamTrnMap);
} catch (Exception e) {
e.printStackTrace();
}
setTopShelfMask();
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mHandler.postDelayed(this, 300);
if (mTeamSclFragment.getView() != null && getCurrentFocus() instanceof RelativeLayout) {
mTeamSclFragment.getView().requestFocus();
mHandler.removeCallbacks(this);
mHandler.removeCallbacksAndMessages(null);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}, 300); //Changes START HERE FOR NEW CHANGES - 10/20/2018
}
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
#SuppressLint("MissingSuperCall")
#Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
// remot Button OnClickListener methods
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
// Remove shadow over topShelfImage at here
if (mTeamSclFragment != null) {
mTeamSclFragment.startBackgroundTimer();
}
default:
return super.onKeyUp(keyCode, event);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
// Add shadow over topShelfImage at here
topShelfImg.setAlpha(0.3f);
}
if (mTeamSclFragment != null) {
mTeamSclFragment.onMyKeyDown(keyCode, event);
}
return false;
}
public ImageView getTopShelfImg() {
return topShelfImg;
}
public void setTopShelfMask() {
if (Utils.SHOW_TOP_SHELF_MASK) {
topShelfMask.setBackground(ContextCompat.getDrawable(TeamSclActivity.this, R.drawable.ic_mask_bottom));
}
}
}
My Fragment code -
package com.directsportsnetwork.tv.ui;
import static androidx.leanback.app.BackgroundManager.getInstance;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.leanback.app.BackgroundManager;
import androidx.leanback.app.BrowseFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlight;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.OnResponseReceived;
import com.directsportsnetwork.tv.api.TvApplication;
import com.directsportsnetwork.tv.api.Utils;
import com.directsportsnetwork.tv.model.Team;
import com.directsportsnetwork.tv.presenter.TeamPresenter;
import com.directsportsnetwork.tv.provider.DataBaseHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class TeamSclFragment extends BrowseFragment implements OnResponseReceived {
private final String TAGS = "TeamSclFragment";
private final Handler mHandler = new Handler();
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private Timer mBackgroundTimer;
private URI mBackgroundURI;
private URI defaultBackgroundURI;
public Team selectedTeam;
private JSONArray teamData;
private HashMap<String, Integer> teamTrnMap;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private boolean isFavoriteDisable(String teamId) {
return !(teamTrnMap != null && teamTrnMap.get(teamId) != null);
}
private int getTrnByTeamId(String teamId) {
return teamTrnMap.get(teamId);
}
#Override
public void onResponseData(JSONArray data, HashMap<String, Integer> teamTrnMap) {
try {
Log.e(TAGS, "apiResponse: " + data);
teamData = data;
this.teamTrnMap = teamTrnMap;
prepareBackgroundManager();
setupUIElements();
// Set rows as per data fetched form API
loadTeamRows(teamData);
setupEventListeners();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != mBackgroundTimer) {
mBackgroundTimer.cancel();
}
}
#Override
public void onResume() {
super.onResume();
if (TvApplication.isFavChanged && teamData != null) {
loadTeamRows(teamData);
TvApplication.isFavChanged = false;
if (getView() != null) {
getView().requestFocus();
setSelectedPosition(0, true);
startBackgroundTimer();
}
}
}
#Override
public void onPause() {
super.onPause();
}
public void onMyKeyDown(int keyCode, KeyEvent event) {
//do whatever you want here
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
getActivity().finish();
getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
break;
}
}
private void loadTeamRows(JSONArray teamCategoryList) {
try {
ArrayList<Team> favTeamList = new ArrayList<>();
if (Utils.isStoragePermissionGranted(getActivity())) {
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
favTeamList = dataBase.getAllFavorites();
} else {
favTeamList.add(null);
Utils.showToast(getActivity(), getResources().getString(R.string.no_storage_permission));
}
ListRowPresenter mListRowPresenter = new ListRowPresenter(FocusHighlight.ZOOM_FACTOR_NONE, true);
ArrayObjectAdapter mRowsAdapter = new ArrayObjectAdapter(mListRowPresenter);
TeamPresenter teamPresenter = new TeamPresenter();
for (int i = 0; i < teamCategoryList.length() + 1; i++) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(teamPresenter);
if (i == 0) {
// This is to create Favorite card row
for (int index = 0; index < favTeamList.size(); index++) {
if (favTeamList.get(index) == null) {
listRowAdapter.add(getResources().getString(R.string.favorites));
} else {
Team team = favTeamList.get(index);
team.setIsFavorite(1);
if (isFavoriteDisable(team.getId())) {
// TODO: Team is disabled, remove it from favorites
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
dataBase.removeFavorite(team.getId());
TvApplication.isFavChanged = true;
continue;
} else {
team.setReleaseNo(getTrnByTeamId(team.getId()));
}
listRowAdapter.add(team);
}
}
HeaderItem header = new HeaderItem(i, "Favorites");
mRowsAdapter.add(new ListRow(header, listRowAdapter));
} else {
JSONArray teamList = teamCategoryList.getJSONObject(i - 1).getJSONArray("team");
String category = teamCategoryList.getJSONObject(i - 1).getString("name");
String categoryId = teamCategoryList.getJSONObject(i - 1).getString("id");
for (int index = 0; index < teamList.length(); index++) {
JSONObject teamObj = teamList.getJSONObject(index);
String id = teamObj.getString("id");
String name = teamObj.getString("name");
String shortdesc = teamObj.getString("shortdesc");
String longdesc = teamObj.getString("longdesc");
int trn = teamObj.getInt("trn");
//trn stands for Team Release Number
Team team = new Team();
team.setCatId(categoryId);
team.setCatName(category);
team.setId(id);
team.setName(name);
team.setShortdesc(shortdesc);
team.setLongdesc(longdesc);
team.setIsFavorite(0);
team.setReleaseNo(trn);
if (category.equalsIgnoreCase("NASCAR")) {
team.setIsNascar(1);
} else {
team.setIsNascar(0);
}
listRowAdapter.add(team);
}
HeaderItem header = new HeaderItem(i, category);
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
}
setAdapter(mRowsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void prepareBackgroundManager() {
BackgroundManager mBackgroundManager = getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mDefaultBackground = ContextCompat.getDrawable(getActivity(), R.drawable.default_background);
mBackgroundManager.setColor(Color.BLACK);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
private void setupUIElements() {
getTitleView().setVisibility(View.GONE);
// To hide left side header for BrowseFragment
setHeadersState(HEADERS_DISABLED);
setHeadersTransitionOnBackEnabled(true);
}
private void setupEventListeners() {
setOnItemViewClickedListener(new ItemViewClickedListener());
setOnItemViewSelectedListener(new ItemViewSelectedListener());
}
protected void updateBackground(String uri) {
try {
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
final TeamSclActivity activity = ((TeamSclActivity) getActivity());
if (activity.getTopShelfImg().getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_start).getConstantState() && (uri == defaultBackgroundURI.toString())) {
} else {
//start
if (activity != null) {
Glide.with(activity).load(uri).error(mDefaultBackground).placeholder(R.drawable.teamblank).into(new CustomTarget<Drawable>(width, height) {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
activity.getTopShelfImg().setImageDrawable(resource);
Utils.crossfade(activity.getTopShelfImg());
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
//end
}
mBackgroundTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startBackgroundTimer() {
if (mBackgroundTimer != null) {
mBackgroundTimer.cancel();
}
mBackgroundTimer = new Timer();
mBackgroundTimer.schedule(new UpdateBackgroundTask(), Utils.BACKGROUND_UPDATE_DELAY);
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = (Team) item;
Intent intent = new Intent(getActivity(), TeamChnlActivity.class);
intent.putExtra(Utils.EXTRA_TEAM, team);
startActivity(intent);
} else if (item instanceof String) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.favorite_alert_msg));
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
#Override
public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = ((Team) item);
try {
selectedTeam = team;
mBackgroundURI = new URI(team.getTopShelfImageUrl(team.getId(), team.getReleaseNo()));
defaultBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?");
if (team.getIsFavorite() == 1) {
startBackgroundTimer();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (item instanceof String) {
try {
selectedTeam = null;
Random random = new Random();
mBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?" + random.nextInt(100));
defaultBackgroundURI = mBackgroundURI;
startBackgroundTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class UpdateBackgroundTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
if (mBackgroundURI != null) {
updateBackground(mBackgroundURI.toString());
}
}
});
}
}
}
My activity_teamscl.xml code -
<?xml version="1.0" encoding="utf-8"?>
<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">
<fragment
android:id="#+id/main_browse_fragment"
android:name="com.directsportsnetwork.tv.ui.TeamSclFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignTop="#+id/center_baseline"
tools:context=".ui.TeamSclActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />
</RelativeLayout>

Error on MediaPlayer.onCreate method / Android Music app

I have problem with my music app. I have made a MediaPlayer and application is crashing on this:
2021-08-03 22:54:09.621 6494-6494/com.example.musiclistenerremake E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.musiclistenerremake, PID: 6494
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musiclistenerremake/com.example.musiclistenerremake.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.musiclistenerremake.PlayerActivity.getIntentMethod(PlayerActivity.java:106)
at com.example.musiclistenerremake.PlayerActivity.onCreate(PlayerActivity.java:36)
...
Full logcat log:
2021-08-03 22:54:09.621 6494-6494/com.example.musiclistenerremake E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.musiclistenerremake, PID: 6494
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.musiclistenerremake/com.example.musiclistenerremake.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.musiclistenerremake.PlayerActivity.getIntentMethod(PlayerActivity.java:106)
at com.example.musiclistenerremake.PlayerActivity.onCreate(PlayerActivity.java:36)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
2021-08-03 22:54:15.300 6494-6509/com.example.musiclistenerremake W/MediaPlayer-JNI: MediaPlayer finalized without being released
In my opinion I did initialize MediaPlayer correctly, I tried to move mediaPlayer before if statement (I don't know why I thought it will help) only, don't have idea what is wrong here.
Im using Android API 29.
private void getIntentMethod() {
position = getIntent().getIntExtra("position", -1);
listSongs = musicFiles;
if (listSongs != null)
{
playPauseBtn.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(listSongs.get(position).getPath());
}
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
else
{
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
Here is full code of this activity (PlayerActivity):
package com.example.musiclistenerremake;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import static com.example.musiclistenerremake.MainActivity.musicFiles;
public class PlayerActivity extends AppCompatActivity {
TextView song_name, artist_name, duration_played, duration_total;
ImageView cover_art, nextBtn, prevBtn, backBtn, shuffleBtn, repeatBtn;
FloatingActionButton playPauseBtn;
SeekBar seekBar;
int position = -1;
static ArrayList<MusicFiles> listSongs = new ArrayList<>();
static Uri uri;
static MediaPlayer mediaPlayer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initViews();
getIntentMethod();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser)
{
mediaPlayer.seekTo(progress * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
PlayerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mediaPlayer != null)
{
int mCurrentPosition = mediaPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
duration_played.setText(formattedTime(mCurrentPosition));
}
handler.postDelayed(this, 1000);
}
});
}
private String formattedTime(int mCurrentPosition) {
String totalOut = "";
String totalNew = "";
String seconds = String.valueOf(mCurrentPosition % 60);
String minutes = String.valueOf(mCurrentPosition / 60);
totalOut = minutes + ":" + seconds;
totalNew = minutes + ":" + "0" + seconds;
if (seconds.length() == 1)
{
return totalNew;
}
else
{
return totalOut;
}
}
private void getIntentMethod() {
position = getIntent().getIntExtra("position", -1);
listSongs = musicFiles;
if (listSongs != null)
{
playPauseBtn.setImageResource(R.drawable.ic_baseline_pause_24);
uri = Uri.parse(listSongs.get(position).getPath());
}
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
else
{
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
seekBar.setMax(mediaPlayer.getDuration() / 1000);
}
private void initViews() {
song_name = findViewById(R.id.song_name);
artist_name = findViewById(R.id.song_artist);
duration_played = findViewById(R.id.durationPlayed);
duration_total = findViewById(R.id.durationTotal);
cover_art = findViewById(R.id.cover_art);
nextBtn = findViewById(R.id.id_next);
prevBtn = findViewById(R.id.id_prev);
backBtn = findViewById(R.id.back_btn);
shuffleBtn = findViewById(R.id.shuffle);
repeatBtn = findViewById(R.id.id_repeat);
playPauseBtn = findViewById(R.id.play_pause);
seekBar = findViewById(R.id.seekBar);
}
}
Don't use mediaplayer.release()
because after resetting player after mediaplayer.reset() is uninitialized state and if the player is not initialized then it will throw an exception

I/Choreographer: Skipped 8 frames! The application may be doing too much work on its main thread [duplicate]

This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
my app is not fetching the data from my database. it shows a blank text view and says the errors on logcat which is given below.... please help me. I am on the deadline for the work.....
2020-02-26 11:53:30.062 29392-29392/com.example.d_specs I/TextToSpeech: Sucessfully bound to com.google.android.tts
2020-02-26 11:53:30.070 29392-29418/com.example.d_specs D/ColorExSystemServiceHelper: checkColorExSystemService className = com.google.android.tts.service.GoogleTTSService
2020-02-26 11:53:30.075 29392-29392/com.example.d_specs D/WindowManager: Add to mViews: DecorView#fa8568c[SecondOneActivity], this = android.view.WindowManagerGlobal#b0c7f51,pkg= com.example.d_specs
2020-02-26 11:53:30.083 29392-29392/com.example.d_specs I/TextToSpeech: Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
2020-02-26 11:53:30.091 29392-29497/com.example.d_specs I/TextToSpeech: Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
2020-02-26 11:53:30.264 29392-29392/com.example.d_specs I/Choreographer: Skipped 8 frames! The application may be doing too much work on its main thread.
2020-02-26 11:53:30.553 29392-29392/com.example.d_specs D/SurfaceView: 238649477 updateRequestedVisibility, mViewVisibility:true, mWindowVisibility:false, mWindowStopped:false by android.view.SurfaceView.onWindowVisibilityChanged:292 android.view.View.dispatchWindowVisibilityChanged:13970 android.view.ViewGroup.dispatchWindowVisibilityChanged:1580 android.view.ViewGroup.dispatchWindowVisibilityChanged:1580 android.view.ViewGroup.dispatchWindowVisibilityChanged:1580 android.view.ViewGroup.dispatchWindowVisibilityChanged:1580 android.view.ViewGroup.dispatchWindowVisibilityChanged:1580 android.view.ViewGroup.dispatchWindowVisibilityChanged:1580
2020-02-26 11:53:30.553 29392-29392/com.example.d_specs I/SurfaceView: 238649477 Changes: creating=false format=false size=false visible=true left=false top=false
2020-02-26 11:53:30.553 29392-29392/com.example.d_specs I/SurfaceView: 238649477 Cur surface: Surface(name=null)/#0xfeb1e8, visible=false
2020-02-26 11:53:30.555 29392-29392/com.example.d_specs I/SurfaceView: 238649477 visibleChanged:true -> SurfaceHolder.Callback.surfaceDestroyed
2020-02-26 11:53:30.557 29392-29392/com.example.d_specs V/SurfaceView: Layout: x=0 y=264 w=1094 h=1944, frame=Rect(0, 0 - 1094, 1944)
2020-02-26 11:53:30.559 29392-29480/com.example.d_specs D/SurfaceView: 135700481 windowPositionLost, frameNr = 0
2020-02-26 11:53:30.576 29392-29392/com.example.d_specs D/SurfaceView: 238649477 updateRequestedVisibility, mViewVisibility:true, mWindowVisibility:false, mWindowStopped:true by android.view.SurfaceView.windowStopped:264 android.view.ViewRootImpl.setWindowStopped:1722 android.view.WindowManagerGlobal.setStoppedState:685 android.app.Activity.performStop:8206 android.app.ActivityThread.callActivityOnStop:4899 android.app.ActivityThread.performStopActivityInner:4877 android.app.ActivityThread.handleStopActivity:4959 android.app.servertransaction.StopActivityItem.execute:41
2020-02-26 11:54:08.979 29392-29392/com.example.d_specs I/Choreographer: Skipped 2 frames! The application may be doing too much work on its main thread.
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import java.util.ArrayList;
import java.util.Locale;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class SecondOneActivity extends AppCompatActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
private static final String TAG = "SampleActivity";
private GestureDetectorCompat GestureDetect;
private TextToSpeech tts;
TextToSpeech txt;
//array declaration
ArrayList<String> array1;
ArrayList<String> array2;
//global variable
String glo;
String nameget;
String priceget;
TextView text;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
DatabaseReference databasefetch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_one);
Bundle bundle = getIntent().getExtras(); //get the intent and data passed
//next check that bundle is not null
if (bundle != null) {
String scanResult = bundle.getString("SCAN_RESULT");
//try loging out the value
Log.i("value", scanResult);
glo = scanResult;
}
//typeCast
long l = Long.parseLong(glo);
//initialize arraylists
array1 = new ArrayList<String>();
array2 = new ArrayList<String>();
txt=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status!=TextToSpeech.ERROR)
{
txt.setLanguage(Locale.UK);
}
}
});
GestureDetect = new GestureDetectorCompat(this,this);
GestureDetect.setOnDoubleTapListener(this);
text = (TextView) findViewById(R.id.textView3);
//database initialize
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
//database data fetching : from here onwards
//database query as "select * from save where id=l;
databasefetch = FirebaseDatabase.getInstance().getReference().child("DPOS");
Query query = databasefetch.orderByChild("id").equalTo(l);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.i("TAG", "sujith annan");
String name = snapshot.child("name").getValue().toString();
String details = snapshot.child("details").getValue().toString();
String price = snapshot.child("price").getValue().toString();
// nameget = name;
// priceget = price;
text = (TextView) findViewById(R.id.textView3);
//to print
text.setText("\nProduct Name : " + name + "\nDetails : " + details + "\nPrice : " + price);
//text to speech
String toSpeak = text.getText().toString();
Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
txt.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
GestureDetect.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
//text to speech
String toSpeak = text.getText().toString();
Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
txt.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Intent intent=new Intent(SecondOneActivity.this,SecondActivity.class);
startActivity(intent);
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
#Override
public boolean onDown(MotionEvent e) {
return false;
}
#Override
public void onShowPress(MotionEvent e) {
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
#Override
public void onLongPress(MotionEvent e) {
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Toast.makeText(this,"Item saved for billing",Toast.LENGTH_SHORT).show();
array1.add(nameget);
array2.add(priceget);
return false;
}
#Override
public void onBackPressed() {
Intent in =new Intent(this,BillingActivity.class);
in.putStringArrayListExtra("arr1",array1);
in.putStringArrayListExtra("arr2",array2);
startActivity(in);
super.onBackPressed();
}
}
You are doing too much task on Main Thread. Because android application run one thread which manages GUI.
In you code you calling "Firebase" on Main Thread. That's why it misses some frames to render on screen.
If many frames misses then sometimes your "UI" is frozen. Avoid to
call web-services or DB operation on Main Thread.
To avoid this you can use "AsyncTask" or Service to perform this task.
Thanks

Value on Spinner can't post to databae mySql

logcat doesn't give me a specific error, it only shows the error location, which is on line 155 {id_status = spStatus.getSelectedItem().toString();}
I don't know the right keyword to solve the error. I've been browsing, and I think this is the same as the tutorial I followed. where is my mistake? give me more detailed instructions
my java like this:
package src.bkkpost.loker;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import src.bkkpost.MainActivity;
import src.bkkpost.R;
import src.bkkpost.loker.adapter.AdapterStatus;
import src.bkkpost.model.Value;
import src.bkkpost.util.BaseApiService;
import src.bkkpost.util.SharedPrefManager;
import src.bkkpost.util.UtilsApi;
public class UpdateLoker extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//string spinner kelamin
String[] idStatus = {"10", "20"};
String[] nama_status = {"Buka", "Tutup"};
//string spinner kelamin
String[] id_kelamin = {"5001", "5002", "5003"};
String[] nama_kelamin = {"Pria/Wanita", "Pria", "Wanita"};
//string spinner pendidikan
String[] pendidikan_id = {"3001", "3002", "3003", "30004", "3005", "3006", "3007"};
String[] nama_pendidikan = {"SD", "SMP", "SMA", "SMK ", "Diploma/(D3)", "Sarjana/(S1)", "Master/(S2)"};
//string spinner pendidikan
String[] jurusan_id = {"30001", "300301", "300302", "3000401", "3000402", "3000403", "3000404",
"3000405", "3000406", "3000407", "3000408", "3000409", "3000410", "3000411", "3000412", "3000413", "3000414",
"3000415", "300501", "300502", "300503", "300504", "300505", "300506", "300075"};
String[] nama_jurusan = {"Semua Jurusan", "IPA", "IPS", "Administrasi Perkantoran ", "Akuntansi ", "ANalisis Kimia ",
"Animasi ", "Broadcasting ", "Elektronik ", "Farmasi ", "Multimedia ", "Otomotif ", "Pariwisata ", "Pemasaran ",
"Perbankan ", "Perhotelan", "Tata Boga ", "Tata Busana ", "Perpajakan(D3/S1) ", "Broadcasting(D3/S1)", "Teknik Mesin(D3/S1)",
"Pariwisata(D3/S1)", "Sekretaris (D3/S1)", "Hubungan Masyarakat (D3/S1)", "Akuntansi(D3/S1) "};
AutoCompleteTextView date;
DatePickerDialog datePickerDialog;
BaseApiService mApiservice;
ProgressDialog loading;
Context mContex;
SharedPrefManager sharedPrefManager;
public static final String URL = "http://192.168.43.164/gokerja/";
private ProgressDialog progress;
String bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status;
#BindView(R.id.post_btn_upload)
Button btnUpload;
#BindView(R.id.post_bkk_id)
TextView tvBkkid;
#BindView(R.id.post_posisi)
AutoCompleteTextView etPosisi;
#BindView(R.id.post_namaperusahaan)
AutoCompleteTextView etNamaperusahan;
#BindView(R.id.post_alamat_pt)
AutoCompleteTextView etAlamat;
#BindView(R.id.post_tanggal)
AutoCompleteTextView etTangggal;
#BindView(R.id.post_spin_statusup)
Spinner spStatus;
#OnClick(R.id.post_btn_upload)
void daftar() { }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loker_update_loker);
ButterKnife.bind(this);
sharedPrefManager = new SharedPrefManager(this);
tvBkkid.setText(sharedPrefManager.getSPNama());
mApiservice = UtilsApi.getAPIService();
mContex = this;
date = (AutoCompleteTextView) findViewById(R.id.post_tanggal);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final java.util.Calendar c = java.util.Calendar.getInstance();
int mYear = c.get(java.util.Calendar.YEAR);
int mMont = c.get(Calendar.MONTH);
int mDay = c.get(java.util.Calendar.DAY_OF_MONTH);
//date picker dialog
datePickerDialog = new DatePickerDialog(UpdateLoker.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int month, int dayOfMonth) {
date.setText(year + "-"
+ (month + 1) + "-" + dayOfMonth);
}
}, mYear, mMont, mDay);
datePickerDialog.show();
}
});
//get spinner status
final Spinner spinnerStatus = (Spinner) findViewById(R.id.post_spin_statusup);
spinnerStatus.setOnItemSelectedListener(this);
AdapterStatus adapterStatus = new AdapterStatus(getApplicationContext(), idStatus);
spinnerStatus.setAdapter(adapterStatus);
progress = new ProgressDialog(this);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etPosisi.getText().toString().equals("")) {
etPosisi.setError("Posisi harus di isi");
} else if (etNamaperusahan.getText().toString().equals("")) {
etNamaperusahan.setError("Perusahaan harus di isi");
} else if (etAlamat.getText().toString().equals("")) {
etAlamat.setError("alamat harus di isi");
} else {
//Untuk menampilkan progress dialog
progress.setCancelable(false);
progress.setMessage("Loading...");
progress.show();
bkk_id = tvBkkid.getText().toString();
posisi = etPosisi.getText().toString();
nama_pt = etNamaperusahan.getText().toString();
alamat_pt = etAlamat.getText().toString();
waktu_buka = etTangggal.getText().toString();
id_status = spStatus.getSelectedItem().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BaseApiService api = retrofit.create(BaseApiService.class);
Call<Value> call = api.post_loker(bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
String message = response.body().getMessage();
progress.dismiss();
if (value.equals("1")) {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Iklan Lowongan kerja telah berhasil dibuat");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, MainActivity.class));
dialog.dismiss();
}
});
alert.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Terjadi Kesalahan Jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, UpdateLoker.class));
dialog.dismiss();
}
});
alert.show();
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
t.printStackTrace();
progress.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Error 301");
alert.setMessage("Terjadi kesalahan jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
//Toast.makeText(UpdateLoker.this, "semelekete", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
this my Logcat
09-04 17:13:15.904 16015-16015/src.bkkpost D/AndroidRuntime: Shutting down VM
09-04 17:13:15.904 16015-16015/src.bkkpost W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x419f3d58)
--------- beginning of /dev/log/system
09-04 17:13:15.904 16015-16015/src.bkkpost E/AndroidRuntime: FATAL EXCEPTION: main
Process: src.bkkpost, PID: 16015
java.lang.NullPointerException
at src.bkkpost.loker.UpdateLoker$2.onClick(UpdateLoker.java:155)
at android.view.View.performClick(View.java:4444)
at android.view.View$PerformClick.run(View.java:18457)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5113)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)

starting my countdown clock when activity is open

I am a bit of a keen novice at Android! I have a snippet of code for timer I want to use in my app however it works when the button is clicked and I want it to work when I open the activity that it is on. I have tried so many solutions but cannot get it to operate. Would really appreciate any help, I have tried putting an if statement in, I have tried using the onStart, and putting it the OnCreate all with no joy. The closest I can get is that it just starts with "Time Up!" in the field.
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
Button buttonStartTime;
TextView textViewShowTime;
CountDownTimer countDownTimer;
long totalTimeCountInMilliseconds;
long timeBlinkInMilliseconds;
boolean blink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getReferenceOfViews ();
setActionListeners ();
totalTimeCountInMilliseconds = 60 * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void setActionListeners() {
buttonStartTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewShowTime.setTextAppearance(getApplicationContext(), R.style.normalText);
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if ( leftTimeInMilliseconds < timeBlinkInMilliseconds ) {
textViewShowTime.setTextAppearance(getApplicationContext(), R.style.blinkText);
if ( blink ) {
textViewShowTime.setVisibility(View.VISIBLE);
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
textViewShowTime.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));
}
#Override
public void onFinish()
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
}
}.start();
}
}
);
}
private void getReferenceOfViews() {
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
}
}
You can modify your onResume() as :
#Override
public void onResume(){
buttonStartTime.performClick();
super.onResume();
}
You should make buttonStartTime a global variable for the class.

Categories