I have a small application Image Slider. There is a scrolling timer for the picture. The timer does not stop if the user is active and scans the images manually. How to pause the timer for the user and resume it in the event that the activity has stopped. Help me please. I'm just starting to study iandroid studio/
MainActivity.java
package com.androidtutorialpoint.androidimageslider;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import me.relex.circleindicator.CircleIndicator;
public class MainActivity extends AppCompatActivity {
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.beast,R.drawable.charles,R.drawable.magneto,R.drawable.mystique,R.drawable.wolverine};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new MyAdapter(MainActivity.this,XMENArray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 2500, 3000);
}
}
You can pause the handler in the activity onPause lifecycle callback. There's an example located here: Android, pausing and resuming handler callbacks
You can then resume the timer in the activity onResume() lifecycle callback.
Related
I am implementing a local database using ROOM in android studio. I am having a problem. I am successful in inserting and deleting the data entries into the database. But when I am getting all the data objects from the database then each time I am getting one object less.
When that activity starts then there is no problem but when I am trying to update the recycler view after inserting a new data object into the database then that object is being updated into the recycler view one step after creating a new data object entry and the same problem happens with this also.
below is my complete code:-
package com.example.eventus.DashBoard;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.example.eventus.ApplicationDatabase.Events.Event;
import com.example.eventus.ApplicationDatabase.Events.EventsAdapter;
import com.example.eventus.ApplicationDatabase.Events.EventsDao;
import com.example.eventus.R;
import com.example.eventus.Singletons.DatabaseSingleton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Dashboard extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
//Declaring the views
private FloatingActionButton fbAddEvent;
private Button btnOKNewEvent, btnCancelNewEvent;
private EditText etDeadlineNewEvent, etTitleNewEvent, etInfoNewEvent;
//For recycler view
private RecyclerView rvEvents;
private RecyclerView.LayoutManager layoutManager;
private List<Event> events;
private EventsAdapter eventsAdapter;
//For alert box
private AlertDialog.Builder alertDialogBuilder;
private AlertDialog alertDialog;
private View alertDialogView;
//For database
private DatabaseSingleton databaseSingleton;
private EventsDao eventsDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//Initializing and setting onclicklisteners on views
init();
//RecyclerView stuff
recyclerViewStuff();
//new event stuff
newEventDialog();
//database stuff
database();
//loadEvents
loadEvents();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.fb_add_event_dashboard:
alertDialog.show();
}
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(mCalendar.getTime());
etDeadlineNewEvent.setText(selectedDate);
}
private void init(){
//Initializing the views
rvEvents = findViewById(R.id.rv_events_dashboard);
fbAddEvent = findViewById(R.id.fb_add_event_dashboard);
//Setting onclicklisteners on views
fbAddEvent.setOnClickListener(this);
}
private void recyclerViewStuff() {
//Initializing the recycler view stuffs
layoutManager = new GridLayoutManager(this, 2);
rvEvents.setLayoutManager(layoutManager);
}
private void newEventDialog() {
alertDialogBuilder = new AlertDialog.Builder(Dashboard.this);
alertDialogView = getLayoutInflater().inflate(R.layout.new_event, null);
alertDialogBuilder.setView(alertDialogView);
alertDialog = alertDialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
//Instantiating the view
btnOKNewEvent = alertDialogView.findViewById(R.id.btn_ok_new_event);
etDeadlineNewEvent = alertDialogView.findViewById(R.id.et_deadline_new_event);
btnCancelNewEvent = alertDialogView.findViewById(R.id.btn_cancel_new_event);
etTitleNewEvent = alertDialogView.findViewById(R.id.et_title_new_event);
etInfoNewEvent = alertDialogView.findViewById(R.id.et_info_new_event);
//setting on click listeners for the views in dialog box
btnOKNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addEvent();
//loadEvents();
refreshEvents();
alertDialog.dismiss();
}
});
btnCancelNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
etDeadlineNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new com.example.eventus.DateAndTime.DatePicker();
datePicker.show(getSupportFragmentManager(), null);
}
});
}
private void database(){
//getting the database instance
databaseSingleton = DatabaseSingleton.getInstance();
//getting the events dao
eventsDao = databaseSingleton.getEventsDao(getApplicationContext());
//deleting all previously saved events
eventsDao.deleteAllEvent();
}
private void addEvent() {
String eventTitle, eventInfo, eventDeadline;
eventTitle = etTitleNewEvent.getText().toString();
eventInfo = etInfoNewEvent.getText().toString();
eventDeadline = etDeadlineNewEvent.getText().toString();
//creating an event
Event event = new Event(eventTitle, eventInfo, eventDeadline);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
eventsDao.createEvent(event);
Toast.makeText(Dashboard.this, "Event Created", Toast.LENGTH_SHORT).show();
}
};
handler.post(runnable);
}
private void loadEvents(){
events = eventsDao.getEvents();
eventsAdapter = new EventsAdapter(events);
rvEvents.setAdapter(eventsAdapter);
}
private void refreshEvents(){
events.clear();
List<Event> tempEventsList = eventsDao.getEvents();
for(int i=0;i<tempEventsList.size();i++){
events.add(tempEventsList.get(i));
}
eventsAdapter.notifyDataSetChanged();
}
}
The problem you are having is realted to concurrency. If you check your code you first call the add event method and place the insertion inside a Runnable, this tells the application to execute at a later time when possible, but it does not execute it inmediately; therefor the code continues its execution, you fetch the events and then, at a later time, the new event is added.
To solve your problem, try to place the call of the method refreshEvents inside the runnable.
Runnable runnable = new Runnable() {
#Override
public void run() {
eventsDao.createEvent(event);
Toast.makeText(Dashboard.this, "Event Created", Toast.LENGTH_SHORT).show();
refreshEvents();
}
};
handler.post(runnable);
EDIT: As correctly said in the comments is not a mult-thread issue, it's the execution time of code fragments inside a single thread.
I made 2D game and it worked just fine. I decided to create a simple "Start Screen" that ought to show high score and "Start" button that should start the game.
I thought I could use just a regular intent to go from one activity to another, but it doesn't work. App simply crashes after I click "Start" button.
I'm using Scene Manager so not all code is written in Game Panel.
Here's my MainActivity
package com.example.korisnik_pc.a2dgame;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Button button;
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // MAKE IT FULLSCREEN
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // REMOVES TOOLBAR
// setting the screen dimensions
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
Constants.SCREEN_HEIGHT = dm.heightPixels;
Constants.SCREEN_WIDTH = dm.widthPixels;
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, GamePanel.class);
startActivity(intent);
}
});
}
Game Panel
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
private MainThread thread;
private SceneManager sceneManager;
public GamePanel(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
sceneManager = new SceneManager();
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new MainThread(getHolder(), this);
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (true) {
try {
thread.setRunning(false);
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
retry = false;
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
sceneManager.receiveTouch(event);
return true;
}
public void update() {
sceneManager.update();
}
public void draw(Canvas canvas) {
super.draw(canvas);
sceneManager.draw(canvas);
}
}
I am trying to create a simple Android stopwatch application. I was having trouble with the application freezing every time I would hit the start button. I learned from reading various things online that the reason it hangs is that I ran a while loop in the UI thread and in order for the application not to crash, that while loop had to be somewhere different. A post on the XDA forums suggested that someone encountering this problem should use an AsyncTask to accomplish this. I am having trouble understanding exactly how to use AsyncTask to do this.
TL;DR: I am trying to count time and then have it update a textview with the corresponding time
Original code with while loop in UI thread
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
Button start, stop, reset;
TextView time;
boolean timeStopped = false;
long timeInNanoSeconds, startTimeInNanoSeconds;
double timer;
public double getTimeInSeconds()
{
timeInNanoSeconds = System.nanoTime() - startTimeInNanoSeconds;
double timeSeconds = (double) timeInNanoSeconds / 1000000000.0;
double roundOff = Math.round(timeSeconds * 100.0) / 100.0;
return roundOff;
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
reset = (Button) findViewById(R.id.resetButton);
time = (TextView) findViewById(R.id.timeField);
start.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
startTimeInNanoSeconds = System.nanoTime();
while(timeStopped == false)
{
double timer = getTimeInSeconds();
String stringTimer = Double.toString(timer);
CharSequence sequenceTimer = stringTimer;
time.setText(sequenceTimer);
}
}
});
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
});
reset.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
time.setText("");
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
EDIT: Working version using Handler
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button start, stop, reset;
TextView time;
Handler m_handler;
Runnable m_handlerTask;
int timeleft = 0;
boolean timeStopped;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.buttonStart);
stop = (Button) findViewById(R.id.buttonStop);
reset = (Button) findViewById(R.id.buttonReset);
time = (TextView) findViewById(R.id.textTime);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
timeStopped = false;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
public void run() {
if(timeStopped == false){
if(timeleft > -1) {
Log.i("timeleft","" + timeleft);
time.setText(String.valueOf(timeleft));
timeleft++;
}
else{
m_handler.removeCallbacks(m_handlerTask);
}
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeStopped = true;
m_handler.removeCallbacks(m_handlerTask);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeStopped = true;
m_handler.removeCallbacks(m_handlerTask);
timeleft = 0;
time.setText(String.valueOf(timeleft));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
doInbackground is invoked on the background thread. you cannot update ui from a background
time.setText(sequenceTimer);
// should be in a ui thread.
Use runOnUithread or setText in onPostExecute.
You can use a Handler , a timer task or a CountDowntimer depending on your requirement.
Android Thread for a timer
Edit:
Using Handler
public class MainActivity extends Activity
{
Button start;
TextView time;
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
time = (TextView)findViewById(R.id.textView1);
start.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
time.setText(String.valueOf(timeleft));
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
}
});
}
}
In my opinion AsyncTask is not fit for you, as this in my mind is a single shot action.
I would suggest something like this:
private ScheduledExecutorService exec;
private void startExec() {
shutDownExec();
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
// this starts immediately and is run once every minute
double timer = getTimeInSeconds();
String stringTimer = Double.toString(timer);
CharSequence sequenceTimer = stringTimer;
runOnUiThread(new UpdateUI(R.id.yourtime_textview, sequenceTimer));
}
}, 0, 1, TimeUnit.MINUTES); // adjust how often run() is executed here
}
private void shutDownExec() {
if (exec != null && !exec.isTerminated()) {
exec.shutdown();
}
}
private class UpdateUI implements Runnable {
private String mText;
private TextView mTv;
public UpdateUI(int textviewid, String text) {
this.mTv = (TextView) findViewById(textviewid);
this.mText = text;
}
#Override
public void run() {
mTv.setText(mText);
}
}
I had to do a similar task lately I used created a separate thread with the following code. It lets you update at set time intervals which I think would be suited to your task.
Hope it helps.
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
public class AutomationTreadClass {
Activity refToUIActivity;
//Declare the timer
Timer t = new Timer();
//pass UI activity so you can call update on it
AutomationTreadClass( Activity callingActivity ){
refToUIActivity = callingActivity;
startTimerTread();
}
private void startTimerTread(){
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//do any updates to the time you need to do here
updateLevelMeter();
}
},
//Start Time of thread
0,
//interval of updates
30);
}
private void updateLevelMeter() {
refToUIActivity.runOnUiThread(new Runnable() {
public void run() {
//access what ever UI comment you need to here. like giving you textview a value.
}
});
}
}
I want to create a small android app that would show the system time in periodic intervals after clicking on a button ( i.e. setting the activity up )...The code for button creation and setting the periodic activity via Intent goes like this :
package com.example.timeupdate;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
TextView show;
#Override
protected void onCreate(Bundle I_Love_Biriyani) {
super.onCreate(I_Love_Biriyani);
setContentView(R.layout.activity_main);
button = (Button) findViewById (R.id.pressButton);
show = (TextView) findViewById (R.id.Show);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent openTimeUpdater = new Intent("com.example.timeupdate.TIMEUPDATER");
startActivity(openTimeUpdater);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here is the code for repeating the timer( for say 5 seconds ) where I used TimerTask class to perform the job :
package com.example.timeupdate;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TimeUpdater extends Activity {
TextView Show;
TimerTask timer= new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
Date d = new Date();
Show.setText(""+d);
}
};
#Override
protected void onCreate(Bundle hotovaga) throws IllegalStateException {
// TODO Auto-generated method stub
super.onCreate(hotovaga);
setContentView(R.layout.new_update);
Show = (TextView) findViewById (R.id.time);
Timer t = new Timer();
t.scheduleAtFixedRate(timer , 0 , 5000);
}
}
After clicking on the button the time is shown only once then application is getting stopped showing a dialog-message. Need explanations to do this job in the same fashion.
You are trying to access an UI element inside non-UI thread.
Show.setText(""+d);
Instead, wrap it up in runOnUiThread interface to get proper output.
Use below code for your TimeUpdater class
public class TimeUpdater extends Activity {
TextView Show = null;
Calendar c;
int seconds;
int minutes;
int hours;
TimerTask timer= new TimerTask(){
#Override
public void run() {
c = Calendar.getInstance();
seconds = c.get(Calendar.SECOND);
minutes = c.get(Calendar.MINUTE);
hours = c.get(Calendar.HOUR);
runOnUiThread(new Runnable() {
#Override
public void run() {
Show.setText(hours + ":" + minutes + ":" + seconds);
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_update);
Show = (TextView) findViewById (R.id.time);
Timer t = new Timer();
t.scheduleAtFixedRate(timer , 0 , 5000);
}
}
Using an actual Timer (java.util.Timer) in conjunction with runOnUiThread() is one way to solve this issue, and below is an example of how to implement it.
public class myActivity extends Activity {
private Timer myTimer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
// Set your textView data here.
//Do something to the UI thread here
}
};
}
use PeriodicTask from Play-Service, it is the newest tool from Google to schedule a job background.
I've built a splash screen that loads a (splash) activity and then starts another activity and it works fine. (I've attached it below - it's called SPLASH 1)
I created another splash screen to replace this one which is supposed to only run once - then after creating a SharedPreferences boolean it is supposed to load another activity. Everything seems fine with this but now when it loads the new activity, none of the menuitems appear. I have no idea what changed in SPLASH 2 - but something in there is causing the MenuItems not to appear after it loads the exact same activity SPLASH 1 does (NEWCORE.JAVA)
I'm really not sure what is going on here - any help is greatly appreciated!
(please let me know if any additional info is needed)
SPLASH 1. (WORKING)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import com.nfc.linkingmanager.R;
public class SplashScreen extends Activity {
private boolean mIsBackButtonPressed;
private static final int SPLASH_DURATION = 1000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
// make sure we close the splash screen so the user won't come back when it presses back key
finish();
if (!mIsBackButtonPressed) {
// start the home screen if the back button wasn't pressed already
Intent intent = new Intent(SplashScreen.this, NewCore.class);
SplashScreen.this.startActivity(intent);
}
}
}, SPLASH_DURATION); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
#Override
public void onBackPressed() {
// set the flag to true so the next activity won't start up
mIsBackButtonPressed = true;
super.onBackPressed();
}
}
SPLASH 2 (NOT WORKING - CAUSES MENUITEMS not to appear on the activity it loads)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import com.nfc.linkingmanager.R;
import android.content.SharedPreferences;
import java.lang.Object;
import android.preference.PreferenceManager;
public class SplashScreen extends Activity
{
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
Intent i = new Intent(SplashScreen.this, AppActivity.class);
SplashScreen.this.startActivity(i);
this.finish();
}
};
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("first_time", false))
{
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
Intent i = new Intent(SplashScreen.this, NewCore.class);
this.startActivity(i);
this.finish();
}
else
{
this.setContentView(R.layout.country_list);
handler.sendEmptyMessageDelayed(0, 2000);
}
}
}
NEWCORE.JAVA (Connected to by both Splash Screens - Only missing MenuItems when using SPLASH 2)
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class NewCore extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// map each name to a TextView
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(NewCore.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetContacts().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(NewCore.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllContacts();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent addContact = new Intent(NewCore.this, NewCore.class);
startActivity(addContact);
return super.onOptionsItemSelected(item);
}
OnItemClickListener viewConListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent viewCon = new Intent(NewCore.this, NewCore.class);
viewCon.putExtra(ROW_ID, arg3);
startActivity(viewCon);
}
};
}
Create a new activity which extends the Android Activity class, and place your menu handling in there. Then, extend the new activity in your other activities - thus ensuring that the menu handling is consistent. For lists, you could create a second new activity which extends ListActivity, or grab the ListActivity code and just make that extend your previous activity with the menus.
In Splash 2 put
SetContentView(R.layout.country_list);
just below
super.onCreate(savedInstanceState);