I have a working code now with my thesis but I decided to clean it up using functions/methods/objects (not really sure what to call them) but after organizing them, my app crashes everytime i start it. I dont really know what the problem is.
Main Screen shows Start and Exit Button. When I press START, the app says "Unfortunately thesis has stopped".
My code goes like this:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.items, menu);
View v = (View) menu.findItem(R.id.search).getActionView();
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String curtextArray = txtSearch.getText().toString();
char[] curletters = curtextArray.toCharArray();
char[] curenhancedLetters = curtextArray.toCharArray();
//probably, problem here on Stemming stem
Stemming stem = new Stemming(curtextArray, curletters, curenhancedLetters);
AsyncTaskRunner newTask = new AsyncTaskRunner(enhancedStem);
// and probably, problem is here on the stem.<x process>;
stem.removeApostrophe();
stem.vowelMarking();
stem.shortSyllable();
if (continueStem == 1){
stem.region1();
stem.region2();
stem.shortWord();
stem.step0();
stem.step1a();
stem.step1b();
newTask.execute();
}
return false;
};
});
return super.onCreateOptionsMenu(menu);
}
Here's my Stemming Class
public class Stemming {
String textArray;
char[] letters;
char[] enhancedLetters;
public Stemming (String curtextArray, char[] curletters, char[] curenhancedLetters){
this.textArray = curtextArray;
this.letters = curletters;
this.enhancedLetters = curenhancedLetters;
}
public Stemming(){
}
public void removeApostrophe(){
...processes here
}
public void vowelMarking(){
...processes here
}
public void shortSyllable(){
...processes here
}
public void region1(){
...processes here
}
public void region2(){
...processes here
}
public void shortWord(){
...processes here
}
public void step0(){
...processes here
}
public void step1a(){
...processes here
}
public void step1b(){
...processes here
}
}
}
I have a theory on why it crashes. Is this method possible? (pseudocode):
public class Stemming {
String result;
String sample = "A A A A A";
public void changeAtoB{
//do process to convert all As to Bs making String sample = "B B B B B"
result = sample;
}
public void changeBtoC{
//do process to convert all Bs to Cs making String result = "C C C C C"
result = result;
}
... so on {
}
}
What I did was process the string in a straight manner without doing any variable declarations (my variables are declared globally) or initializations. and I also did not put any return statements.
My code used to work when It was still without those functions/methods/objects.
Sorry about my long post. Don't know how to explain it better. I hope you help me. Thank you in Advance!
LOGCAT:
>E/AndroidRuntime(11007): FATAL EXCEPTION: main
E/AndroidRuntime(11007): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.atienzaerni.thesis/com.atienzaerni.thesis.secondactivity}: java.lang.NullPointerException
E/AndroidRuntime(11007): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
E/AndroidRuntime(11007): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
E/AndroidRuntime(11007): at android.app.ActivityThread.access$600(ActivityThread.java:127)
E/AndroidRuntime(11007): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
E/AndroidRuntime(11007): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(11007): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(11007): at android.app.ActivityThread.main(ActivityThread.java:4441)
E/AndroidRuntime(11007): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(11007): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(11007): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime(11007): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime(11007): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(11007): Caused by: java.lang.NullPointerException
E/AndroidRuntime(11007): at android.app.Activity.findViewById(Activity.java:1794)
E/AndroidRuntime(11007): at com.atienzaerni.thesis.secondactivity.<init>(secondactivity.java:54)
E/AndroidRuntime(11007): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(11007): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime(11007): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
E/AndroidRuntime(11007): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
E/AndroidRuntime(11007): ... 11 more
I/Process(11007): Sending signal. PID: 11007 SIG: 9
(I'm using my phone by the way. Not an emulator. If this makes a difference)
It looks like you are getting a NullPointerException because v is null at this line:
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
This is probably caused by null being returned from the menu items action view here:
View v = (View) menu.findItem(R.id.search).getActionView();
You should either set the action view in code and not call getActionView or make sure you have a proper action view set in the menu XML. Without seeing your menu XML it's hard to tell if the problem lies in the XML.
Related
I'm creating my own application. I tested it on Android Lollipop and Marshmallow - everything works great. But whenever I try Android Kitkat, an error occurs. Here's error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newproject/com.example.newproject.Progi}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at com.example.newproject.Progi.onCreate(Progi.java:62)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
It looks like problem is on line 62 in "progi" class, but - as for me - everything is OK especially that on newer Android versions it works great.
public class Progi extends AppCompatActivity {
Intent intent;
Bundle liczby;
Bundle doble;
BigDecimal tablica [][];
BigDecimal punkty = new BigDecimal(-1);
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
android.content.SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
boolean warunek = shared.getBoolean("serial", false);
android.view.MenuItem menuitem = menu.getItem(0);
if(warunek)
{
menuitem.setTitle("Oceny pojedynczo");
}
else menuitem.setTitle("Oceny seryjnie");
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.firstmenu, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutprogi);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Progi punktowe");
intent = getIntent();
liczby = intent.getBundleExtra("liczby");
doble = intent.getBundleExtra("doble");
tablica = (BigDecimal[][]) doble.getSerializable("doble"); //here is line 62
if(intent.hasExtra("max")) {
Bundle a = intent.getBundleExtra("max");
punkty = (BigDecimal) a.getSerializable("max");
}
przejscie(true);
if(punkty.compareTo(new BigDecimal(-3))==0)
{
procenty(findViewById(android.R.id.content));
}
else if(punkty.compareTo(new BigDecimal(-1))!=0)
{
liczymy(findViewById(android.R.id.content));
}}
And in case someone asking "what 'tablica' gets from intent?":
BigDecimal[][] tablica = new BigDecimal[16][3];
//here i get data from file and put in inside "tablica"
Bundle doble = new Bundle();
doble.putSerializable("doble", tablica);
Intent intent = new Intent(Starter.this, MyActivity.class);
intent.putExtra("doble", doble);
startActivity(intent);
Any idea what's wrong?
Try switching your array implementation (BigDecimal[] []) to ArrayList.
If you want to pass an Array through an intent on Android versions
prior to Android 5.0.1 (maybe some older versions work aswell, but up
to Android 4.3 it is NOT working) You'll have to work around it. You
could do this by converting your Array to an ArrayList.
Then you would be casting it something like this:
(ArrayList<ArrayList<BigDecimal>>) doble.getSerializable("doble");
Related SO answer
Solution:
The following worked fine, but I had two Activities already using my helper class, but forgot to add the Interface to one Activity.
So I got the TypeCastException.
But I did not realize I always looked at the wrong Activity, so I could not find the issue.
I currently write my first android service, which works fine.
Now I realized, that I have to bind unbind, check binding all over and so I thought to put all into a subclass and only do an interface with callbacks for the only functions I need.
But now i am stuck to call my interface functions
onTcBlueServiceConnected()
onTcBlueServiceDisconnected()
I simply want to prevent to write the same code over and over again.
Each activity I have to use the service, I extend from this helper class, instead of the AppCompatActivity.
Maybe I chose the wrong path, but lost with the right words for a search.
As far as I understand bound services, I have to bind from each activity I access the service, and unbind of course when it is destroyed.
So I thought this is a good approach
public abstract class TcBlueServiceHelper extends AppCompatActivity {
private static String LOG_TAG = "TcBlueServiceHelper";
TcBlueService mTcBlueService;
TcBlueService.TcBlueBinder myBinder;
boolean mServiceBound = false;
Context mCallingContext;
public TcBlueServiceHelper(Context callingContext) {
mCallingContext = callingContext;
}
public TcBlueServiceHelper(){
mCallingContext = this;
}
public void bindServiceSave(){
if (mServiceBound == false) {
Intent intent = new Intent(this, TcBlueService.class);
startService(intent);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
}
public void unbindServiceSave(){
if (mServiceBound) {
unbindService(mServiceConnection);
mServiceBound = false;
}
}
public TcBlueService.TcBlueBinder getBinder(){
return myBinder;
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
((ITcBlueServiceHelper)mCallingContext).onTCBServiceDisconnected(name);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder = (TcBlueService.TcBlueBinder) service;
mTcBlueService = myBinder.getService();
mServiceBound = true;
((ITcBlueServiceHelper)mCallingContext).onTCBServiceConnected(name, service);
}
};
public interface ITcBlueServiceHelper{
public void onTCBServiceConnected(ComponentName name, IBinder service);
public void onTCBServiceDisconnected(ComponentName name);
}
}
My first thought to cast result in a "ClassCastException"
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ClassCastException: de.mobacomp.android.freightweight.StartActivity cannot be cast to de.mobacomp.android.freightweight.TcBlueServiceHelper$ITcBlueServiceHelper
at de.mobacomp.android.freightweight.TcBlueServiceHelper$1.onServiceConnected(TcBlueServiceHelper.java:72)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1068)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1085)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
I am working on adding Shared Preferences to my Note taking Android App and I am running into a peculiar null pointer exception. I am currently testing settings for font size and typeface in my app and have been able to successfully save the shared preferences for both but am having trouble with the retrieval part. When the settings are changed, they successfully change the font and font size on a Fragment for the remainder of time the app is opened but I cannot restore them if the app is restarted.
First weird Null Pointer is in the onCreate.
OnCreate:
//create a new note fragment if one has not been created yet
mNoteFragment = (NoteFragment) getFragmentManager().findFragmentById(R.id.container);
if (mNoteFragment == null) {
mNoteFragment = new NoteFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container, mNoteFragment).commit();
}
//restore SharedPreferences
SharedPreferences sharedPrefs = getPreferences(0);
int stylePref = sharedPrefs.getInt(SharedPreferanceConstants.PREF_FONT_SIZE, 2);
String fontPref = sharedPrefs.getString(SharedPreferanceConstants.PREF_TYPEFACE, "");
Log.e("STYLEID", String.valueOf(stylePref));
Log.e("FONTTYPE", fontPref);
onStyleChange(null , stylePref); //NULL POINTER EXCEPTION HERE
onFontChange(null, fontPref);
The logs output "3" and "Impact" which are the correct values for size and font which indicates that stylePref and fontPref are not null.
The next Null Pointer is below.:
#Override
public void onStyleChange(CustomStyleDialogFragment dialog, int styleId) {
Log.d("NOTEFRAGMENT", String.valueOf(mNoteFragment));
mNoteFragment.setCustomStyle(styleId); //NULL POINTER EXCEPTION HERE
}
#Override
public void onFontChange(CustomStyleDialogFragment dialog, String fontName) {
mNoteFragment.setCustomFont(fontName);
}
I have tested logging the value of styleId and got "3" so that doesn't seem to be the issue. mNoteFragment isnt null either based on the log.
Here is the third NP Exception in the NoteFragment.java. This is where I ultimately set the EditText view to the desired settings. I had no trouble changing font and size without shared preferences so I am not sure the issue here.
public void setCustomFont(String fontName) {
if(fontName.equals("Helvetica")) {
mEditText.setTypeface(mHelvetica);
}
else if(fontName.equals("Helvetica-Neue")) {
mEditText.setTypeface(mHelveticaNeue);
}
else if(fontName.equals("Impact")) {
mEditText.setTypeface(mImpact);
}
else {
mEditText.setTypeface(Typeface.DEFAULT);
}
}
public void setCustomStyle(int styleId) {
if(styleId == 1) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small);
}
else if(styleId == 2) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
}
else if(styleId == 3) {
//NULL POINTER EXCEPTION HERE
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large);
}
}
And of course, here is the logcat. Thanks in advance!
11-18 10:31:53.030 18966-18966/com.richluick.blocnotes I/Process﹕ Sending signal. PID: 18966 SIG: 9
11-18 10:35:32.838 19248-19248/com.richluick.blocnotes D/STYLEID﹕ 3
11-18 10:35:32.838 19248-19248/com.richluick.blocnotes D/FONTTYPE﹕ Impact
11-18 10:35:32.839 19248-19248/com.richluick.blocnotes D/ERROR﹕ NoteFragment{422972f8 id=0x7f090001}
11-18 10:35:32.840 19248-19248/com.richluick.blocnotes D/AndroidRuntime﹕ Shutting down VM
11-18 10:35:32.840 19248-19248/com.richluick.blocnotes W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4197dd40)
11-18 10:35:32.842 19248-19248/com.richluick.blocnotes E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.richluick.blocnotes, PID: 19248
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.richluick.blocnotes/com.richluick.blocnotes.BlocNotes}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5097)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.richluick.blocnotes.NoteFragment.setCustomStyle(NoteFragment.java:86)
at com.richluick.blocnotes.BlocNotes.onStyleChange(BlocNotes.java:139)
at com.richluick.blocnotes.BlocNotes.onCreate(BlocNotes.java:61)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5097)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
NoteFragment.java
public class NoteFragment extends Fragment {
public EditText mEditText;
private Typeface mHelvetica;
private Typeface mHelveticaNeue;
private Typeface mImpact;
private static final String TEXT = "text";
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(TEXT, mEditText.getText().toString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_note, container, false);
setHasOptionsMenu(true);
//restore state of app when activity is destroyed and restarted
mEditText = (EditText) rootView.findViewById(R.id.editText);
if (savedInstanceState != null) {
mEditText.setText(savedInstanceState.getString(TEXT));
}
//Store the font assets as variables
mHelvetica = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Helvetica_Reg.ttf");
mHelveticaNeue = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HelveticaNeue_Lt.ttf");
mImpact = Typeface.createFromAsset(getActivity().getAssets(), "fonts/impact.ttf");
return rootView;
}
/**
* This is a setter method for setting the font the user has selected from the spinner
*
* param fontName the name of the font the user selected
* #return void
* */
public void setCustomFont(String fontName) {
if(fontName.equals("Helvetica")) {
mEditText.setTypeface(mHelvetica);
}
else if(fontName.equals("Helvetica-Neue")) {
mEditText.setTypeface(mHelveticaNeue);
}
else if(fontName.equals("Impact")) {
mEditText.setTypeface(mImpact);
}
else {
mEditText.setTypeface(Typeface.DEFAULT);
}
}
/**
* This is a setter method for setting the font style the user has selected from custom menu
*
* param styleId the integer id of the font stlye selected (SMALL, MEDIUM, LARGE)
* #return void
* */
public void setCustomStyle(int styleId) {
if(styleId == 1) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small);
}
else if(styleId == 2) {
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
}
else if(styleId == 3) {
Log.d("EDITTEXT", String.valueOf(mEditText));
mEditText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.bloc_notes, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_erase) {
mEditText.setText("");
}
return super.onOptionsItemSelected(item);
}
}
In your SomeActivity.onCreate() you are creating an instance of NoteFragment, but even if you commit it via a transaction, it won't be inflated and created right away. Which basically means, the NoteFragment.onCreateView() was not executed and the fragments UI is not yet created. However, your Activity.onCreate() assumes, that mFragment.mEditText is already set, which is not the case, so you run into a NullPointerException.
Take a look at the FragmentTransation.commit method: http://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#commit()
Schedules a commit of this transaction. The commit does not happen immediately; it will
be scheduled as work on the main thread to be done the next time that thread is ready.
Your mEditText in your NoteFragment is null at this time, hence the NPE.
Just init your member mEditText in onCreate() or onActivityCreated() of the fragment, not onCreateView(). That should ensure that mEditText is not null when you call your setters.
Whatever happens, you should be protecting against a null mEditText in your setter functions.
EDIT this is what I meant:
public void setCustomFont(String fontName) {
if(mEditText != null){
if(fontName.equals("Helvetica")) {
mEditText.setTypeface(mHelvetica);
}
else if(fontName.equals("Helvetica-Neue")) {
mEditText.setTypeface(mHelveticaNeue);
}
else if(fontName.equals("Impact")) {
mEditText.setTypeface(mImpact);
}
else {
mEditText.setTypeface(Typeface.DEFAULT);
}
}
}
EDIT 2: Oncreate will not be a good place. Basically you want to call your setter after the fragmentmanager has committed your change, so that mEditText has been initialized.
EDIT 3 - Try this with your initial code:
getFragmentManager().beginTransaction().replace(R.id.container, mNoteFragment).commit();
getFragmentManager().executePendingTransactions();
Okay so I am not sure why this works but I was able to figure out the anwer based on this question:
onCreateView() in Fragment is not called immediately, even after FragmentManager.executePendingTransactions()
I added the following line
getFragmentManager().executePendingTransactions();
and then moved everthing to the onStart method
#Override
protected void onStart() {
super.onStart();
//create a new note fragment if one has not been created yet
mNoteFragment = (NoteFragment) getFragmentManager().findFragmentById(R.id.container);
if (mNoteFragment == null) {
mNoteFragment = new NoteFragment();
getFragmentManager().beginTransaction().replace(R.id.container, mNoteFragment).commit();
getFragmentManager().executePendingTransactions();
}
//restore SharedPreferences
SharedPreferences sharedPrefs = getPreferences(0);
int stylePref = sharedPrefs.getInt(SharedPreferanceConstants.PREF_FONT_SIZE, 2);
String fontPref = sharedPrefs.getString(SharedPreferanceConstants.PREF_TYPEFACE, "");
Log.d("STYLEID", String.valueOf(stylePref));
Log.d("FONTTYPE", fontPref);
onStyleChange(null , stylePref);
onFontChange(null, fontPref);
}
and for some reason it works fine now. If anyone could explain why that would be great
Try use 'apply' instead of 'commit' , the justification is here -> What's the difference between commit() and apply() in Shared Preference by Lukas Knuth.
But basically, apply() will commits its changes to the in-memory SharedPreferences immediately.
It's strong recommended use a class to manager your preferences, like 'MyPreferencesManager'.
I've programmed a game for android, everything works fine, but now I want my app to have Google play Games services (leaderboards and achievements). I used the Google example code to log in to the Google services (no errors in the script), but every time I want to connect with my App in debug mode, I get this error:
6-29 11:48:29.391 23779-23779/com.JFKGames.theepicbutton E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.JFKGames.theepicbutton, PID: 23779
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=9001, result=10004, data=null} to activity {com.JFKGames.theepicbutton/com.JFKGames.theepicbutton.MainActivity}: java.lang.IllegalStateException: GoogleApiClient must be connected.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3446)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3489)
at android.app.ActivityThread.access$1300(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: GoogleApiClient must be connected.
at com.google.android.gms.internal.fq.a(Unknown Source)
at com.google.android.gms.games.Games.c(Unknown Source)
at com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore(Unknown Source)
at com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore(Unknown Source)
at com.JFKGames.theepicbutton.MainActivity.onActivityResult(MainActivity.java:79)
at android.app.Activity.dispatchActivityResult(Activity.java:5446)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3442)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3489)
at android.app.ActivityThread.access$1300(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
And the App crashes. Here's my code for the MainActivity where I want it to connect:
public class MainActivity extends BaseGameActivity implements
GameHelper.GameHelperListener, View.OnClickListener {
public static int REQUEST_LEADERBOARD = 1002;
boolean mExplicitSignOut = false;
boolean mInSignInFlow = false;
GoogleApiClient mClient() {
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedClients(BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.startbutton);
button.setOnClickListener (this);
Button highscorebutton = (Button)findViewById(R.id.highscorebutton);
highscorebutton.setOnClickListener(this);
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
}
public void onClick(View view) {
if(view.getId()==R.id.startbutton) {
startActivityForResult(new Intent(this, buttonActivity.class), 1);
} else if(view.getId()==R.id.highscorebutton) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.the_best_players)),REQUEST_LEADERBOARD);
} else if (view.getId() == R.id.sign_in_button) {
// start the asynchronous sign in flow
beginUserInitiatedSignIn();
}
else if (view.getId() == R.id.sign_out_button) {
// sign out.
signOut();
// show sign-in button, hide the sign-out button
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.the_best_players), resultCode);
if(requestCode==1) {
if(resultCode > leseHighscore()) {
schreibeHighscore(resultCode);
}
}
}
#Override
public void onSignInFailed() {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
View a = findViewById(R.id.highscorebutton);
a.setVisibility(View.VISIBLE);
View b = findViewById(R.id.button3);
b.setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
}
Thanks, GoogleWelt
According to the official documentation, "Before any operation is executed, the GoogleApiClient must be connected"
When the user in not connected(signed in) and clicks to show leaderboards or achievements, it results in the exception thrown. Modify your code for launching the leaderboard like this:
} else if(view.getId()==R.id.highscorebutton) {
if (isSignedIn())
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.the_best_players)), REQUEST_LEADERBOARD);
else showAlert("Please sign in to view leaderboards");
}
Use the same logic for showing achievements:
if (isSignedIn())
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), REQUEST_ACHIEVEMENT);
else showAlert("Please sign in to view achievements");
Check the part where you are getting ApiClient i.e. getApiClient().
Write the code below to see if GoogleApiClient is Connected or not.
GoogleApiClient mGoogleApiClient;
if(mGoogleApiClient.isConnected()){
// good
}else{
//connect it
mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
}
I keep getting this error, I am not sure what's causing it. I declared and initialized the variables, but the error didn't disappear. I have been looking at the same error but I can't catch the mistake.
05-01 20:57:43.162 32675-32675/com.ammar.customlistview1.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40be21f8)
05-01 20:57:43.172 32675-32675/com.ammar.customlistview1.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ammar.customlistview1.app/com.ammar.customlistview1.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1810)
at com.ammar.customlistview1.app.MainActivity.<init>(MainActivity.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1026)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Here is my class code:
package com.ammar.customlistview1.app;
/**
* Created by Ammar on 5/1/2014.
*/
public class person {
private String name = "Ammar";
private int age = 21;
private int picture = R.drawable.ic_launcher;
public person(String name, int age, int picture) {
this.name = name;
this.age = age;
this.picture = picture;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPicture() {
return picture;
}
public void setPicture(int picture) {
this.picture = picture;
}
}
Here is my main activity code:
package com.ammar.customlistview1.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
personadaptor adapter ;
ArrayList <person> theperson = new ArrayList<person>();
ListView lv = (ListView) findViewById(R.id.lvmain);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
person p1 = new person("Ammar", 21 , R.drawable.ic_launcher);
person p2 = new person("Ali", 25 , R.drawable.ic_launcher);
person p3 = new person("Saber", 23 , R.drawable.ic_launcher);
theperson.add(p1);
theperson.add(p2);
theperson.add(p3);
adapter = new personadaptor(theperson, this);
lv.setAdapter(adapter);
}
#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);
}
}
You can't call findViewById() until you've called setContentView().
You cannot use Android UI methods such as findViewById() in the initializers of an Activity (or similar) Class, as these are only valid during and after the call to onCreate().
Move your initialization code to onCreate()
(And when you do so, be sure to put the findViewById() after setContentView() as Matiash so correctly points out - otherwise you will only get a different null pointer exception)
1.ListView lv;
Listview initialization shld be after
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvmain);
2.no need to initialize this name,age and picture in person just write
private String name;
private int age ;
private int picture ;
3.in adapterclass u need layout
adapter = new personadaptor(theperson, this);//where is your row layout