transfer List from activity to fragment in Android - Android Q&A, Help & Troubleshooting

Hello,
I have an activity:
public List<Steps> steps;
Recipe recipe;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity);
///..........
steps = recipe.getRecipeSteps();
int len1 = steps.size();
Log.i(TAG, "Steps length=" + len1);
}
public List<Steps> getMyData() {
return steps;
}
and a fragment
public class FragmentStepTitle extends Fragment {
// Whether the app has two panel( tablet ) or one panel( phone ).
//private boolean hasTwoPanel = false;
@nullable
@override
public View onCreateView(LayoutInflater inflater, @nullable ViewGroup container, @nullable Bundle savedInstanceState) {
.....
//receive info from detail
DetailActivity activity = (DetailActivity) getActivity();
List<Steps> myDataFromActivity = activity.getMyData();
Log.i("Fragment",myDataFromActivity.get(0).getShortDescription());
return ret;
}
}
The error caused is:
Attempt to invoke interface method ‘java.lang.Object java.util.List.get(int)’ on a null object reference
at com.example.ionutb.baking.ui.FragmentStepTitle.onCreateView
Why I don-t see the List value??

Related

Using multiple drawables with MapsForge

After following the developer tutorial using Google Maps, my code is crashing when trying to execute the map code from the start up screen. I am trying to add Big East basketball team icons on the map in the correct GPS location. When that part of the code is taken out it works but I can't find what I'm doing wrong. Thanks for any help you can provide.
Here is the map code:
Code:
public class MapsForgeViewer extends MapActivity implements LocationListener, OnClickListener {
private static final double latitudePitt = 40.443061;
private static final double longitudePitt = -79.962273;
private static final double latitudeUConn = 41.807975;
private static final double longitudeUConn = -72.253626;
private MapView mapView;
private GeoPoint myCurrentLocation;
private Button findPosition;
private Button roster;
private Button schedule;
private Button stats;
private Button exit;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.map_view);
// setting up the location listener
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
100, 0, mlocListener);
// end of location listener setup
// find from XML and set onClickListeners
findPosition = (Button) findViewById(R.id.findPositionButton);
roster = (Button) findViewById(R.id.roster);
schedule = (Button) findViewById(R.id.schedule);
stats = (Button) findViewById(R.id.stats);
exit = (Button) findViewById(R.id.exit);
findPosition.setOnClickListener(this);
roster.setOnClickListener(this);
schedule.setOnClickListener(this);
stats.setOnClickListener(this);
exit.setOnClickListener(this);
// end of mapView layout setup
// setting the up the map at the proper zoom level and creating the
// scale bars and buttons
mapView = (MapView) findViewById(R.id.mapView);
mapView.setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
mapView.setBuiltInZoomControls(true);
mapView.setScaleBar(true);
mapView.setClickable(true);
findPositionButton(myCurrentLocation);
mapView.getController().setZoom(14);
setCenterlocation();
// end of mapView setup
//Put pins on map
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawablePitt = this.getResources().getDrawable(R.drawable.pittspin);
CustomItemizedOverlay itemizedOverlayPitt = new CustomItemizedOverlay(drawablePitt, this);
Drawable drawableUConn = this.getResources().getDrawable(R.drawable.connpin);
CustomItemizedOverlay itemizedOverlayUConn = new CustomItemizedOverlay(drawableUConn, this);
//Create points using latitude and longitude
GeoPoint pointPitt = new GeoPoint(latitudePitt, longitudePitt);
OverlayItem overlayitemPitt = new OverlayItem(pointPitt, "Pitt", "Panthers");
GeoPoint pointUConn = new GeoPoint(latitudeUConn, longitudeUConn);
OverlayItem overlayitemUConn = new OverlayItem(pointUConn, "UConn", "Huskies");
itemizedOverlayPitt.addOverlay(overlayitemPitt);
itemizedOverlayUConn.addOverlay(overlayitemUConn);
//add to map
mapOverlays.add(itemizedOverlayPitt);
mapOverlays.add(itemizedOverlayUConn);
}
public void onClick(View v)
{
switch (v.getId())
{
case (R.id.findPositionButton):
findPositionButton(myCurrentLocation);
break;
case (R.id.roster):
// get data from database
break;
case (R.id.schedule):
break;
case (R.id.stats):
break;
// close the app
case (R.id.exit):
finish();
break;
}
}
public void findPositionButton(GeoPoint p)
{
mapView.getController().setCenter(p);
}
@Override
// resumes the actions of the application on a pause
protected void onResume()
{
super.onResume();
}
// sets the center of the screen on the map
protected void setCenterlocation()
{
if (myCurrentLocation == null)
mapView.getController().setCenter(new GeoPoint(39.00, -100.00));
else
mapView.getController().setCenter(myCurrentLocation);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
GeoPoint gp = new GeoPoint(loc.getLatitude(), loc.getLongitude());
if (gp != null)
myCurrentLocation = gp;
}
// activates when the current provider is disabled, or inactive
public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(), "GPS Disabled",
Toast.LENGTH_LONG).show();
}
// activates when a provider is found.
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "GPS Enabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void onLocationChanged(Location arg0)
{
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
CustomItemizedOverlay:
Code:
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public MapsForgeViewer mActivtyl;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
@Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
@Override
public int size() {
return mapOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}

[Q] Options menu problem

I'm trying to get a working option menu, and I can get it to work with any activity i got in my app, but not the Main one. that's mean, whenever i try to access the main activity from the option menu, i get an error. here is the main activity, maybe it'll help:
public class Main extends Activity {
private ContentResolver cResolver;
private Window window;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPrefsBrightness();
SharedPreferences sp1 = getSharedPreferences("ButtonData", MODE_PRIVATE);
boolean cbValue = sp1.getBoolean("ButtonData", false);
if(cbValue){
Music.play(this, R.raw.japanese_garden);
Music.stoping();
}else{
Music.play(this, R.raw.japanese_garden);
}
SharedPreferences sp3 = getSharedPreferences("SleepData", MODE_PRIVATE);
boolean cbValue2 = sp3.getBoolean("SleepData", false);
if(cbValue2){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
public void loadPrefsBrightness() {
SharedPreferences sp2 = getSharedPreferences("BrightnessData", MODE_PRIVATE);
int bnessValue = sp2.getInt("BrightnessData", 150);
cResolver = getContentResolver();
window = getWindow();
android.provider.Settings.System.putInt(cResolver, android.provider.Settings.System.SCREEN_BRIGHTNESS, bnessValue);
LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = bnessValue / (float)255;
window.setAttributes(layoutpars);
}
public void setting_onclick(View view) {
Intent i = new Intent("net.lirazarviv.Setting");
startActivity(i);
}
public void free_search_onclick(View view) {
Intent i = new Intent("net.lirazarviv.FreeSearch");
startActivity(i);
}
public void search_by_type_onclick(View view) {
Intent i = new Intent("net.lirazarviv.SearchByType");
startActivity(i);
}
public void search_by_difficulty_onclick(View view) {
Intent i = new Intent("net.lirazarviv.SearchByDifficulty");
startActivity(i);
}
public void info_onclick(View view) {
Intent i = new Intent("net.lirazarviv.Info");
startActivity(i);
}
@override
protected void onPause() {
if (this.isFinishing()){ //basically BACK was pressed from this activity
Music.stop();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
Music.stop();
}
}
super.onPause();
}
}
Why not post the logcat of eclipse? It will help to track down the bug easier
Sent from my GT-N7000 using xda app-developers app

[Q] Fragment null pointer after orientation change

Hi
I have a class Fragment_b extends Fragment with
Code:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b_layout, container, false);
return view;
}
frag_b_layout with root element of ScrollView containing a RelativeLayout with @+id/dummy for Android Studio ID sake.
in the container Activity
Code:
public class MainActivity extends ActionBarActivity{
Fragment_b fragment_b;
FragmentManager manager;
//...
FragmentTransaction transaction = manager.beginTransaction();
public void myFunc(){
if (fragment_b == null){
fragment_b = new Fragment_b();
transaction.add(R.id.container_activity_layout, fragment_b, "someTag");
transaction.commit();
//...
}
}
//...
}
All works fine, but when device orientation changes, fragment_b appears again but with fragment_b == null returns true, I was expecting false. what can I do so that it works as I expect?
for no avail, I tried
in the AndroidManifest
Code:
android:windowSoftInputMode="stateUnchanged|adjustResize"
in the onCreate of fragment_b
Code:
this.setRetainInstance(true);
Thank you

[Q] referencing a dynamica fragment

Hi
Frag1 which is a side navigation drawer, is instantiated in MainActivity.java onCreate by manager.findFragmentById since there is a fragment tag in a xml file.
Frag2 and Frag3 are dynamically committed at some point by a manager, non of their layouts contain a <fragment> tag, they are not committed in the MainActivity onCreate method and thus don't have ids or tags either.
When a button on frag2 is pressed, frag3 "a dialogFragment" needs to be displayed on the screen for user login inputs.
How can I get this to work? I am getting null pointer when referencing frag2 in MainActivity.
here is a illustrative stripped down version of the code. sorry for any unintended typos
Thank you for helping
Frag2.java
Code:
public class Frag2 extends Fragment {
Frag2Communicator = mFrag2communicator;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag2_layout, container, false);
class ClickHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
mFrag2communicator.show_frag3();
}
}
}
public interface Frag2Communicator {
public void show_frag3();
}
public void setFrag2Communicator(Frag2Communicator frag2communicator) {
mFrag2communicator = frag2communicator;
}
}
MainActivity.java
Code:
public class MainActivity extends ActionBarActivity implements frag2.frag2Communicator {
protected void onCreate(Bundle savedInstanceState) {
Frag2 frag2 = getSupportFragmentManager().findFragmentById(R.id.frag_2);
//frag_2 is the id of a RelativeLayout inside a ScrollView inside frag2_layout.xml
//I tried to move this ide to the root tag "ScrollView" but still get a null pointer.
frag2.setFrag2Communicator(this);
public void show_frag3(){
FragmentManager manager = getSupportFragmentManager();
Frag3 frag_3 = new Frag3();
frag_3.show(manager, "loging");
}
}
}

Camera2 API running in background service

Hello everybody
Unfortunately, I have too few post to make a thread in the " Android Software Development" forum. I would be very happy if this post can be moved to it.
I have used the Camera2 API to implement a background video recorder running as a service and recording from the front cam. For this I have created a new SurfaceView, set its size to 1x1 and moved it to the top left corner. My code is shown below. I'm using Android 5.1.
With the Camera API it worked very well but unfortunately the frame rate is only at 20 fps (and when I increase the exposure compensation it drops even more), although with the Open Camera app I have 30 fps also with increased exposure compensation. That is why I want to try Camera2 API (hoping to get higher fps). Unfortunately, I'm getting the following error:
MediaRecoder: setOutputFile called in an invalid state(2)
MediaRecorder: start called in an invalid state: 2
Click to expand...
Click to collapse
Here is my code:
Code:
public class RecorderServiceCamera2 extends Service implements SurfaceHolder.Callback {
private WindowManager windowManager;
private SurfaceView surfaceView;
private CameraDevice mCamera;
private MediaRecorder mediaRecorder = null;
private CaptureRequest mCaptureRequest;
private CameraCaptureSession mSession;
@Override
public void onCreate() {
// Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
//.setSmallIcon(R.mipmap.app_icon)
.setContentTitle("Background Video Recorder")
.setContentText("")
.setContentIntent(pendingIntent).build();
startForeground(MainActivity.NOTIFICATION_ID_RECORDER_SERVICE, notification);
return Service.START_NOT_STICKY;
}
@Override
public void surfaceCreated(final SurfaceHolder surfaceHolder) {
mediaRecorder = new MediaRecorder();
try {
CameraManager manager = (CameraManager) getSystemService(CAMERA_SERVICE);
String[] cameras = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameras[1]);
StreamConfigurationMap configs = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] sizes = configs.getOutputSizes(MediaCodec.class);
final Size sizeHigh = sizes[0];
manager.openCamera(cameras[1], new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
mCamera = camera;
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setMaxFileSize(0);
mediaRecorder.setOrientationHint(0);
mediaRecorder.setOutputFile("test.mp4");
try { mediaRecorder.prepare(); } catch (Exception ignored) {}
List<Surface> list = new ArrayList<>();
list.add(surfaceHolder.getSurface());
try {
CaptureRequest.Builder captureRequest = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
captureRequest.addTarget(surfaceHolder.getSurface());
mCaptureRequest = captureRequest.build();
} catch (CameraAccessException e) {
e.printStackTrace();
}
try {
mCamera.createCaptureSession(list, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
mSession = session;
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
mSession = session;
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
mediaRecorder.start();
try {
mSession.setRepeatingRequest(mCaptureRequest,
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
super.onCaptureStarted(session, request, timestamp, frameNumber);
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
}
@Override
public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
// Stop recording and remove SurfaceView
@Override
public void onDestroy() {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mCamera.close();
mediaRecorder= null;
windowManager.removeView(surfaceView);
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {}
@Override
public IBinder onBind(Intent intent) { return null; }
}
Hi, were you able to get this code to work without the errors?

Categories

Resources