NullPointerException on onPostExecute method - java

I’m having a navigation drawer for my app that contains a menu with which I can navigate between the fragments. The first fragment that i get after the app lunch is the Home which contains a listView and a footer attached in the bottom (is just for the test). The problem is when I lunch the Home fragment for the first time nothing happen and its work very well, but when I change the fragments from the navigation drawer and trying to get back the home fragment the app crash. The error log show me a null pointer Exception. Thes is my code detail
onCreateView method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.fragment_homes, container, false);
listView = (ListView) v.findViewById(R.id.homeList);
l = new HomeListAdapter(this, homeList);
if(l == null)
Log.i("tag","null");
listView.setAdapter(l);
} catch (InflateException e) {
}
return v;
}
onPostExecute method
#Override
protected void onPostExecute(final String res) {
/*try {
jObj = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
/* JSONArray j = null;
try {
j = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
// Parsing json
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition");
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
l.notifyDataSetChanged();
//pDialog.hide();
}
The error log
10-10 09:31:30.884 2447-2447/com.example.user.unchained E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.unchained, PID: 2447
java.lang.NullPointerException
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:375)
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:277)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
And this is exactly the line that cause the error : l.notifyDataSetChanged();. I notice that the error is just in the case when i'm trying to display the fragment for the secode time.
So any help please ? Thanks !

You need to use this in doInBackground.
#Override
protected Void doInBackground(void... ) {
try {
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition"); //give some other name in getter setter for setText in Home.java. It makes not to understand whether you are using setText for textview assigning.
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
postExecute is used to display UI. don't perform heavy operation like parsing in PostExecute.

Related

Android - How to pass another activity application context from java class extends fragments to asynctask?

Hi I am trying to make application that has view pager and tablayout. So when I choose 'friends' tab layout it will call java class named FragFriends.java,
In this class I want to inflate layout where recycler view adapter is filled with data from database that I retrieve using asynctask method in class PHPuserlist.java
However my application suddenly stopped
Here is the the FragFriends.java
public class FragmentFriends extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.activity_user_view,container,false);// The activity that contains recyclerview
View dview = inflater.inflate(R.layout.activity_profile,container,false); //This is the activity that contains tablayout
PHPUserList phpUserList = new PHPUserList(dview.getContext());
phpUserList.execute();
return rootview;
}
}
I have implement this recycler view with intent and it work just fine. But I need to use this with fragment
Pleas help me
This is the logcat
05-27 16:55:12.198 14031-14031/com.rumahdosen.www.rumahdosen E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rumahdosen.www.rumahdosen, PID: 14031
java.lang.NullPointerException
at com.rumahdosen.www.rumahdosen.PHPUserList.onPreExecute(PHPUserList.java:82)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.rumahdosen.www.rumahdosen.FragmentFriends.onCreateView(FragmentFriends.java:20)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:16834)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:824)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
at android.view.View.measure(View.java:16834)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2252)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1315)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Below is the PHPUserList.java
public class PHPUserList extends AsyncTask<Void,UserList,Void> {
private Context context;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserList> arrayList = new ArrayList<>();
PHPUserList(Context ctx){
this.context = ctx;
activity = (Activity)ctx;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://njtwicomp.pe.hu/listuser.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
UserList userList = new UserList(JO.getString("Name"),JO.getString("Username"));
publishProgress(userList);
}
Log.d("JSON STRING", json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView) activity.findViewById(R.id.RVUserList);
layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected void onProgressUpdate(UserList... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
I try to find the recyclerview by id in another activity while I set the activity as the activity of the passed context. But I don't know how to fix that
So how do I get the activity which is not the context that I passed in asynctask?
Change this:
PHPUserList phpUserList = new PHPUserList(dview.getContext());
phpUserList.execute();
to :
new PHPUserList(getActivity()).execute();
In your fragment class just put getActivity(), where Context is needed it will do the job!
just use getContext();
This does the work.
In case you need to use the Activity Context then Have static context of ClassName.this

Why does my Activity get destroyed upon adding a fragment (#2)?

I want to make it clear that this question will look very similar to one I asked earlier, but that I'm not asking exactly the same thing.
In my previous question, I got a RuntimeException/IllegalStateException, which told me my Activity got destroyed upon adding a new fragment.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
Activity has been destroyed
In that case, it turned out it had to do with me creating new instances of MainActivityin an invalid way:
MainActivity ma = new MainActivity();
(PSA: Don't do the above, use MainActivity ma = (MainActivity) getActivity(); instead.)
I have now corrected this in my entire project, and am getting almost exactly the same error. Let me be clear: I (think I) know the original error was fixed, because I got a different error in between these two RE's, which I was able to fix myself.
To reiterate on my gibberish: Got the first RE, fixed it with the answer on my question, got a different error, fixed that myself, got almost exactly the same RE.
I have searched through my entire project to see if I had anything similar to the error I made before, but I can't find anything, so here I am. So basically, the answer I got on my previous question fixed my issue, temporarily. That answer however, does not help me with this new error I'm getting, that's why I'm asking this question.
TL;DR: Answer on Q1 fixed my issue at first(which makes it a working answer), but it does not fix the issue I'm having right now, which is almost the same.
The actual question
So, now we've got that bit out of the way, let's get on with my issue. So, I'm getting a RuntimeException/IllegalStateExcetion:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}:
java.lang.IllegalStateException: Activity has been destroyed
(PS. It's only a RE because I have my app navigate to the GeneralSettings fragment on startup, for debugging ease.)
I've read up on this kind of error, but nothing I could find that applies on my project.
So, what is causing this RuntimeException/IllegalStateException?
Full log
04-05 14:17:53.140 23411-23411/? I/art: Not late-enabling -Xcheck:jni (already on)
04-05 14:17:53.190 23411-23411/com.example.tim.timapp W/System: ClassLoader referenced unknown path: /data/app/com.example.tim.timapp-1/lib/x86_64
04-05 14:17:53.210 23411-23411/com.example.tim.timapp D/TEST DBHandler: sInstance == null
04-05 14:17:53.370 23411-23411/com.example.tim.timapp D/AndroidRuntime: Shutting down VM
04-05 14:17:53.370 23411-23411/com.example.tim.timapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tim.timapp, PID: 23411
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commit(BackStackRecord.java:663)
at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:276)
at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:58)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.BackStackRecord.run(BackStackRecord.java:793)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6252)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
MainActivity (Snippet)
package com.example.tim.timapp;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static boolean isMainShown = false;
private static boolean isSettingsShown = false;
private static boolean doSavePopup = false;
private static String backTitle = "";
private String tag = "TEST MA";
DBHandler dbHandler;
Menu menu;
public void DrawVariableFragments(String base,String token){
// FragmentManager fm = getFragmentManager();
ArrayList<String> Data;
dbHandler = DBHandler.getInstance(this);
int AmountOfEntries;
int SettingsContainer;
String SettingsTag;
Fragment SettingsVariableFragment;
Fragment SettingsEmptyFragment;
if (base.equalsIgnoreCase("StuffManager")) {
Data = new ArrayList<String>() {{add("StuffManager"); add("name"); add("tag"); }};
SettingsContainer = R.id.FragmentContainer2;
SettingsTag = getString(R.string.navdrawer_stuffmanager);
SettingsVariableFragment = new StuffManagerVariableFragment();
SettingsEmptyFragment = new StuffManagerEmptyFragment();
} else if (base.equalsIgnoreCase("GeneralSettings")) {
Data = new ArrayList<String>() {{add("GeneralSettings"); add("name"); add("ip"); add("port"); add("username"); add("pass"); }};
SettingsContainer = R.id.FragmentContainerGeneralSettings;
SettingsTag = getString(R.string.navdrawer_generalsettings);
SettingsVariableFragment = new GeneralSettingsVariableFragment();
SettingsEmptyFragment = new GeneralSettingsEmptyFragment();
} else {
Log.e(tag, "String Base not recognised");
return;
}
AmountOfEntries = dbHandler.returnArray(base, Data.get(1)).size();
FragmentManager fm = getFragmentManager().findFragmentByTag(SettingsTag).getChildFragmentManager();
if ((dbHandler.returnArray(base, Data.get(1))).size() == 0 ) {
// Log.d(tag, "SettingsContainer1: " + String.valueOf(SettingsContainer) + "; SettingsEmtpyFragment1: " + SettingsEmptyFragment + "; Base1: " + base);
fm.beginTransaction().add(SettingsContainer, SettingsEmptyFragment, (base + "EmptyFragment")).commit();
fm.executePendingTransactions();
return;
}
if (AmountOfEntries > 0) {
String EmptyFragName = (base + "EmptyFragment");
if ((fm.findFragmentByTag(EmptyFragName)) != null) {
fm.beginTransaction().remove(fm.findFragmentByTag(EmptyFragName)).commit();
fm.executePendingTransactions();
}
for (int i = 0; i < AmountOfEntries; i++) {
ArrayList<String> fragmentData = new ArrayList<>();
for (int k=1; k < Data.size(); k++) {
int j=k-1;
fragmentData.set(j, (dbHandler.returnArray(base, Data.get(k)).get(j)));
}
if (token.equalsIgnoreCase("edit")) {
LinearLayout linearLayout = (LinearLayout) findViewById(SettingsContainer);
linearLayout.removeAllViews();
DrawVariableFragments(base ,"draw");
} else if (token.equalsIgnoreCase("add")) {
if (fm.findFragmentByTag(fragmentData.get(i)) == null) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
} else if (token.equalsIgnoreCase("draw")) {
fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
fm.executePendingTransactions();
if (base.equalsIgnoreCase("StuffManager")) {
((StuffManagerVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1));
} else if (base.equalsIgnoreCase("GeneralSettings")) {
((GeneralSettingsVariableFragment) fm
.findFragmentByTag(fragmentData.get(i)))
.setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
}
}
}
} else {
Log.d("TEST", "WTF, nameArray.size != 0 && !> 0");
}
}
}
GeneralSettingsFragment (Snippet)
package com.example.fragments.Settings;
public class GeneralSettingsFragment extends Fragment {
MainActivity ma;
DBHandler dbHandler;
private static Menu optionsMenu;
public static boolean hideDeleteAllButton = false;
LinearLayout linearLayout;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
ma = (MainActivity) getActivity();
linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);
if (linearLayout == null) {
Log.e("GMF", "Layout is null");
} else if (linearLayout.getChildCount() == 0) {
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
hideDeleteAllButton = true;
} else {
hideDeleteAllButton = false;
}
ma.DrawVariableFragments("GeneralSettings", "draw");
return rootView;
}
}
You are still doing things in an unsupported way. In MainActivity.DrawVariableFragments() you are creating a new GeneralSettingsVariableFragment() and then call getChildFragmentManager() on it and attempt to commit a fragment.
The GeneralSettingsFragment has not yet been attached to an Activity so it does not have a host. This throws the IllegalStateException("Activity has been destroyed") exception you are seeing when you try to commit the FragmentTransaction.
It is unclear why you are creating a new GeneralSettingsVariableFragmentwhen you are already inside a new instance of one.
To properly lookup an existing fragment use getFragmentManager().findFragmentByTag(...) or getFragmentManager().findFragmentById(...).

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

The problem is as follows. I have a login activity (in Android Studio) which worked fine a few days before. I don't remember changing anything but when I run this one the previous time the app closed right after I clicked the login button. The last thing indicated was the toast about pre-execution of AsyncTask.
And I can't understand why there could be a NullPointerException.
I have almost the same code for my signup activity and it works fine.
Here is the log:
05-28 16:04:52.395 1218-1232/system_process V/WindowManager﹕ addAppToken: AppWindowToken{5d89eb token=Token{23ccc93a ActivityRecord{2fe54865 u0 utanashati.reminder/.HomepageActivity t17}}} to stack=1 task=17 at 1
05-28 16:04:52.407 19927-19927/utanashati.reminder D/AndroidRuntime﹕ Shutting down VM
05-28 16:04:52.408 19927-19927/utanashati.reminder E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: utanashati.reminder, PID: 19927
java.lang.RuntimeException: Unable to start activity
ComponentInfo{utanashati.reminder/utanashati.reminder.HomepageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at utanashati.reminder.HomepageActivity.onCreate(HomepageActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-28 16:04:52.410 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 1 utanashati.reminder/.HomepageActivity
05-28 16:04:52.411 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 2 utanashati.reminder/.LoginActivity
EDIT 1
I had my eyes opened, the problem is not with LoginActivity, but with HomepageActivity. Here is the code:
import ...
public class HomepageActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected EditText mAddTaskText;
protected Spinner mPrioritySpinner;
protected Button mAddTaskButton;
protected int intPriority = 0;
protected String taskText;
protected Timestamp taskTimestamp;
protected Task userTask;
protected JsonGenerator taskJSON;
#Override
protected void onCreate(Bundle savedInstanceState) { // Starts activity. The state can be restored from savedInstanceState
super.onCreate(savedInstanceState); // Calls the superclass method (IMPORTANT)
setContentView(R.layout.activity_homepage); // Sets layout from activity_homepage.xml
mPrioritySpinner = (Spinner) findViewById(R.id.prioritySpinner); // Creates an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.priorityList, android.R.layout.simple_spinner_item); // Specifies the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Applies the adapter to the spinner
mPrioritySpinner.setAdapter(adapter);
mPrioritySpinner.setOnItemSelectedListener(this);
mAddTaskText = (EditText) findViewById(R.id.addTaskEditText); // Finds View by its id in .xml file
mAddTaskButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomepageActivity.this, "Done!", Toast.LENGTH_LONG).show();
Calendar taskCalendar = Calendar.getInstance(); // Creates new calendar
long taskTime = taskCalendar.getTimeInMillis(); // Gets time in milliseconds
taskTimestamp = new Timestamp(taskTime); // Creates new Timestamp
taskText = mAddTaskText.getText().toString(); // Gets description of the task
userTask.setDate(taskTimestamp); // Sets date
userTask.setText(taskText); // Sets text
/* Creating JsonGenerator */
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(taskJSON, userTask);
}
catch (IOException e) {
Toast.makeText(HomepageActivity.this, "Could not create JSON", Toast.LENGTH_LONG).show();
}
/* Getting out email and password */
String userPassword = ((EmailPassword) HomepageActivity.this.getApplication()).getPassword();
String userEmail = ((EmailPassword) HomepageActivity.this.getApplication()).getUserEmail();
Toast.makeText(HomepageActivity.this, userEmail + " " + userPassword, Toast.LENGTH_LONG).show();
/* HTTP stuff */
HttpPoster get = new HttpPoster();
get.execute(userEmail, userPassword, taskJSON.toString());
}
});
}
public int getData (String username, String password, String taskJSON) {
try {
HttpPost httpPost = new HttpPost("http://something.com/" + username + "/tasks");
String dataToEncode = username + ":" + password;
String encodedData = Base64.encodeToString(dataToEncode.getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", encodedData);
try {
StringEntity taskEntity = new StringEntity(taskJSON, "UTF-8");
httpPost.setEntity(taskEntity);
}
catch (UnsupportedEncodingException e) {
Toast.makeText(HomepageActivity.this, "Unsupported encoding", Toast.LENGTH_LONG).show();
}
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
return 1;
}
else if (statusCode == 404) { return 2; }
else if (statusCode == 500) { return 3; }
else if (statusCode == 409) { return 4; }
else { return statusCode; }
}
catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String priority = parent.getItemAtPosition(pos).toString(); // Gets chosen priority
Toast.makeText(HomepageActivity.this, priority, Toast.LENGTH_LONG).show();
while (!((priority.equals("Low")) || (priority.equals("Medium")) || (priority.equals("High")))) {
Toast.makeText(HomepageActivity.this, "Something bad happened. Try to choose again", Toast.LENGTH_LONG).show();
}
if (priority.equals("Low")) {
intPriority = 0;
}
else if (priority.equals("Medium")) {
intPriority = 1;
}
else if (priority.equals("High")) {
intPriority = 2;
}
userTask.setPriority(intPriority); // Sets chosen priority
}
public void onNothingSelected(AdapterView<?> parent) {
userTask.setPriority(intPriority); // Sets default priority ("0")
}
public class HttpPoster extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(String... params) {
return getData(params[0], params[1], params[3]);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == 1) {
Toast.makeText(HomepageActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent takeUserHome = new Intent(HomepageActivity.this, HomepageActivity.class);
startActivity(takeUserHome);
}
else if (result == 2) {
Toast.makeText(HomepageActivity.this, "No such user", Toast.LENGTH_LONG).show();
}
else if (result == 3) {
Toast.makeText(HomepageActivity.this, "Internal server error: unable to send email", Toast.LENGTH_LONG).show();
}
else if (result == 4) {
Toast.makeText(HomepageActivity.this, "Task already exists", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(HomepageActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
And XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="utanashati.testapp.HomepageActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Add a new task..."
android:id="#+id/addTaskEditText"
android:nestedScrollingEnabled="false"
android:minLines="1"
android:maxLines="1" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/prioritySpinner"
android:layout_alignRight="#+id/addTaskButton"
android:layout_alignEnd="#+id/addTaskButton"
android:layout_below="#+id/addTaskEditText" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add task"
android:id="#+id/addTaskButton"
android:layout_below="#+id/prioritySpinner"
android:layout_centerHorizontal="true" />
</RelativeLayout>
It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout)
Check it.
mAddTaskButton is null because you never initialize it with:
mAddTaskButton = (Button) findViewById(R.id.addTaskButton);
before you call mAddTaskButton.setOnClickListener().
Check out this solution. It worked for me.....
Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app.
If yes, then change the id of them and then the app runs perfectly.
I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!!
Hope it works
That true,Mustafa....its working..its point to two layout
setContentView(R.layout.your_layout)
v23(your_layout).
You should take Button both activity layout...
solve this problem successfully
Check whether you have matching IDs in both Java and XML
Just define the button as lateinit var at top of your class:
lateinit var buttonOk: Button
When you want to use a button in another layout you should define it in that layout. For example if you want to use button in layout which name is 'dialogview', you should write:
buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)
After this you can use setonclicklistener for the button and you won't have any error.
You can see correct answer of this question: Android Kotlin findViewById must not be null
Make sure that while using :
Button "varName" =findViewById("btID");
you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.
Got the same error,
CHECK THIS : MINOR SILLY MISTAKE
check findviewbyid(R.id.yourID);
If you have put the id correct or not.
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
Placing setOnClickListener in onStart method solved the problem for me.
Checkout "Android Lifecycle concept" for further clarification
mAddTaskButton.setOnClickListener(new View.OnClickListener()
you have a click listner but you haven't initialized the mAddTaskButton with your layout binding
Please check whether you have two Layout folder (e.g Layout & Layout-V21). The XML file should be same in both folders. That was the case for me.

Android: NullPointerException: println needs a message;

I am trying to build an app with master and detail layout using fragments and data is coming from from parsing JSOnArray by consuming webservice using Asynctask.
No matter what fixes I apply as suggested for similar issues over various forums, I always see this error from logcat:
FATAL EXCEPTION: main
Process: com.example.masterdetail, PID: 26639
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.masterdetail.ItemsListFragment.populateResult(ItemsListFragment.java:108) //this is the line where I am building an arraylist in ItemsListFragment.java
at com.example.masterdetail.AsyncRequest.onPostExecute(AsyncRequest.java:147)
at com.example.masterdetail.AsyncRequest.onPostExecute(AsyncRequest.java:23)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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)
==================
ItemsListFragment.java:
public void populateResult(String response) {
/*TextView resultView = (TextView)getActivity().findViewById(R.id.textUrlContent);
resultView.setText(response);*/
try {
ListView lvItems = (ListView) getActivity().findViewById(R.id.lvItems);
ArrayList<Item> products = new ArrayList<Item>();
JSONObject jsonObject = new JSONObject(response);
JSONObject responseObj = jsonObject.getJSONObject("response");
JSONArray jsonDataProducts = responseObj.getJSONArray("products");
for (int i = 0; i < jsonDataProducts.length(); i++) {
JSONObject oneObject = jsonDataProducts.getJSONObject(i);
Item dataProduct = new Item();
dataProduct.setTitle(oneObject.getString("title"));
dataProduct.setBody(oneObject.getString("id"));
products.add(dataProduct); //***Line: 108 from above error msg ************
}
adapterItems = new ArrayAdapter<Item>(getActivity(),
android.R.layout.simple_list_item_activated_1, products);
lvItems.setAdapter(adapterItems);
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View item, int position,
long rowId) {
// Retrieve item based on position
Item i = adapterItems.getItem(position);
// Fire selected event for item
listener.onItemSelected(i);
}
});
} catch (Exception e) {
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage());
}
}
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage());,
The e.getlocalizedMessage() is returning null. Check before calling.
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage() == null ? "" : e.getLocalizedMessage());

Updating Listview ( SharedPreferences -> ArrayList) from separate Class

I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)

Categories