Performing stop of activity that is not resumed? - java

I am making a simple Android app just to become familiar with the concept. I have an app with two activities, the first should just be a splash screen that displays for one second, the second is a canvas w/ a black square that turns cyan when you click it. When I run it, it stops with an error in the log saying "performing stop of activity that is not resumed".
Main Activity:
package com.example.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
Thread.sleep(1000);
}catch(Exception e){}
Intent in = new Intent(this, Afspl.class);
startActivity(in);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Next Activity:
package com.example.test;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class Afspl extends Activity {
public DrawView vi;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vi = new DrawView(this);
}
class DrawView extends View{
Paint paint = new Paint();
public DrawView(Context context){
super(context);
}
public void onDraw(Canvas c){
paint.setColor(col);
c.drawRect(40, 40, 200, 200, paint);
}
private int col = Color.BLACK;
public void setToColor(int c){
col=c;
}
}
public boolean onTouchEvent(MotionEvent me){
if(me.getX()>=30 && me.getX() <= 320 && me.getY() >=30 && me.getY() <= 320)vi.setToColor(Color.CYAN);
return super.onTouchEvent(me);
}
}
Do you have any idea why I'm getting this error or what it means or how I can fix this? All help is appreciated.

Insted of using:
try{
Thread.sleep(1000);
}catch(Exception e){}
Intent in = new Intent(this, Afspl.class);
startActivity(in);
You could try using new
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent in = new Intent(getApplicationContext(), Afspl.class);
startActivity(in);
}
}, 1000);
You should never put to sleep the main thread. If you want to do something in the future use a Handler and a Runnable.
Also, you should declare a View on both Activities, not just the first one. Create a View and set it with "setContentView()" on your second activity.

Related

New layout doesn't pop up

I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.

how to direct to another activity after successful login, Android Developer Studio

as i said, how do i direct to the next activity after successfully login? im kinda stuck for a while now, and it is necessary for this to run. im practicing my android skills awhile back. so i am using android developer studio for my practices of developing android. this is my code. hope you guys can help.
`package com.mikesaclolo.pinasarap;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MainActivity extends Activity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tx1=(TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}`
start activity using Intent :
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,LoginActivity.class); // redirecting to LoginActivity.
startActivity(intent);
}

error: class, interface or enum expected at void

I've been stuck on this problem for a while, I get error:
class, interface or enum expected
Any help will be appreciated? I've been stuck on this problem and my friends cant figure it out.
here is the code:
package com.example.vengelen.knitting;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
public class Rectangular extends ActionBarActivity {
EditText amount1;
EditText amount2;
EditText amount3;
TextView tt;
Button calculate;
double w=0;
double x=0;
double y=0;
double z=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rectangular);
initControls();
}
private void initControls()
{
amount1=(EditText)findViewById(R.id.editText);
amount2=(EditText)findViewById(R.id.editText3);
amount3=(EditText)findViewById(R.id.editText2);
tt=(TextView)findViewById(R.id.editText4);
calculate=(Button)findViewById(R.id.button9);
calculate.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) { calculate();}});
}
EditText input;
EditText output;
Button one;
private void calculate()
{
w=Double.parseDouble(amount3.getText().toString());
x=Double.parseDouble(amount1.getText().toString());
y=Double.parseDouble(amount2.getText().toString());
z=(x+y)*(y+w);
tt.setText(Double.toString(z));
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rectangular);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_selector, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You have unnecesarry end brace just before your method onCreate:
}
^^
#Override
protected void onCreate(Bundle savedInstanceState)
This means that compiler thinks that by that brace, your class definition has completed and then sees a new method definition which should be within another class and hence complains about the same. As a best practice, you should always format your code.

How to keep IOIO connected when android screen goes off?

I am using the following code with IOIO to act as a motion detector, the problem is the IOIO is disconnected whenever my phone screen goes off! I do not want the screen to stay on all the time to keep the IOIO connected!
any solution please?
package com.LookHin.ioio_pir_motion_sensor;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends IOIOActivity {
private ToggleButton toggleButton1;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
//Toast.makeText(getApplicationContext(), "Show About", Toast.LENGTH_SHORT).show();
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Looper extends BaseIOIOLooper {
private DigitalOutput digital_led0;
private AnalogInput deigital_input;
int i = 0;
private float InputStatus;
#Override
protected void setup() throws ConnectionLostException {
digital_led0 = ioio_.openDigitalOutput(0,true);
deigital_input = ioio_.openAnalogInput(45);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "IOIO Connect", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void loop() throws ConnectionLostException {
try{
digital_led0.write(!toggleButton1.isChecked());
InputStatus = deigital_input.getVoltage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView1.setText(String.format("%.02f",InputStatus)+" v.");
if(InputStatus >= 3.0){
textView1.setBackgroundColor(Color.RED);
if (i == 0){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
i = 1;
};
}else{
textView1.setBackgroundColor(Color.TRANSPARENT);
i = 0;
}
}
});
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Option 1) Lock the screen so it always stays awake
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Option 2) Fix your response to onPause().
When the screen goes off the onPause() method is called and you should handle it as otherwise your activity will be closed.
#Override
protected void onPause() {
// Your code
super.onPause();
}
The onPause() normally calls the ioio.disconnect() so this should be overrode.
IOIOService let´s you run your code on the background even if application goes to the background.

Splash Screen Causes MenuItems not to appear

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

Categories

Resources