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);
Related
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.
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.
i have just started with android but have done some c# which seems very similar to java
in short, the problem lies in the closeDialog method
I am not very familiar with view/viewgroup so please dont bombard me with incorrect usage of objects, etc.
in short, i am creating a simple app which i hope to improve on (it is basically the start of a huge project)
the _showhint dialog opens fine, and shows the "hint" as expected, but the closeDialog force closes the app, I have no idea why
package com.example.app;
import android.app.Activity;
import android.app.Dialog;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageImageURI = null;
private TextView lblAnswer, lblWelcome;
private EditText edtInput;
public TextView showText ;
public Button btnShowHint, btnCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtInput = (EditText) findViewById(R.id.edtInput) ;
lblWelcome = (TextView) findViewById(R.id.lblWelcome) ;
lblAnswer = (TextView) findViewById(R.id.lblAnswer) ;
btnShowHint = (Button) findViewById(R.id.btnHelp);
btnCalculate = (Button) findViewById(R.id.btnShow) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void calculate(View vw)
{
String [] arrEditStore = new String[edtInput.length()] ;
String arrOperators [] = {"+", "-", "*", "/", "(", ")"} ;
}
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
EDIT: ADDED "this" to final Dialog dialog = new Dialog(this)
I have discovered what has caused the problem
GIVEN CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
SOULTION
first, I moved the decleration of the btnClose to the top
public Button btnShowHint, btnCalculate, btnClose;
then in the design view, removed the link of the button Close onclick method refering to closeDialog.
Afterwards, removing the closeDialog method completely, and also moving some of that code to the _showHint method
it also makes logical sense, thanks to #Mike M. who commented on the post, helped me reason it out, since I say, THIS button must close the dialog but in the method of this button, I am assigning it to be used by itself, which doesn't make logical sense at all, here is the changed code and it works
CHANGED CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
btnClose = (Button) showHintDialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showHintDialog.dismiss();
}
});
}
We all make stupid and unnessasary mistakes at times, some worse than others, but if you find a solution to a problem you have had, maybe somewhere someone has the same issue, so post a solution to your problem, it might help that someone!!!
cheers
I have an error that I don't know why in my Galaxy Ace Samsung(Android 2.3.6) doesn't work but in my Motorola G (Android 4.4) works perfectly. The exception are so strange this is my code:
adapter = new SimpleCursorAdapter(this,R.layout.single_row_profession, cursor,from,to,0);
package com.orun.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.orun.database.DataBaseManager;
import com.orun.model.Profession;
import com.orun.s.SConnection;
public class ProfessionsActivity extends Activity {
public static SConnection sConnection;
public static DataBaseManager manager;
private static Cursor cursor;
private static ListView listView;
private static SimpleCursorAdapter adapter;
private static EditText etSearch;
private static ImageButton btSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_professions);
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
Toast.makeText(getApplicationContext(), "Rol "+sharedPref.getString("ROL","Estudiante"),Toast.LENGTH_LONG).show();
manager = new DataBaseManager(this);
listView = (ListView) findViewById(R.id.listView);
etSearch = (EditText)findViewById(R.id.etSearch);
new LoadTask().execute();
cursor = manager.searchProfession(etSearch.getText().toString());
int[] to = new int[]{R.id.textCode, R.id.textName,R.id.textType};
String[] from = new String[]{"_id","name","type"};
try {
adapter = new SimpleCursorAdapter(this,R.layout.single_row_profession, cursor,from,to,0);
}catch (Exception e){
e.printStackTrace();
}
listView.setAdapter(adapter);
etSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
new SearchTask().execute();
adapter.changeCursor(cursor);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ProfessionsActivity.this,PrincipalActivity.class);
int codeProfession = Integer.parseInt(((TextView)(view.findViewById(R.id.textCode))).getText().toString());
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("CODE_PROFESSION", codeProfession);
editor.commit();
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.professions, 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);
}
private class SearchTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
cursor = manager.searchProfession(etSearch.getText().toString());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
private class LoadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
sConnection = new SConnection();
for(Profession p : sConnection.getPlansPreg())
manager.insertProfession(p.getCode(),p.getName(),"PRE");
for(Profession p : sConnection.getPlansPos())
manager.insertProfession(p.getCode(),p.getName(),"POS");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext(),"Se han cargador todos los planes",Toast.LENGTH_SHORT).show();
}
}
}
The exception is: Cannot resolve constructor
'(Landroid/context/Context;ILandroid/database/Cursor;[Ljava/lang/String;[II)V
The constructor you are using was added in API level 11, so it's no wonder it doesn't exist in Android 2.3.6 (API level 10).
public SimpleCursorAdapter (Context context, int layout, Cursor c,
String[] from, int[] to, int flags) Added in API level 11
Standard constructor.
Parameters
context The context where the
ListView associated with this SimpleListItemFactory is running
layout resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to"
c The database cursor. Can be null if the cursor is not available yet.
from A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet.
to The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet.
flags Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int).
See class reference.
I am trying to add a back button to app but when i add the code i get the "Non static method 'canGoBack() cannot be referenced from a static context" error. I have read several stack articles about this error but have not been able to solve it. Any ideas please?
package com.test;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.PushService;
public class MainActivity extends Activity implements OnClickListener {
private Button push;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "onReceive invoked!", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PushService.setDefaultPushCallback(this, MainActivity.class);
Button back = (Button) findViewById(R.id.back);
WebView webView = (WebView) findViewById(R.id.webView1);;
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.xxxxx.xxxxxx.xxxxx.xxxx// ");
webView.setWebViewClient(new WebViewClient());
push = (Button)findViewById(R.id.senPushB);
push.setOnClickListener(this);
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (true);
}
}
#Override
public void onBackPressed()
{
if(WebView.canGoBack()){
WebView.goBack();
}else{
super.onBackPressed();
}
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(MyCustomReceiver.intentAction));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
JSONObject obj;
try {
obj = new JSONObject();
obj.put("alert", "hello!");
obj.put("action", MyCustomReceiver.intentAction);
obj.put("customdata","My message");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
// Push the notification to Android users
query.whereEqualTo("deviceType", "android");
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try changing:
#Override
public void onBackPressed()
{
if(WebView.canGoBack()){
WebView.goBack();
}else{
super.onBackPressed();
}
}
to:
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView1);
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
Explanation:
You should call canGoBack() and goBack() for the webview instance that you're using (move to the previous view). This is also why the method is declared at the instance level and not at the class level (static)
canGoBack is an instance (non-static) method. It can only be called on an instance of the WebView class. WebView is the class. Calling WebView.function() only works if function is a static function. You need to get the instance of the WebView and call it on that.
For the record, the difference between a static and instance method- a static method may not use any non-static data. An instance method can. Static data only has 1 copy per class. Non-static data has 1 copy per instance of the class.