I am a PHP developer, who is new to Android development and Java so please bear with me.
I am developing an extremely simple app for testing and learning purposes.
when the user clicks my app icon, they are presented with a loading screen. I have a TextView with a progress bar underneath.
TextView XML code:
<TextView
android:id="#+id/loadingMessage1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:text="#string/loading1" />
The value is set to the string loading1 in strings.xml
<string name="loading1">Loading Message 1</string>
In my loadingscreen.java i have:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class LoadingScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
TextView loadingMessage1 = (TextView)this.findViewById(R.id.loadingMessage1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_loading_screen, menu);
return true;
}
}
Notice I have the code:
TextView loadingMessage1 = (TextView)this.findViewById(R.id.loadingMessage1);
Which I think references the text view.
What I want to happen is that every 3 seconds a different message appears.
So loading message 1... (3 secs) loading message 2... (3 secs) loading message 3..
after loading message 3 i would like a button to replace the progress bar.
You can use the Handler class:
final Handler handler = new Handler();
handler.post(new Runnable(){
#Override
public void run(){
// change your text here
handler.postDelayed(this, 3*1000L);
}
});
You might need to use a timer, which executes every 1 second period.. Read this brilliant android dev blog article on periodic execution using timer and Handler.
Related
I'm trying to make a simple app that changes the background color so many times a second. For example, here I'm trying to do it every 12.5 ms (how do I enter the .5 part?)
I'm extremely new to programming, and can't figure out how to call this method/timer to start running.
I run the app, and it opens the activity with a white background and nothing happens.
Since I'm so new, when I look into the Timer() documentation, I'm not really sure what I'm looking at here.... If someone could help that would be amazing.
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import java.util.Timer;
import java.util.TimerTask;
import static android.support.v7.appcompat.R.attr.background;
/**
* Created by Spader on 3/17/2017.
*/
public class FlashingScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.flashing_screen);
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
runOnUiThread(new Runnable() {
#Override
public void run() {
//stuff that updates ui
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
getWindow().getDecorView().setBackgroundColor(Color.BLACK);
}
;
});
}
},0,12);
}
}
1.
getWindow().getDecorView().setBackgroundColor(Color.WHITE); getWindow().getDecorView().setBackgroundColor(Color.BLACK);
This always set the black color since it is not on a conditional basis. You may want to use a boolean to switch color every time it executes the runnable.
You shouldn't use getDecorView(). Instead find the root View from your layout xml and change the color.
In Java there is no floating value for times. So you can't have 12.5 ms.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html
I have 2 classes for an Android project.
The first class is the Activity and the second class is just a OnClickListener which implements the interface.
If I run the project on my phone I always get an runtime error.
Also I got the message:
The specified activity does not exist! Getting the launcher activity.
Here are my two classes
SendActivity
package kops.sms;
//import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
public class SendActivity extends Activity {
Button buttonSend= (Button) findViewById(R.id.buttonSend);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
buttonSend.setOnClickListener(new ButtonListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.send, menu);
return true;
}
}
and the ButtonListener
package kops.sms;
import android.view.View;
import android.view.View.OnClickListener;
public class ButtonListener implements OnClickListener {
#Override
public void onClick(View v)
{
}
}
I donĀ“t know what is wrong...
I look forward to your replies! :)
You cannot call findViewById() until after you call setContentView(). Please move:
Button buttonSend= (Button) findViewById(R.id.buttonSend);
to after:
setContentView(R.layout.activity_send);
and before:
buttonSend.setOnClickListener(new ButtonListener());
Also, in the future, please use LogCat (e.g., in the DDMS perspective in Eclipse) to examine the Java stack trace associated with your crashes. You would have been told about your NullPointerException, and that may have helped you to fix your problem.
Be sure that your Activity is declared in your manifest. Also, change your onCreate()
public class SendActivity extends Activity {
Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new ButtonListener());
}
You can't call a View such as a Button before you call setContentView() as it exists in your Layout and you haven't inflated your Layout until you call setContentViewe().
If these don't fix your problem then please post Logcat
Edit
Unless I missed it, you need to have all of your Activitys in your manifest. Something like:
<activity
android:name="your.package.name.SendActivity"
// activity attributes such as config changes, lable, etc...
</activity>
Logcat
Logcat output can be one of the most important pieces to determining a crash. It lists what the error was and a line number with activity where the problem occurred. If using Eclipse,
Window-->Show View-->Other-->Android-->Logcat
If you copy/paste the Logcat using coding brackets, it makes getting help much easier. You can also set filters for the logs so you don't get every single message and it is much more manageable. For example, I have a filter with: Filter Name: Runtime, by Log Tag: AndroidRuntime, by Log Level: error. This gives me only error messages for runtime errors/crashes. These filters are on the left side of the logcat view. Hope this helps
Let's try to make it easy to understand.
For an Example I got "Page1" and "Page2" And "Page3".
OK. I created a splash screen on "Page2", so the user can see "Page2" for a specific time (5seconds). and it auto directs him to "Page3" and I also added two buttons on "Page2" so the user can either click "Button1" that goes to "Page3" quicker. or "Button2" that goes to "Page 1"
Ok i done that all correct.
But if "Page2" is on and the user doesnt touch anything it takes him to "Page3".. my problem is that the user can touch anything "Button1" or "Button2" it directs him to "Page3", and if he touches "Button2" and goes to "Page1" (after the timelimit of splashscreen on "Page2" is up, it auto directs him from "Page1" to "Page3"
Please Help.
My Code Is
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.Button;
public class StartGame extends Activity {
// ===========================================================
// Fields
// ===========================================================
private final int SPLASH_DISPLAY_LENGHT = 3000;
// ===========================================================
// "Constructors"
// ===========================================================
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.startgame);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(StartGame.this,Fail.class);
StartGame.this.startActivity(mainIntent);
StartGame.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
Please Help, Thanks.
Wahid
EDIT:
sorry I'm a beginner and I really don't know how to create variables,
Please if you can share some of your knowledge with me and show me an source code.
If variables mean buttons., that's already in there but i didn't
You need to cancel the postDelayed call if your activity 2 has been stopped by the click of a button.
So first you need to create variables from your runnable and your handler.
and then on the press of either button you'll be able to call :
myHandler.removeCallbacks(myRunnable);
Which will stop it from triggering if it is not suppose to anymore.
Edit to suit the beginner profile of the OP :
myRunnable = new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(StartGame.this,Fail.class);
StartGame.this.startActivity(mainIntent);
StartGame.this.finish();
}
}
myHandler = new Handler();
myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGHT);
i am fairly new to android programming and usually find my answers to my problems by searching, but this one i just cant and its very confusing.
The code itself doesn't show any signs of problems, well i do get 2 java exception breakpoints but i dont know how to fix those as they are "unknown"but when i run it on the emulator it says the application has stopped unexpectedly force close. I try to debug it but i dont know how to do it that well. any way here are the codes btw the app is just a test all it to do is have buttons that take me to other "pages" and back. I would appreciate any help.
Main java file
package com.simbestia.original;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class original extends Activity implements View.OnClickListener {
Button button1, button2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.pagetwo);
button2 = (Button) findViewById(R.id.main);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pagetwo:
setContentView(R.layout.pagetwo);
break;
case R.id.main:
setContentView(R.layout.main);
break;
}
}
}
Main xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="pagetwo" android:id="#+id/pagetwo" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
Well here is what i change the code to this one is just one button but it works with multiple and i made a class for every page...
package com.simbestia.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mainmenu = (Button) findViewById(R.id.mainmenu);
mainmenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), mainmenu.class);
startActivityForResult(myIntent, 0);
}
});
}
}
Works how i wanted to so its all good i guess ty again
In the command line/terminal, use ./adb logcat to see, in real time, warnings, erros and such from your device, while you run your app. That should help you a lot.
Note: Don't forget to be in the right folder... <android-sdk-version>/platform-tools, that's where the ADB is.
You should learn to debug your own application. Starting with a break point right in the first line of your onCreate() method.
You can also take a look here: http://www.droidnova.com/debugging-in-android-using-eclipse,541.html
Another possibility is to add a log call in the first line of your onCreate() so you can see where the log of your app starts...
edit:
The way you want to switch the layout is wrong. Try layout switcher or start a new activity for your new layout. calling setContentView more than once is basically just wrong...
Some things to check: make sure your code source folder is the same as your package name (com.simbestia.original) ; make sure it builds (without errors) before you try and run it and make sure that your manifest file has its package attribute set to your package name (com.simbestia.original).