Progress Dialog on Rajawali Vuforia example - progressdialog

It is possible to show progress dialog when loading the .obj model. I tried to call the ProgressDialog in RajawaliVuforiaExampleRenderer.java but it said "Can't create handler inside thread that has not called Looper.prepare()"
I have pasted part of the code here:
protected void initScene() {
mLight = new DirectionalLight(.1f, 0, -1.0f);
mLight.setColor(1.0f, 0, 0);
mLight.setPower(1);
getCurrentScene().addLight(mLight);
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),
mTextureManager, R.raw.wall_obj);
try {
// Load model
objParser.parse();
wall = objParser.getParsedObject();
addChild(wall);
} catch (Exception e) {
e.printStackTrace();
}
}
EDITED:
I have read the comment from Abhishek Agarwal and updated the code for Renderer part, now i having problem on calling the ProgressDialog when loading the model, here is my code for the UI thread.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// receive file path
String filePath = this.getIntent().getStringExtra("FullFilePath");
Log.i(filePath, "FullFilePath:" + filePath);
waitDialog = ProgressDialog.show(this, "", "Loading", true);
waitDialog.show();
new ModelLoader().execute();
}
#Override
protected void setupTracker() {
int result = initTracker(TRACKER_TYPE_MARKER);
if (result == 1) {
result = initTracker(TRACKER_TYPE_IMAGE);
if (result == 1) {
super.setupTracker();
} else {RajLog.e("Couldn't initialize image tracker.");
}
} else {
RajLog.e("Couldn't initialize marker tracker.");
}}
protected void initApplicationAR() {
super.initApplicationAR();
createImageMarker("marker.xml");
}
protected void initRajawali() {
super.initRajawali();
mRenderer = new ModelRenderer(this);
mRenderer.setSurfaceView(mSurfaceView);
super.setRenderer(mRenderer);
mUILayout = this;
mUILayout.setContentView(mLayout, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
private class ModelLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
startVuforia();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
waitDialog.dismiss();
}
}

Progress Dialog can be shown on the UIThread. So show progress dialog on the main thread not under GLThread

You can use Handler to be on threadUI :
`private Handler mHandler = new Handler();
...
mHandler.post(new Runnable() {
#Override
public void run() {
view_progressBar.setProgress(val);
}
});`

Related

Interstitial ads for coco2d android game

I'm facing a lot of difficulties to show the Interstitial, it's my first time working with the Cocos2D game.
This is all main java code
public class FlyingPanda extends Activity implements AdListener {
/** Called when the activity is first created. */
public static CCGLSurfaceView mGLSurfaceView;
private boolean isCreated = false;
private static final String ADMOB_PUBLISH_ID = "xxxxxxxxxxxxxxxxxx";
#Override
public void onCreate(Bundle savedInstanceState) {
if( !isCreated ){
isCreated = true;
} else {
return;
}
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mGLSurfaceView = new CCGLSurfaceView(this);
// Create the adView
AdView adView = new AdView(this, AdSize.BANNER, ADMOB_PUBLISH_ID);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
adView.setAdListener(this);
// Add the adView to it
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
layout.addView(mGLSurfaceView);
layout.addView(adView);
setContentView(layout);
Common.game_initialize();
getScaledCoordinate();
CCDirector.sharedDirector().attachInView(mGLSurfaceView);
// attach the OpenGL view to a window
Common.sound_engine = SoundEngine.sharedEngine();
loadSound();
What am I supposed to add here in admob setting? I'll define a variable named interstitial like the banner or what?
////////////////////////////////////////////////////////////////////////////////
// Admob Setting
////////////////////////////////////////////////////////////////////////////////
How can I Load interstitial in all this public classes?
#Override
public void onDismissScreen(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad ad, ErrorCode errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad ad) {
MainActivity.java:
public class AppActivity extends Cocos2dxActivity {
private static final String ADMOB_INTERSTITIAL = "ca-app-pub-2575683230512628/5833084223";
private InterstitialAd admobInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_appActivity = this;
admobInterstitial = new InterstitialAd(this);
admobInterstitial.setAdUnitId(ADMOB_INTERSTITIAL);
admobInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
admobInterstitial.loadAd(newAdRequest());
}
});
admobInterstitial.loadAd(newAdRequest());
}
public static void showInterstitial(final String adSdk){
Log.d("ADMOB INTERSTITIAL", "showInterstitial: " + adSdk);
_appActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(adSdk.equalsIgnoreCase("admob")){
if(_appActivity.admobInterstitial != null){
if(_appActivity.admobInterstitial.isLoaded()){
_appActivity.admobInterstitial.show();
}
}
}
else if(adSdk.equalsIgnoreCase("chartboost")){
}
else if(adSdk.equalsIgnoreCase("revmob")){
}
else{
Log.w("INTERSTITIAL", "unknown ad to show: " + adSdk);
}
}
});
}
private AdRequest newAdRequest(){
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("YOUR_DEVICE_ID")
.build();
return adRequest;
}
}
c++ code (.c file):
const char* AppActivityClassName = "org/cocos2dx/cpp/AppActivity";
bool NativeHelper::instanceFlag = false;
NativeHelper* NativeHelper::instance = NULL;
NativeHelper* NativeHelper::getInstance(){
if(!instanceFlag){
instance = new NativeHelper();
instanceFlag = true;
}
return instance;
}
void NativeHelper::showInterstitial(string adSdk){
cocos2d::JniMethodInfo t;
if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "showInterstitial", "(Ljava/lang/String;)V")){
jstring stringArg = t.env->NewStringUTF(adSdk.c_str());
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
c++ code (.h file):
class NativeHelper
{
public:
static void showInterstitial(string adSdk);
private:
static bool instanceFlag;
static NativeHelper* instance;
}
You can also use SDKBOX, but this is more flexible solution and you always have up-to-date sdk.

runOnUiThread not working properly

I am trying to create textview in android which display the remaining time(seconds).
Have used runOnUiThread and Hadnler for this and everything seems working fine(sysout and debug shows that both threads are executed and value is updated properly).
However, on UI the textview value is not updated properly. It gets updated with last value when the thread completes.
I am writing the below code inside private method of the fragment.
final TextView timerText = (TextView) mainView.findViewById(R.id.timerText);
timerText.setText(R.string.maxAllowedSeconds);
handler.post(new Runnable() {
#Override
public void run() {
while(true)
{
System.out.println("Text:"+ ""+maxAllowedSeconds);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
maxAllowedSeconds--;
if(maxAllowedSeconds <= 0)
break;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("Running on UI Thread : " + maxAllowedSeconds);
timerText.setText("" + maxAllowedSeconds);
}
});
}
}
});
Gone through many of the previous questions in this area but none seems to have concrete solutions for this problem.
Thanks in advance.
SOLUTOIN:
Finally I used AsynchTask which worked perfectly as expected.
private class RapidFireAsyncTimerTask extends AsyncTask<Integer, Integer, Void> {
private Context context;
private View rootView;
public RapidFireAsyncTimerTask(Context ctx, View rootView) {
this.context = ctx;
this.rootView = rootView;
}
#Override
protected Void doInBackground(Integer... params) {
int maxSec= params[0];
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(--maxSec);
if (maxSec <= 0)
break;
}
return null;
}
#Override
protected void onProgressUpdate(final Integer... values) {
((TextView) rootView.findViewById(R.id.timerText)).setText("" + values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
//next task
}
}
Instead of Handler, it worked with AsynchTask(No runOnUiThread needed).
public RapidFireAsyncTimerTask(Context ctx, View rootView) {
this.context = ctx;
this.rootView = rootView;
}
#Override
protected Void doInBackground(Integer... params) {
int maxSec= params[0];
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(--maxSec);
if (maxSec <= 0)
break;
}
return null;
}
#Override
protected void onProgressUpdate(final Integer... values) {
((TextView) rootView.findViewById(R.id.timerText)).setText("" + values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
//next task
}
}

Camera in Android app

I am creating an app which required to perform from API 15 to API 23 using camera so what should be the best way to implement camera as camera class is deprecated in API 21 and also android.hardware.camera2 not able to implement on lower version then API 21.
The below code is something I have taken out of one of my projects, it has had a lot of stuff ripped out for the purpose of putting it on here so you will have to edit it for your needs. It uses the original camera api which is back compatible for your api needs.
public class RecordGameKam extends Fragment
implements TextureView.SurfaceTextureListener, View.OnClickListener {
private final static String TAG = "CameraRecordTexture";
private Camera mCamera;
private TextureView mTextureView;
int numberOfCameras;
int defaultCameraId;
private boolean isRecording = false;
protected MediaRecorder mediaRecorder;
#SuppressWarnings("ConstantConditions")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
View rootView = new RelativeLayout(getActivity());
mTextureView = new TextureView(getActivity());
mTextureView.setSurfaceTextureListener(this);
//View parameters-----------------------------------------------------------------------
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
rootView.setLayoutParams(params);
((ViewGroup) rootView).addView(mTextureView);
return rootView;
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
// Find the total number of cameras available
numberOfCameras = Camera.getNumberOfCameras();
// Find the ID of the default camera
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
try {
if (mCamera != null) {
//final Camera.Size previewSize = onMeasure();
//Camera.Size recorderSize = previewSize;
final Camera.Parameters params = mCamera.getParameters();
params.setPreviewSize(720, 480);
mCamera.setParameters(params);
mCamera.setDisplayOrientation(90);
mCamera.setPreviewTexture(surface);
mCamera.startPreview();
startContinuousAutoFocus();
}
} catch (IOException ioe) {
// Something bad happened
mCamera.release();
mCamera = null;
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Ignored, Camera does all the work for us
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
try {
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().show();
}
} catch (Exception e) {
e.printStackTrace();
}
releaseMediaRecorder();
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// Invoked every time there's a new Camera preview frame
}
private boolean setMediaRecorder() throws IllegalStateException {
try {
//Create a new instance of MediaRecorder.
mediaRecorder = new MediaRecorder();
//Unlock and set camera to Media recorder
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
//Configure audio/video input
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
CamcorderProfile profile = null;
if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_480P)) {
profile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
}
if (profile != null) {
mediaRecorder.setProfile(profile);
}
//Change oritentation
mediaRecorder.setOrientationHint(90 - 180 + 360);
mediaRecorder.setOutputFile(getFilename());
} catch (Exception e) {
e.printStackTrace();
}
//Attempt to prepare the configuration and record video.
try {
button.setBackgroundResource(R.drawable.camera_pressed);
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
mediaRecorder.release();
return false;
}
return true;
}
boolean startContinuousAutoFocus() {
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
assert focusModes != null;
String CAF_PICTURE = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
CAF_VIDEO = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
supportedMode = focusModes
.contains(CAF_PICTURE) ? CAF_PICTURE : focusModes
.contains(CAF_VIDEO) ? CAF_VIDEO : "";
if (!supportedMode.equals("")) {
params.setFocusMode(supportedMode);
mCamera.setParameters(params);
return true;
}
return false;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
enter code here

How to reopen/prevent closing of ControlsFX LoginDialog on failed login?

In my application, the first I do is request the user to login using the controlsFX LoginDialog. If the login is successful, I display the application, however if it fails the login window will close.
I would rather the login window stay open to allow the user to attempt to login again.
public void start(Stage stage) throws Exception {
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String,String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if(success){
openDriverWindow(stage);
}else {
//Display error message
}
return null;
}
});
ld.show();
}
If the login is unsuccessful, the dialog closes - which requires the user to reopen the application.
You can use Dialog from JDK8u40 which will be released at march 2015 or use dialogs from ConrolsFX (openjfx-dialogs-1.0.2). There is a code to implement Dialog which will not be closed until authentication is not passed.
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");
grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
Button loginButton = (Button)dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
**// Prevent closing dialog if not authenticated**
loginButton.addEventFilter(ActionEvent.ACTION, (event) -> {
if (!authenticated()) {
event.consume();
}
});
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(username.getText(), password.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});
this example was given from this article where you can find many useful examples
Try this:
public class Main extends Application{
private boolean login(String key, String value){
Pair loginData = new Pair<String, String>("test", "test");
if (loginData.getKey().equals(key) && loginData.getValue().equals(value)) {
return true;
}
else {
//Вывести Alert.
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
Alert alert = new Alert(Alert.AlertType.ERROR, "Вы ввели неправильное имя или пароль");
alert.setTitle("Error");
alert.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return false;
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Terminal Kuban-electro");
getLogin(primaryStage);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
System.exit(0);
}
});
}
private void getLogin(Stage primaryStage){
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String, String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if (success) {
Scene scene = null;
try {
scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("fxml/main.fxml")));
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
}
} else {
getLogin(primaryStage);
}
return null;
}
});
ld.setHeaderText("Введите имя пользователя и пароль");
ld.setTitle("Авторизация");
ld.show();
}
public static void main(String[] args) throws MalformedURLException {
//Инициализация формы в потоке
Thread myThready = new Thread(() -> {
launch(args);
});
myThready.start();
}
}

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}