AsyncTaskLoader not initialized after screen rotation - android

I am using recyclerview which is getting its data from adapter which gets data trough AsyncTaskLoader. Everything runs fine until I rotate the screen from portrait to landscape. At that point I get nullpointer exception when using .forceLoad(); on my asyncTaskLoader
I have absolutelly no idea why is the fileLoader null when the same onCreate method is called regardless of orientation and it works on portrait and doesnt on landscape.
Here is the code:
package sk.tomus.filescoper;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
mport java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<File>> {
private android.support.v4.content.AsyncTaskLoader<List<File>> fileLoader;
private DirectoryManager directoryManager;
private RecyclerView recyclerView;
private FileRecyclerAdapter recyclerAdapter;
private RecyclerView.LayoutManager layoutManager;
private boolean isLandscape;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
directoryManager = new DirectoryManager(prefs.getString("PREFERENCE_EDIT_DEF_FOLDER", "/"));
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
isLandscape = getResources().getBoolean(R.bool.isLandscape);
if (isLandscape) {
layoutManager = new GridLayoutManager(this, 4);
} else {
layoutManager = new LinearLayoutManager(this);
}
recyclerView.setLayoutManager(layoutManager);
recyclerAdapter = new FileRecyclerAdapter(new ArrayList<File>());
getSupportLoaderManager().initLoader(0, null, this);
//below is line 51 where the code crashes
fileLoader.forceLoad();
recyclerView.setAdapter(recyclerAdapter);
}
#Override
protected void onResume() {
super.onResume();
recyclerAdapter.setOnItemClickListener(new FileRecyclerAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i("LOG", " Clicked on Item " + position);
}
});
}
private void onFileClicked(File file) {
if (file.isDirectory()) {
Log.i("opening directory", file.getAbsolutePath());
if (!file.canRead()) {
Toast.makeText(getApplicationContext(), "inaccessible", Toast.LENGTH_SHORT).show();
return;
}
directoryManager.setPreviousDir(directoryManager.getCurrentDir());
directoryManager.setCurrentDir(file);
if (fileLoader.isStarted()) {
fileLoader.onContentChanged();
}
} else {
openFile(Uri.fromFile(file));
}
}
private void openFile(Uri fileUri) {
String mimeType = directoryManager.getMimeType(fileUri);
if (mimeType != null) {
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(fileUri, mimeType);
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "file type recognized, but no apps to open it", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "unknown file type", Toast.LENGTH_LONG).show();
}
}
#Override
public Loader<List<File>> onCreateLoader(int i, Bundle bundle) {
fileLoader = new android.support.v4.content.AsyncTaskLoader<List<File>>(this) {
#Override
public List<File> loadInBackground() {
Log.i("loader loading:", directoryManager.getCurrentDir().toString());
return directoryManager.getAllFiles(directoryManager.getCurrentDir());
}
};
return fileLoader;
}
#Override
public void onLoadFinished(Loader<List<File>> loader, List<File> data) {
recyclerAdapter.setFiles(data);
}
#Override
public void onLoaderReset(Loader<List<File>> loader) {
}
}
here is the stacktrace:
08-29 00:50:21.176 16411-16411/sk.tomus.filescoper E/AndroidRuntime: FATAL EXCEPTION: main
Process: sk.tomus.filescoper, PID: 16411
java.lang.RuntimeException: Unable to start activity ComponentInfo{sk.tomus.filescoper/sk.tomus.filescoper.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.AsyncTaskLoader.forceLoad()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$900(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.AsyncTaskLoader.forceLoad()' on a null object reference
at sk.tomus.filescoper.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053) 
at android.app.ActivityThread.access$900(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:211) 
at android.app.ActivityThread.main(ActivityThread.java:5389) 
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:1020) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) 
thanks in advance for any help

You shouldn't be calling forceLoad() in your onCreate() method at all - it won't be created until onCreateLoader() is called (which is after onCreate() finishes).
As per the Making Loading Data Lifecycle Aware blog post, you should instead be calling forceLoad() in your AsyncTaskLoader's onStartLoading method. This ensures that your Loader is created and ready to start loading before you call forceLoad().
fileLoader = new android.support.v4.content.AsyncTaskLoader<List<File>>(this) {
#Override
public void onStartLoading() {
forceLoad();
}
#Override
public List<File> loadInBackground() {
Log.i("loader loading:", directoryManager.getCurrentDir().toString());
return directoryManager.getAllFiles(directoryManager.getCurrentDir());
}
};

Related

Cannot transfer downloaded data from activity to fragment using bundle in android

I have been trying to pass some downloaded content from my activity to fragment in vain. I've broken up the steps to see where the error pops up and have made a few conclusions: (i) switching between fragment and activity and vice versa works fine.
(ii) Problem arises only when I enter some data and try to pass it to the fragment from the activity using a bundle.
Here is my fragment code:
package com.antojoh.bottomnavig;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ShopFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ShopFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ShopFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
static ArrayList<String> arrayList = new ArrayList<String>();
static ArrayAdapter<String> arrayAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ShopFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ShopFragment.
*/
// TODO: Rename and change types and number of parameters
public static ShopFragment newInstance(String param1, String param2) {
ShopFragment fragment = new ShopFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_shop, container, false);
ListView listView = (ListView) view.findViewById(R.id.list);
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_checked, arrayList);
listView.setAdapter(arrayAdapter);
CardView cardView = (CardView) view.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), BarcodeActivity.class);
startActivity(intent);
}
});
Bundle bundle = this.getArguments();
if (bundle != null){
String value = bundle.getString("coder");
arrayList.add(value);
arrayAdapter.notifyDataSetChanged();
}
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Shop Fragment", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Here is my Activity Code :
package com.antojoh.bottomnavig;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BarcodeActivity extends AppCompatActivity {
SurfaceView cameraPreview;
private EditText editText;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestCameraPermissionID: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
editText = (EditText) findViewById(R.id.editText);
cameraPreview = (SurfaceView) findViewById(R.id.cameraPreview);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.UPC_A | Barcode.UPC_E | Barcode.EAN_8 | Barcode.EAN_13 | Barcode.CODE_128 | Barcode.CODE_39 | Barcode.CODE_93 | Barcode.ISBN | Barcode.ITF)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.setAutoFocusEnabled(true)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(BarcodeActivity.this, new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0){
update(qrcodes.valueAt(0).rawValue);
}
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result="";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
public void update(String string) {
String result = "";
DownloadTask task = new DownloadTask();
try {
result = task.execute("https://www.barcodable.com/ean/" + string).get();
} catch (Exception e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("<title>UPC (.*?)</title>");
Matcher m = p.matcher(result);
while (m.find()) {
if (m.group(1) != null) {
Bundle bundle = new Bundle();
bundle.putString("coder", m.group(1));
ShopFragment shopFragment = new ShopFragment();
shopFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.cont, shopFragment).commit();
}
}
}
public void enter(View view){
update(editText.getText().toString());
}
}
And the Logcat :
08-14 14:46:03.037 5419-5460/com.antojoh.bottomnavig W/System.err: java.io.FileNotFoundException: https://www.barcodable.com/ean/9781614272137
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at com.antojoh.bottomnavig.BarcodeActivity$DownloadTask.doInBackground(BarcodeActivity.java:144)
at com.antojoh.bottomnavig.BarcodeActivity$DownloadTask.doInBackground(BarcodeActivity.java:134)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
08-14 14:46:03.038 5419-5460/com.antojoh.bottomnavig W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
08-14 14:46:03.041 5419-5419/com.antojoh.bottomnavig E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antojoh.bottomnavig, PID: 5419
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
at java.util.regex.Matcher.reset(Matcher.java:995)
at java.util.regex.Matcher.<init>(Matcher.java:174)
at java.util.regex.Pattern.matcher(Pattern.java:1006)
at com.antojoh.bottomnavig.BarcodeActivity.update(BarcodeActivity.java:171)
at com.antojoh.bottomnavig.BarcodeActivity.enter(BarcodeActivity.java:190)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
It was simple. The website did not accept too many requests at a time( which I did). So all i had to do was either switch to another website or wait for a specific time to gain entry for requesting access again! Thanks!

Compare 2 arraylist with SharedPref UserId on it

I wanna compare 2 ArrayList from LatestFragment and ApplyFragment. ApplyFragment contains ArrayList from the user. But, when I compare it, the following error appears. How to getUserId() from SharedPref when im comparing this 2 ArrayList?
this is the comparison in JobAdapter.java
for (ItemJob itemJob : LatestFragment.mListItem){
boolean found = false;
for (ItemJob itemJob2 : ApplyFragment.mListItem) {
if (itemJob2.id == itemJob.id)
btnApplyJob.setText(R.string.applied);
found = true;
}
if(!found){
btnApplyJob.setText(R.string.apply_now);
}
}
ApplyFragment.java
package com.data.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.app.hero.MyApplication;
import com.app.hero.R;
import com.data.adapter.JobAdapter;
import com.data.adapter.JobProviderAdapter;
import com.data.item.ItemJob;
import com.data.util.Constant;
import com.data.util.ItemOffsetDecoration;
import com.data.util.JsonUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by laxmi.
*/
public class ApplyFragment extends Fragment {
public static ArrayList<ItemJob> mListItem;
public RecyclerView recyclerView;
JobAdapter adapter;
private ProgressBar progressBar;
private LinearLayout lyt_not_found;
MyApplication MyApp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.row_recyclerview, container, false);
MyApp = MyApplication.getInstance();
mListItem = new ArrayList<>();
lyt_not_found = rootView.findViewById(R.id.lyt_not_found);
progressBar = rootView.findViewById(R.id.progressBar);
recyclerView = rootView.findViewById(R.id.vertical_courses_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(getActivity(), R.dimen.item_offset);
recyclerView.addItemDecoration(itemDecoration);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new getLatest().execute(Constant.USERS_JOB_APPLIED_LIST + MyApp.getUserId());
}
return rootView;
}
private class getLatest extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(true);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showProgress(false);
if (null == result || result.length() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.ARRAY_NAME);
JSONObject objJson;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemJob objItem = new ItemJob();
objItem.setId(objJson.getString(Constant.JOB_ID));
objItem.setJobName(objJson.getString(Constant.JOB_NAME));
objItem.setJobCompanyName(objJson.getString(Constant.JOB_COMPANY_NAME));
objItem.setJobDate(objJson.getString(Constant.JOB_DATE));
objItem.setJobDateFrom(objJson.getString(Constant.JOB_DATEFROM));
objItem.setJobDateTo(objJson.getString(Constant.JOB_DATETO));
objItem.setJobDesignation(objJson.getString(Constant.JOB_DESIGNATION));
objItem.setJobAddress(objJson.getString(Constant.JOB_ADDRESS));
objItem.setJobImage(objJson.getString(Constant.JOB_IMAGE));
mListItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
displayData();
}
}
}
private void displayData() {
adapter = new JobAdapter(getActivity(), mListItem);
recyclerView.setAdapter(adapter);
if (adapter.getItemCount() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
lyt_not_found.setVisibility(View.GONE);
}
}
private void showProgress(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
lyt_not_found.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
}
And This is the error
Process: com.app.hero, PID: 25830
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.app.hero.MyApplication.getUserId()' on a null object reference
at com.data.fragment.ApplyFragment.onCreateView(ApplyFragment.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:700)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
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)
'java.lang.String com.app.hero.MyApplication.getUserId()' on a null object reference
you got this error because your UserId() is not set properly and you try to getUserId().
I guess everything is perfect just check your sharedPreference have all your UserData.

"Unfortunately, App has stopped" After clicking the Item in ListView to Fragment Activity

I'm a beginner for doing this application and I encounter this problem after I put Listview in Tab Activity. In Listview there are items are onclick to go for the new activity (That activity is fragment) for VR Panorama View I will display the codes and logcat.
ImageLoaderTask
package com.example.computer.vratdragfinal;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;
import java.lang.ref.WeakReference;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
public class ImageLoaderTask extends AsyncTask<AssetManager, Void, Bitmap> {
private static final String TAG = "ImageLoaderTask";
private final String assetName;
private final WeakReference<VrPanoramaView> viewReference;
private final VrPanoramaView.Options viewOptions;
private static WeakReference<Bitmap> lastBitmap = new WeakReference<>(null);
private static String lastName;
#Override
protected Bitmap doInBackground(AssetManager... params) {
AssetManager assetManager = params[0];
if (assetName.equals(lastName) && lastBitmap.get() != null) {
return lastBitmap.get();
}
try(InputStream istr = assetManager.open(assetName)) {
Bitmap b = BitmapFactory.decodeStream(istr);
lastBitmap = new WeakReference<>(b);
lastName = assetName;
return b;
} catch (IOException e) {
Log.e(TAG, "Could not decode default bitmap: " + e);
return null;
}
}
#Override
protected void onPostExecute(Bitmap bitmap) {
final VrPanoramaView vw = viewReference.get();
if (vw != null && bitmap != null) {
vw.loadImageFromBitmap(bitmap, viewOptions);
}
}
public ImageLoaderTask(VrPanoramaView view, VrPanoramaView.Options viewOptions, String assetName) {
viewReference = new WeakReference<>(view);
this.viewOptions = viewOptions;
this.assetName = assetName;
}
}
MainActivity
package com.example.computer.vratdragfinal;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
assert tabLayout != null;
tabLayout.addTab(tabLayout.newTab().setText(R.string.welcome));
tabLayout.addTab(tabLayout.newTab().setText(R.string.venue));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new WelcomeFragment();
case 1:
return new ttsd();
}
return null;
}
#Override
public int getCount() {
return 2;
}
};
assert viewPager != null;
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void refreshNow() {
finish();
overridePendingTransition(0,0);
startActivity(getIntent());
overridePendingTransition(0,0);
}
}
toptourist1
package com.example.computer.vratdragfinal;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;
public class toptourist1 extends Fragment {
private VrPanoramaView panoWidgetView;
private ImageLoaderTask backgroundImageLoaderTask;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_toptourist1, container,false);
panoWidgetView = (VrPanoramaView) v.findViewById(R.id.pano_view);
return v;
}
#Override
public void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
public void onResume() {
panoWidgetView.resumeRendering();
super.onResume();
}
#Override
public void onDestroy() {
panoWidgetView.shutdown();
super.onDestroy();
}
private synchronized void loadPanoImage() {
ImageLoaderTask task = backgroundImageLoaderTask;
if (task != null && !task.isCancelled()) {
task.cancel(true);
}
VrPanoramaView.Options viewOptions = new VrPanoramaView.Options();
viewOptions.inputType = VrPanoramaView.Options.TYPE_STEREO_OVER_UNDER;
String panoImageName = "sample_converted.jpg";
task = new ImageLoaderTask(panoWidgetView, viewOptions, panoImageName);
task.execute(getActivity().getAssets());
backgroundImageLoaderTask = task;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadPanoImage();
}
}
ttsd
package com.example.computer.vratdragfinal;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
import android.widget.AdapterView;
public class ttsd extends Fragment {
public ttsd() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ttsd, container, false);
// Inflate the layout for this fragment
String[] awayStrings = {
"Tubbataha Reef",
"San Agustin Church",
"Mayon Volcano",
"Malapascua Island",
"Puerto Galera",
"Puerto Princesa Undergound River",
"Donsol",
"Banaue Rice Terraces",
};
ListView lv = (ListView) view.findViewById(R.id.listView2);
ArrayAdapter<String> lva = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1, awayStrings);
lv.setAdapter(lva);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position==0) {
Intent myintent = new Intent(view.getContext(), toptourist1.class);
startActivityForResult(myintent, 0);
}
}
});
final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.fragment_away);
mSwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
((MainActivity) getActivity()).refreshNow();
Toast.makeText(getContext(), "Refresh Layout working", Toast.LENGTH_LONG).show();
}
}
);
return view;
}
}
ViewPageAdapter
package com.example.computer.vratdragfinal;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
public class ViewPageAdapter extends FragmentPagerAdapter{
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments (Fragment fragments,String tabTitles){
this.fragments.add(fragments);
this.tabTitles.add(tabTitles);
}
public ViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
**WelcomeFragment**
package com.example.computer.vratdragfinal;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;
public class WelcomeFragment extends Fragment {
private VrPanoramaView panoWidgetView;
private ImageLoaderTask backgroundImageLoaderTask;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.welcome_fragment, container,false);
panoWidgetView = (VrPanoramaView) v.findViewById(R.id.pano_view);
return v;
}
#Override
public void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
public void onResume() {
panoWidgetView.resumeRendering();
super.onResume();
}
#Override
public void onDestroy() {
panoWidgetView.shutdown();
super.onDestroy();
}
private synchronized void loadPanoImage() {
ImageLoaderTask task = backgroundImageLoaderTask;
if (task != null && !task.isCancelled()) {
task.cancel(true);
}
VrPanoramaView.Options viewOptions = new VrPanoramaView.Options();
viewOptions.inputType = VrPanoramaView.Options.TYPE_STEREO_OVER_UNDER;
String panoImageName = "converted.jpg";
task = new ImageLoaderTask(panoWidgetView, viewOptions, panoImageName);
task.execute(getActivity().getAssets());
backgroundImageLoaderTask = task;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadPanoImage();
}
}
Run
02/13 16:35:13: Launching app
$ adb shell am start -n "com.example.computer.vratdragfinal/com.example.computer.vratdragfinal.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 7627 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
W/SdkConfigurationReader: VrParamsProvider returned null params, using defaults.
D/ConfigUtils: Parameters file not found for reading: java.io.FileNotFoundException: /storage/sdcard/Cardboard/current_device_params: open failed: ENOENT (No such file or directory)
I/GVR: [vr/gvr/capi/src/gvr.cc:94] Initialized GVR version 1.10.0
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
W/art: Attempt to remove local handle scope entry from IRT, ignoring
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.computer.vratdragfinal, PID: 7627
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.computer.vratdragfinal/com.example.computer.vratdragfinal.toptourist1}: java.lang.ClassCastException: com.example.computer.vratdragfinal.toptourist1 cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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:5254)
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.ClassCastException: com.example.computer.vratdragfinal.toptourist1 cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
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:5254) 
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) 
Application terminated.
You can't simply say here Activity is a fragment and can not redirect from one fragment to another using Intent. Intent is used to switch between activities. That's the reason behind the crash. Either use the mechanism by which you can redirect to fragment or if you want to use intent, you need to use activity instead of fragment.

Firebase error "invoke virtual method" on null object when object should be initialized

I keep getting a null object error and my app crashes, though I don't see why there should be an error. I have looked at other examples and those are all the same, and don't help with my issue. My issue occurring although from what I have seen it shouldn't be. The code is:
package com.example.matthew.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class makecharact extends Activity {
Button retur, mak, cont;
FirebaseUser user;
DataSnapshot datasss;
Spinner spinner2;
List<String> list = new ArrayList<String>();
String id;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.charlist);
Intent task = getIntent();
retur = (Button) findViewById(R.id.returnToLast);
mak = (Button) findViewById(R.id.make);
cont = (Button) findViewById(R.id.Conti);
addListenerOnButton();
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
datasss = dataSnapshot;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
myRef = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("Test Point 1", "Got to line 61 at the least");
id = user.getUid();
int check = 0;
boolean done = false;
Log.d("User ID", id);
while(done == false) {
String sCheck = Integer.toString(check);
if (datasss.hasChild(id) == true){
if(datasss.child(id).hasChild("Character List") == true){
if (datasss.child(id).child("Character List").hasChild(sCheck) == true) {
list.add(datasss.child(id).child("Character List").child(sCheck).getValue().toString());
check = check + 1;
}else{
done = false;
}
}else{
list.add("No characters");
done = true;
}
}
}
ArrayAdapter<String> dataset = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
dataset.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataset);
Log.d("Test Point 2", "Got to line 77 at the least");
}
public void addListenerOnButton() {
cont.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String stats;
stats = spinner2.getSelectedItem().toString();
myRef.child(id).child("Current Character").setValue(stats);
Intent TaskIntent = new Intent(getApplicationContext(), MainScreen.class);
startActivity(TaskIntent);
finish();
}
});
mak.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Log.d(TAG, "Moving");
Intent TaskIntent = new Intent(getApplicationContext(), spinner.class);
startActivity(TaskIntent);
finish();
}
});
retur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Moving");
finish();
}
});
}
}
My logcat shows:
05-31 21:05:39.802 14318-14318/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.matthew.myapplication, PID: 14318
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matthew.myapplication/com.example.matthew.myapplication.makecharact}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.database.DataSnapshot.hasChild(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:223)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.database.DataSnapshot.hasChild(java.lang.String)' on a null object reference
at com.example.matthew.myapplication.makecharact.addListenerOnButton(makecharact.java:81)
at com.example.matthew.myapplication.makecharact.onCreate(makecharact.java:45)
at android.app.Activity.performCreate(Activity.java:6877)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
at android.app.ActivityThread.access$1100(ActivityThread.java:223) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7223) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
I have tried a lot though I still don't get why it isn't working. Any help is appreciated, even if it is it's already been solved on another post (which i couldn't find with a link to said post. Thanks
Yes it will return Null pointer exception Because your variable dataass not initialized.
and its is initialized only when ValueEventListener() is triggers onDataChange() So you need to execute every thing inside the onDataChange()
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
datasss = dataSnapshot;myRef = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("Test Point 1", "Got to line 61 at the least");
id = user.getUid();
int check = 0;
boolean done = false;
Log.d("User ID", id);
while(done == false) {
String sCheck = Integer.toString(check);
if (datasss.hasChild(id) == true){
if(datasss.child(id).hasChild("Character List") == true){
if (datasss.child(id).child("Character List").hasChild(sCheck) == true) {
list.add(datasss.child(id).child("Character List").child(sCheck).getValue().toString());
check = check + 1;
}else{
done = false;
}
}else{
list.add("No characters");
done = true;
}
}
}
ArrayAdapter<String> dataset = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
dataset.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataset);
Log.d("Test Point 2", "Got to line 77 at the least");
}
You can get firebase data like this.
DatabaseReference databaseTracks;
List<Track> tracks;
databaseTracks = FirebaseDatabase.getInstance().getReference("tracks").child(intent.getStringExtra(MainActivity.ARTIST_ID));
#Override
protected void onStart() {
super.onStart();
databaseTracks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tracks.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Track track = postSnapshot.getValue(Track.class);
tracks.add(track);
}
TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks);
listViewTracks.setAdapter(trackListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

How to restore Recyclerview after rotation with onRestoreInstanteState()

I have a fragment that needs to restore the its containing RecyclerView upon screen rotation. I've been using the standard procedure with onViewStateRestored() and onSaveInstantState(). However, I'm getting a null point exception when I rotate the screen. The problem arises during onCreate() as shown on my code and logcat below. Any detailed instructions on what I'm doing wrong would be greatly appreciated.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import org.json.JSONObject;
import static uk.co.my_package.weatherscan.Utils.getForecastEndPoint;
public class PlaceForecastListFragment extends Fragment {
public static final String PAGERTABTITLE = "Forecast";
private static final String CITYID = "weather_cityid";
private static final String SEVENDAYS = "7";
private static final String LIST_STATE_KEY = "list_state";
private static final String TAG = PlaceForecastListFragment.class.getSimpleName();
private LinearLayoutManager mLinearLayoutManager;
private RecyclerView mRecyclerView;
private Parcelable mListState;
private ProgressDialog pDialog;
private String mCityId;
public PlaceForecastListFragment() {
// Required empty public constructor
}
public static PlaceForecastListFragment newInstance(String cityid) {
PlaceForecastListFragment fragment = new PlaceForecastListFragment();
Bundle args = new Bundle();
args.putString(CITYID, cityid);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mCityId = getArguments().getString(CITYID);
}
if (savedInstanceState == null) {
// Shows message to user while makeJsonObjectRequest() is still running.
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Getting weather forecast...");
pDialog.setCancelable(false);
// Make JSON request
makeJsonObjectRequest(mCityId);
} else {
// Problem arises here!!!!!!!!!!!!!!!!!!!!
mLinearLayoutManager.onRestoreInstanceState(mListState);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_place_forecast_list, container, false);
if (view instanceof RecyclerView) {
Context context = view.getContext();
mRecyclerView = (RecyclerView) view;
mLinearLayoutManager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
}
return view;
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
mListState = savedInstanceState.getParcelable(LIST_STATE_KEY);
mRecyclerView.getLayoutManager().onRestoreInstanceState(mListState);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstantState) {
super.onSaveInstanceState(savedInstantState);
//mListState = mLinearLayoutManager.onSaveInstanceState();
savedInstantState.putParcelable(LIST_STATE_KEY, mRecyclerView.getLayoutManager().onSaveInstanceState());
}
// TODO CBA: Move this method to its own class and call it from here. This will be more organized.
/**
* Method to make json object request
*/
private void makeJsonObjectRequest(final String cityId) {
showpDialog();
String url = getForecastEndPoint(cityId, SEVENDAYS);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log response
Log.d(TAG, response.toString());
String responseString = String.valueOf(response);
Gson gson = new Gson();
ResponseForecastConditions responseForecastConditionsObj =
gson.fromJson(responseString, ResponseForecastConditions.class);
mRecyclerView.setAdapter(new ForecastAdapter(responseForecastConditionsObj,
getContext()));
// Hide dialog after information has been requested
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Warn user
Toast.makeText(getContext(),
"No internet connection", Toast.LENGTH_LONG).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Method for showing dialog
*/
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
/**
* Method for hiding dialog
*/
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Below is the logcat output:
03-20 16:32:40.801 6371-6405/uk.co.my_package.weatherscan E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7cfcb0
03-20 16:32:40.823 6371-6371/uk.co.my_package.weatherscan D/AndroidRuntime: Shutting down VM
03-20 16:32:40.823 6371-6371/uk.co.my_package.weatherscan E/AndroidRuntime: FATAL EXCEPTION: main
Process: uk.co.my_package.weatherscan, PID: 6371
java.lang.RuntimeException: Unable to start activity ComponentInfo{uk.co.my_package.weatherscan/uk.co.my_package.weatherscan.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.LinearLayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
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.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.LinearLayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference
at uk.co.my_package.weatherscan.PlaceForecastListFragment.onCreate(PlaceForecastListFragment.java:68)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1234)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:2041)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1964)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1234)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:2041)
at android.support.v4.app.FragmentController.dispatchCreate(FragmentController.java:163)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:332)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:74)
at uk.co.my_package.weatherscan.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
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)
03-20 16:33:58.373 6371-6378/uk.co.my_package.weatherscan W/art: Suspending all threads took: 24.263ms
03-20 16:34:04.875 6371-6378/uk.co.my_package.weatherscan W/art: Suspending all threads took: 17.116ms
03-20 16:36:28.696 6371-6378/uk.co.my_package.weatherscan W/art: Suspending all threads took: 15.452ms
03-20 16:37:40.836 6371-6371/? I/Process: Sending signal. PID: 6371 SIG: 9
mLinearLayoutManager is null in onCreate because you create it in onCreateView(). Create an instance in onCreate and reuse it in onCreateView.
I have a fragment that needs to restore the its containing
RecyclerView upon screen rotation. I've been using the standard
procedure with onViewStateRestored() and onSaveInstantState().
However, I'm getting a null point exception when I rotate the screen.
you have done it wrongly. You do not need to save layoutManager for rotation changes, just instantiate it every time. if you have any other DATA save them and use them to create your layoutManager.

Categories

Resources