I don't know how to custom my own Fragment which inherite another Fragment class.
I'd like to add button and catch every click on them, but I don't how to do that.
As you'll see, I'm using actionBarSherlock and Zxing (a sub-library of Zxing actually: "barcodeFragLibV2") and the navigation drawer.
Here my code:
MainActivity.java:
public class MainActivity extends SherlockFragmentActivity {
private static final String TAG = MainActivity.class.getSimpleName();
/**
* The navigation drawer layout.
*/
DrawerLayout mDrawerLayout;
/**
* The elements list of the menu.
*/
ListView mDrawerList;
/**
* The button to open/close the menu.
*/
ActionBarDrawerToggle mDrawerToggle;
/**
* The helper item of the local database.
*/
private DatabaseHelper dbHelper = null;
/**
* The current fragment title.
*/
String mTitle = "";
/**
* #author LG
* #category Property
*/
private boolean mShowOptionMenu;
private int fragmentStatus = 0;
private Menu mMenu = null;
private MenuItem mGoItem;
private static final int GO_ITEM_ID = 1;
private static final int CLEAR_ITEM_ID = 2;
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
/**
* Method called when the activity is loaded.
*
* #param savedInstanceState
* the bundle sent.
*/
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "================= onCreate =================");
if (!isTablet()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.activity_main);
mTitle = (String) getTitle();
mShowOptionMenu = false;
// result_view = findViewById(R.id.result_view);
// result_view.setVisibility(View.GONE);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
MenuListAdapter adapter = new MenuListAdapter(getBaseContext());
mDrawerList.setAdapter(adapter);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
displayView(position);
}
private void displayView(int position) {
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
MainActivity.this.fragmentStatus = position;
SherlockFragment rFragment = null;
Log.d(TAG, "================= mDrawerList.setOnItemClickListener =================");
if (position == 0)
rFragment = new SearchFragment();
else if (position == 1) {
mShowOptionMenu = true;
rFragment = new AdvanceSearchFragment();
} else if (position == 2) {
rFragment = new QrCodeScannerFragment(); // WORKS
} else if (position == 3)
rFragment = new FavorisFragment();
else if (position == 4)
rFragment = new HistoriqueFragment();
else if (position == 5)
rFragment = new InformationsFragment();
if (rFragment != null) {
Bundle data = new Bundle();
data.putInt("position", position);
rFragment.setArguments(data);
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.getBackStackEntryCount() > 0)
fragmentManager.popBackStackImmediate();
FragmentTransaction ft = fragmentManager.beginTransaction();
// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.content_frame, rFragment);
ft.addToBackStack(null);
ft.commit();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
);
SearchFragment rFragment = new SearchFragment();
Bundle data = new Bundle();
rFragment.setArguments(data);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, rFragment);
ft.commit();
}
/**
* Method called after the activity is loaded.
*
* #param savedInstanceState
* the bundle sent.
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Log.d(TAG, "================= onPostCreate =================");
mDrawerToggle.syncState();
}
/**
* Inflate the menu; this adds items to the action bar if it is present.
*
* #param menu
* the menu
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "================= onCreateOptionsMenu ================= fragSt: " + fragmentStatus);
getSupportMenuInflater().inflate(R.menu.main, (Menu) menu);
if (fragmentStatus == 1) {
Log.i(TAG, "Show optionMenu");
mGoItem = menu.add(0, GO_ITEM_ID, 0, null);
mGoItem.setIcon(R.drawable.abs__ic_go).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mShowOptionMenu = false;
}
return true;
}
/**
* Called whenever we call invalidateOptionsMenu()
*
* #param menu
* the menu
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
Log.d(TAG, "================= onPrepareOptionsMenu ================= fragSt: " + fragmentStatus);
return super.onPrepareOptionsMenu(menu);
}
/**
* Method called when an menu's item is selected.
*
* #param item
* the item selected
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "================= onOptionsItemSelected ================= fragSt: " + fragmentStatus);
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
return false;
}
/**
* Method to get device button actions
*
* #param keyCode
* the code of the button pressed
* #param event
* the event
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(TAG, "================= onKeyDown ================= fragSt: " + fragmentStatus);
Log.w(TAG, "KeyEven: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_MENU ) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
if (!drawerOpen)
mDrawerLayout.openDrawer(Gravity.LEFT);
else
mDrawerLayout.closeDrawer(Gravity.LEFT);
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.d(TAG, "TouchKeyBack");
}
return super.onKeyDown(keyCode, event);
}
/**
* Method called when the back button is pressed
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (mShowOptionMenu == true)
mShowOptionMenu = false;
Log.d(TAG, "onBackPressed");
int tt = fm.getBackStackEntryCount();
// Log.d(TAG, "BackStackEntry name : " +
// fm.getBackStackEntryAt(tt).getName());
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
getSupportFragmentManager().popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
/**
* Method to know if the device is tablet or smartphone
*
* #return a boolean indicating if the device is a tablet
*/
public boolean isTablet() {
Log.d(TAG, "================= isTablet =================");
boolean xlarge = ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
boolean large = ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
return (xlarge || large);
}
/**
* Method called when the activity is deallocated
*/
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "================= onDestroy =================");
if (dbHelper != null) {
OpenHelperManager.releaseHelper();
dbHelper = null;
}
}
/**
* Return the database helper
*/
public DatabaseHelper getHelper() {
if (dbHelper == null) {
dbHelper = (DatabaseHelper) OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return dbHelper;
}
/**
* Method called when the activity start. Used for Google Analytics
*/
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "================= onStart =================");
EasyTracker.getInstance(this).activityStart(this);
}
/**
* Method called when the activity stop. Used for Google Analytics
*/
#Override
public void onStop() {
Log.d(TAG, "================= onStop =================");
super.onStop();
EasyTracker.getInstance(this).activityStop(this);
}
}
QrCodeScannerFragment.java:
public class QrCodeScannerFragment extends BarcodeFragment {
public static final String TAG = QrCodeScannerFragment.class.getSimpleName();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setScanResultHandler(new IScanResultHandler() {
#Override
public void scanResult(ScanResult result) {
Log.w(TAG, "ScanResult");
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
return super.onCreateView(inflater, container, savedInstanceState);
}
}
BarcodeFragment.java:
public class BarcodeFragment extends SherlockFragment implements SurfaceHolder.Callback {
private static final String TAG = BarcodeFragment.class.getSimpleName();
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private CameraManager cameraManager;
private CaptureFragmentHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private boolean hasSurface;
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType, ?> decodeHints;
private String characterSet;
private InactivityTimer inactivityTimer;
private AmbientLightManager ambientLightManager;
private IScanResultHandler resultHandler;
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
public CameraManager getCameraManager() {
return cameraManager;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
hasSurface = false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FrameLayout frameLayout = new FrameLayout(getActivity());
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
frameLayout.setLayoutParams(layoutParams);
surfaceView = new SurfaceView(getActivity());
surfaceView.setLayoutParams(layoutParams);
viewfinderView = new ViewfinderView(getActivity());
viewfinderView.setLayoutParams(layoutParams);
frameLayout.addView(surfaceView);
frameLayout.addView(viewfinderView);
View v = frameLayout;
inactivityTimer = new InactivityTimer(this.getActivity());
ambientLightManager = new AmbientLightManager(this.getActivity());
return v;
}
SurfaceView surfaceView;
#SuppressWarnings("deprecation")
#Override
public void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is
// necessary because we don't
// want to open the camera driver and measure the screen size if we're
// going to show the help on
// first launch. That led to bugs where the scanning rectangle was the
// wrong size and partially
// off screen.
cameraManager = new CameraManager(this.getActivity(), getView());
viewfinderView.setCameraManager(cameraManager);
handler = null;
resetStatusView();
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still
// exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the
// camera.
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
decodeFormats = null;
characterSet = null;
}
#Override
public void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = this.surfaceView;
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
#Override
public void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
public void restart() {
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, IDS.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show
* the results.
*
* #param rawResult
* The contents of the barcode.
* #param scaleFactor
* amount by which thumbnail was scaled
* #param barcode
* A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
inactivityTimer.onActivity();
ScanResult resultHandler = ResultHandlerFactory.parseResult(rawResult);
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
drawResultPoints(barcode, scaleFactor, rawResult);
}
handleDecodeInternally(rawResult, resultHandler, barcode);
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of
* the barcode.
*
* #param barcode
* A bitmap of the captured image.
* #param scaleFactor
* amount by which thumbnail was scaled
* #param rawResult
* The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c099cc00"));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4
&& (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and
// metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
if (a != null && b != null) {
canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(), scaleFactor * b.getX(), scaleFactor * b.getY(), paint);
}
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, ScanResult resultHandler, Bitmap barcode) {
viewfinderView.setVisibility(View.GONE);
if (this.resultHandler != null) {
this.resultHandler.scanResult(resultHandler);
}
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a
// RuntimeException.
if (handler == null) {
handler = new CaptureFragmentHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle(getString(R.string.app_name));
builder.setMessage("Sorry, the Android camera encountered a problem. You may need to restart the device.");
builder.setPositiveButton("OK", new FinishListener(this.getActivity()));
builder.setOnCancelListener(new FinishListener(this.getActivity()));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(IDS.id.restart_preview, delayMS);
}
resetStatusView();
}
private void resetStatusView() {
viewfinderView.setVisibility(View.VISIBLE);
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
public IScanResultHandler getScanResultHandler() {
return resultHandler;
}
public void setScanResultHandler(IScanResultHandler resultHandler) {
this.resultHandler = resultHandler;
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have problem is "java.lang.NullPointerException"
I want to know how I can solve it , I want to show dialoge
Look at the picture
I have two of the classes MainActivity and MaterialDialog
See the error message :
> FATAL EXCEPTION: main
> Process: com.example.android.dialoge, PID: 14884
> java.lang.NullPointerException
> at
> com.example.android.dialoge.MaterialDialog$Builder.setTitle(MaterialDialog.java:265)
> at
> com.example.android.dialoge.MaterialDialog$Builder.<init>(MaterialDialog.java:198)
> at
> com.example.android.dialoge.MaterialDialog$Builder.<init>(MaterialDialog.java:179)
> at
> com.example.android.dialoge.MaterialDialog.show(MaterialDialog.java:59)
> at com.example.android.dialoge.MainActivity.test(MainActivity.java:58)
> at
> com.example.android.dialoge.MainActivity$1.onClick(MainActivity.java:28)
> at android.view.View.performClick(View.java:4438)
> at android.view.View$PerformClick.run(View.java:18422)
> at android.os.Handler.handleCallback(Handler.java:733)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> 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)
// see the first class MainActivity
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
Button clickButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
test();
}
/*
MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this).build();
RecyclerView list = dialog.getRecyclerView();
// Do something with it
dialog.show();
*/
});
}
void test(){
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
for (int j = 0; j < 38; j++) {
arrayAdapter.add("This is item " + j);
}
ListView listView = new ListView(this);
listView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (8 * scale + 0.5f);
listView.setPadding(0, dpAsPixels, 0, dpAsPixels);
listView.setDividerHeight(0);
listView.setAdapter(arrayAdapter);
final com.example.android.dialoge.MaterialDialog alert = new com.example.android.dialoge.MaterialDialog(this)
.setTitle("ghjghj").setContentView(listView);
alert.setPositiveButton("OK", new View.OnClickListener() {
#Override public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
}
// See the Second Class MaterialDialog :
public class MaterialDialog {
private final static int BUTTON_BOTTOM = 9;
private final static int BUTTON_TOP = 9;
private boolean mCancel;
private Context mContext;
private AlertDialog mAlertDialog;
private MaterialDialog.Builder mBuilder;
private View mView;
private int mTitleResId;
private CharSequence mTitle;
private int mMessageResId;
private CharSequence mMessage;
private Button mPositiveButton;
private LinearLayout.LayoutParams mLayoutParams;
private Button mNegativeButton;
private boolean mHasShow = false;
private int mBackgroundResId = -1;
private Drawable mBackgroundDrawable;
private View mMessageContentView;
private int mMessageContentViewResId;
private DialogInterface.OnDismissListener mOnDismissListener;
private int pId = -1, nId = -1;
private String pText, nText;
View.OnClickListener pListener, nListener;
public MaterialDialog(Context context) {
this.mContext = context;
}
public void show() {
if (!mHasShow) {
mBuilder = new Builder();
} else {
mAlertDialog.show();
}
mHasShow = true;
}
public MaterialDialog setView(View view) {
mView = view;
if (mBuilder != null) {
mBuilder.setView(view);
}
return this;
}
public MaterialDialog setContentView(View view) {
mMessageContentView = view;
mMessageContentViewResId = 0;
if (mBuilder != null) {
mBuilder.setContentView(mMessageContentView);
}
return this;
}
/**
* Set a custom view resource to be the contents of the dialog.
*
* #param layoutResId resource ID to be inflated
*/
public MaterialDialog setContentView(int layoutResId) {
mMessageContentViewResId = layoutResId;
mMessageContentView = null;
if (mBuilder != null) {
mBuilder.setContentView(layoutResId);
}
return this;
}
public void dismiss() {
mAlertDialog.dismiss();
}
private int dip2px(float dpValue) {
final float scale = mContext.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
private static boolean isLollipop() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
public MaterialDialog setTitle(int resId) {
mTitleResId = resId;
if (mBuilder != null) {
mBuilder.setTitle(resId);
}
return this;
}
public MaterialDialog setTitle(CharSequence title) {
mTitle = title;
if (mBuilder != null) {
mBuilder.setTitle(title);
}
return this;
}
public MaterialDialog setMessage(int resId) {
mMessageResId = resId;
if (mBuilder != null) {
mBuilder.setMessage(resId);
}
return this;
}
public MaterialDialog setMessage(CharSequence message) {
mMessage = message;
if (mBuilder != null) {
mBuilder.setMessage(message);
}
return this;
}
public MaterialDialog setPositiveButton(int resId, final View.OnClickListener listener) {
this.pId = resId;
this.pListener = listener;
return this;
}
public Button getPositiveButton() {
return mPositiveButton;
}
public Button getNegativeButton() {
return mNegativeButton;
}
public MaterialDialog setPositiveButton(String text, final View.OnClickListener listener) {
this.pText = text;
this.pListener = listener;
return this;
}
public MaterialDialog setNegativeButton(int resId, final View.OnClickListener listener) {
this.nId = resId;
this.nListener = listener;
return this;
}
public MaterialDialog setNegativeButton(String text, final View.OnClickListener listener) {
this.nText = text;
this.nListener = listener;
return this;
}
/**
* Sets whether this dialog is canceled when touched outside the window's
* bounds OR pressed the back key. If setting to true, the dialog is
* set to be cancelable if not
* already set.
*
* #param cancel Whether the dialog should be canceled when touched outside
* the window OR pressed the back key.
*/
public MaterialDialog setCanceledOnTouchOutside(boolean cancel) {
this.mCancel = cancel;
if (mBuilder != null) {
mBuilder.setCanceledOnTouchOutside(mCancel);
}
return this;
}
public MaterialDialog setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
this.mOnDismissListener = onDismissListener;
return this;
}
private class Builder{
private TextView mTitleView;
private ViewGroup mMessageContentRoot;
private TextView mMessageView;
private Window mAlertDialogWindow;
private Builder(){
mAlertDialog = new AlertDialog.Builder(mContext).create();
mAlertDialog.show();
mAlertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mAlertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE);
mAlertDialogWindow = mAlertDialog.getWindow();
mAlertDialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (mTitleResId != 0) {
setTitle(mTitleResId);
}
if (mTitle != null) {
setTitle(mTitle);
}
if (mTitle == null && mTitleResId == 0){
mTitleView.setVisibility(View.GONE);
}
if (mMessageResId != 0){
setMessage(mMessageResId);
}
if(mMessage != null){
setMessage(mMessage);
}
if(pId != -1){
mPositiveButton.setVisibility(View.VISIBLE);
mPositiveButton.setText(pId);
mPositiveButton.setOnClickListener(pListener);
if (isLollipop()) {
mPositiveButton.setElevation(0);
}
}
if (nId != -1) {
mNegativeButton.setVisibility(View.VISIBLE);
mNegativeButton.setText(nId);
mNegativeButton.setOnClickListener(nListener);
if (isLollipop()) {
mNegativeButton.setElevation(0);
}
}
if (!isNullOrEmpty(pText)) {
mPositiveButton.setVisibility(View.VISIBLE);
mPositiveButton.setText(pText);
mPositiveButton.setOnClickListener(pListener);
if (isLollipop()) {
mPositiveButton.setElevation(0);
}
}
if (!isNullOrEmpty(nText)) {
mNegativeButton.setVisibility(View.VISIBLE);
mNegativeButton.setText(nText);
mNegativeButton.setOnClickListener(nListener);
if (isLollipop()) {
mNegativeButton.setElevation(0);
}
}
if (isNullOrEmpty(pText) && pId == -1) {
mPositiveButton.setVisibility(View.GONE);
}
if (isNullOrEmpty(nText) && nId == -1) {
mNegativeButton.setVisibility(View.GONE);
}
if (mMessageContentView != null) {
this.setContentView(mMessageContentView);
} else if (mMessageContentViewResId != 0) {
this.setContentView(mMessageContentViewResId);
}
mAlertDialog.setCanceledOnTouchOutside(mCancel);
mAlertDialog.setCancelable(mCancel);
if (mOnDismissListener != null) {
mAlertDialog.setOnDismissListener(mOnDismissListener);
}
}
public void setTitle(int resId) {
mTitleView.setText(resId);
}
public void setTitle(CharSequence title) {
mTitleView.setText(title);
}
public void setMessage(int resId) {
if (mMessageView != null) {
mMessageView.setText(resId);
}
}
public void setMessage(CharSequence message) {
if (mMessageView != null) {
mMessageView.setText(message);
}
}
/**
* set negative button
*
* #param text the name of button
*/
public void setNegativeButton(String text, final View.OnClickListener listener) {
Button button = new Button(mContext);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(text);
button.setTextColor(Color.argb(222, 0, 0, 0));
button.setTextSize(14);
button.setGravity(Gravity.CENTER);
button.setPadding(0, 0, 0, dip2px(8));
button.setOnClickListener(listener);
}
public void setView(View view) {
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(layoutParams);
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override public void onFocusChange(View v, boolean hasFocus) {
mAlertDialogWindow.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// show imm
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
if (viewGroup.getChildAt(i) instanceof EditText) {
EditText editText = (EditText) viewGroup.getChildAt(i);
editText.setFocusable(true);
editText.requestFocus();
editText.setFocusableInTouchMode(true);
}
}
for (int i = 0; i < viewGroup.getChildCount(); i++) {
if (viewGroup.getChildAt(i) instanceof AutoCompleteTextView) {
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) viewGroup
.getChildAt(i);
autoCompleteTextView.setFocusable(true);
autoCompleteTextView.requestFocus();
autoCompleteTextView.setFocusableInTouchMode(true);
}
}
}
}
public void setContentView(View contentView) {
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
contentView.setLayoutParams(layoutParams);
if (contentView instanceof ListView) {
setListViewHeightBasedOnChildren((ListView) contentView);
}
}
/**
* Set a custom view resource to be the contents of the dialog. The
* resource will be inflated into a ScrollView.
*
* #param layoutResId resource ID to be inflated
*/
public void setContentView(int layoutResId) {
mMessageContentRoot.removeAllViews();
// Not setting this to the other content view because user has defined their own
// layout params, and we don't want to overwrite those.
LayoutInflater.from(mMessageContentRoot.getContext())
.inflate(layoutResId, mMessageContentRoot);
}
public void setCanceledOnTouchOutside(boolean canceledOnTouchOutside) {
mAlertDialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
mAlertDialog.setCancelable(canceledOnTouchOutside);
}
}
private boolean isNullOrEmpty(String nText) {
return nText == null || nText.isEmpty();
}
private void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
// My lib gardle :
compile 'com.github.afollestad.material-dialogs:core:0.8.5.6#aar'
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
Try this.....
I am a newbie in Android developing and i try to understand how to use callbacks in interfaces.
I am use "Color-pick-preference" library in my app. I need it to change different settings, for example background color. And i want to change in runtime, without refresh activities.
This is how i do it now:
Color-picker-preference have three main classes:
ColorPickerView (as I understand it show color panel and send user choise via callback to ColorPickerDialog)
ColorPickerDialog (this class show preferebce dialog window includes color panel, submit color button etc. And send user choise data further in ColorPickerPreference)
and ColorPicerPreference wich save user choise in Shared Preferences.
I described very superficially, if you'll excuse me.
Parts of these three files
ColorPickerView
***
***
private OnColorChangedListener mListener;
***
public interface OnColorChangedListener {
public void onColorChanged(int color);
}
***
#Override
public boolean onTouchEvent(MotionEvent event) {
boolean update = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartTouchPoint = new Point((int) event.getX(), (int) event.getY());
update = moveTrackersIfNeeded(event);
break;
case MotionEvent.ACTION_MOVE:
update = moveTrackersIfNeeded(event);
break;
case MotionEvent.ACTION_UP:
mStartTouchPoint = null;
update = moveTrackersIfNeeded(event);
break;
}
if (update) {
if (mListener != null) {
mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
}
invalidate();
return true;
}
return super.onTouchEvent(event);
}
***
public void setOnColorChangedListener(OnColorChangedListener listener) {
mListener = listener;
}
***
public void setColor(int color, boolean callback) {
int alpha = Color.alpha(color);
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
mAlpha = alpha;
mHue = hsv[0];
mSat = hsv[1];
mVal = hsv[2];
if (callback && mListener != null) {
mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
}
invalidate();
}
ColorPickerDialog
***
public class ColorPickerDialog
extends
Dialog
implements
ColorPickerView.OnColorChangedListener,
View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener ...
***
private OnColorChangedListener mListener;
***
public interface OnColorChangedListener {
public void onColorChanged(int color);
}
***
private void setUp(int color) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayout = inflater.inflate(R.layout.dialog_color_picker, null);
mLayout.getViewTreeObserver().addOnGlobalLayoutListener(this);
mOrientation = getContext().getResources().getConfiguration().orientation;
setContentView(mLayout);
setTitle(R.string.dialog_color_picker);
mColorPicker = (ColorPickerView) mLayout.findViewById(R.id.color_picker_view);
mOldColor = (ColorPickerPanelView) mLayout.findViewById(R.id.old_color_panel);
mNewColor = (ColorPickerPanelView) mLayout.findViewById(R.id.new_color_panel);
mHexVal = (EditText) mLayout.findViewById(R.id.hex_val);
mHexVal.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
mHexDefaultTextColor = mHexVal.getTextColors();
mHexVal.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
String s = mHexVal.getText().toString();
if (s.length() > 5 || s.length() < 10) {
try {
int c = ColorPickerPreference.convertToColorInt(s.toString());
mColorPicker.setColor(c, true);
mHexVal.setTextColor(mHexDefaultTextColor);
} catch (IllegalArgumentException e) {
mHexVal.setTextColor(Color.RED);
}
} else {
mHexVal.setTextColor(Color.RED);
}
return true;
}
return false;
}
});
((LinearLayout) mOldColor.getParent()).setPadding(
Math.round(mColorPicker.getDrawingOffset()),
0,
Math.round(mColorPicker.getDrawingOffset()),
0
);
mOldColor.setOnClickListener(this);
mNewColor.setOnClickListener(this);
mColorPicker.setOnColorChangedListener(this);
mOldColor.setColor(color);
mColorPicker.setColor(color, true);
}
***
#Override
public void onColorChanged(int color) {
mNewColor.setColor(color);
if (mHexValueEnabled)
updateHexValue(color);
}
***
public void setOnColorChangedListener(OnColorChangedListener listener) {
mListener = listener;
}
ColorPickerPreference
public class ColorPickerPreference
extends
Preference
implements
Preference.OnPreferenceClickListener,
ColorPickerDialog.OnColorChangedListener ...
***
#Override
public void onColorChanged(int color) {
if (isPersistent()) {
persistInt(color);
}
mValue = color;
setPreviewColor();
try {
getOnPreferenceChangeListener().onPreferenceChange(this, color);
} catch (NullPointerException e) {
}
notifyChanged();
}
***
protected void showDialog(Bundle state) {
mDialog = new ColorPickerDialog(getContext(), mValue);
mDialog.setOnColorChangedListener(this);
if (mAlphaSliderEnabled) {
mDialog.setAlphaSliderVisible(true);
}
if (mHexValueEnabled) {
mDialog.setHexValueEnabled(true);
}
if (state != null) {
mDialog.onRestoreInstanceState(state);
}
mDialog.show();
}
And what i try to do in my MainActivity
public class MainActivity extends AppCompatActivity implements
ColorPickerDialog.OnColorChangedListener {
public ColorPickerDialog cpd;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//return super.onOptionsItemSelected(item);
Integer id = item.getItemId();
switch (id) {
case R.id.menu_action_settings:
Intent i = new Intent(this, SettingActivity.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cpd = new ColorPickerDialog(this,Color.BLACK);
cpd.setOnColorChangedListener(this);
setContentView(R.layout.activity_main);
}
public void onColorChanged(int color) {
RelativeLayout main_scroll_view = (RelativeLayout)findViewById(R.id.activity_main_rel_layout);
System.out.println("AIM ALIVE!");
main_scroll_view.setBackgroundColor(color);
}
}
But when i change color in ColorPickerPreference widget -nothing happens. the background color does not change and my System.out.println does not work ?
Sorry for chaotic presentation and thank you for your answers.
I too myself more of a challenge) Solved the problem by simply adding the onResume method in Mainactivity and check the Shared Preference and then setting the background color in the resulting value.
Where do you declare the action so you could show/open the dialog?
SettingActivity
***
public static class SettingsFragment extends PreferenceFragment {
PrefernceAnimation pa;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String settings = getArguments().getString("settings");
if ("colors".equals(settings)) {
addPreferencesFromResource(R.xml.preference_fragment_colors);
} else if ("sounds".equals(settings)) {
addPreferencesFromResource(R.xml.preference_fragment_sounds);
}
else if ("animation".equals(settings)) {
addPreferencesFromResource(R.xml.preference_fragment_animation);
}
}
}
and preference_headers.xml
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="com.dosomeweb.mika.babypic.SettingActivity$SettingsFragment"
android:title="#string/pref_main_title_colors"
android:summary="#string/pref_main_summery_colors">
<extra
android:name="settings"
android:value="colors"/>
</header>
<header
android:fragment="com.dosomeweb.mika.babypic.SettingActivity$SettingsFragment"
android:title="#string/pref_main_title_sounds"
android:summary="#string/pref_main_summery_sounds">
<extra
android:name="settings"
android:value="sounds"/>
</header>
<header
android:fragment="com.dosomeweb.mika.babypic.SettingActivity$SettingsFragment"
android:title="#string/pref_main_title_animation"
android:summary="#string/pref_main_summery_animation">
<extra
android:name="settings"
android:value="animation"/>
</header>
just in case prference_fragment_colors.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<net.margaritov.preference.colorpicker.ColorPickerPreference
android:key="pref_bg_color"
android:title="#string/pref_title_layout_bg_color"
android:summary="#string/pref_summary_layout_bg_color"
android:defaultValue="#color/colorAccent"/>
</PreferenceScreen>
Why are you creating so many different interface? Why not use 1 interface and link it all together since the callback have the same parameter.
I have a little UI problem with my ViewPager.
My ViewPager is the center of my UI.
I have a NavigationView with 4 items and a Toolbar with 2 items.
Each time an item of the NavigationView is clicked, I replace the adapter. Therefore I have 4 adapters and only one is causing problems : BrowseAdapter (code is below).
This adapter is filled with a list of Events and provide a Fragment for each Event.
Something good to know is that whatever the size of the eventList is, the setAdapter method of the ViewPager takes at least 150ms to execute, whereas for the other Adapters, it takes only 20 to 50ms to load.
I have tried to put all calls to setAdapter in the View.post(new Runnable()); method and in an AsyncTask<Void, Void, Void> :
The post method froze the UI
The AsyncTask changed nothing because I can only call setAdapter on the UI Thread (in the postExecute method) which is basically the same as calling it without the AsyncTask.
I think this is basically an optimization problem but I can't see where is the problem.
Thank you for you help.
Here is the code in question :
MainActivity :
/*
.
. Import stuff
.
.
.*/
public class MainActivity extends AppCompatActivity implements RequestCallback,
ConnectionCallbacks, OnConnectionFailedListener, FBLoginChanged, LocationListener {
/**
* The main content view
*/
private CustomViewPager mViewPager;
/**
* Adapters : One for each feature of the application
*/
private BrowseAdapter mBrowseAdapter;
private CurrentAdapter mCurrentAdapter = new CurrentAdapter(getFragmentManager());
private CalendarAdapter mCalendarAdapter = new CalendarAdapter(getFragmentManager());
private SettingsAdapter mSettingsAdapter = new SettingsAdapter(getFragmentManager());
/**
* The action bar of the application
*/
private Toolbar mToolbar;
/**
* TabLayout provide the new Material Design tab navigation
*/
private TabLayout mTabLayout;
/**
* Side navigation given by a NavigationView instead of a NavigationDrawer
* to support Material Design
*/
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
/**
* List of all events.
*/
private ArrayList<Event> mEventList = new ArrayList<Event>();
/**
* Provide different way of browsing through the events
*/
private enum BrowseType {
DEFAULT,
POPULAR,
RANDOM
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*.
.
. Initialization stuff
.
.*/
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Closing drawer on item click
mDrawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
case R.id.home:
mTabLayout.setVisibility(View.VISIBLE);
mBrowseAdapter.setBrowsingType(BrowseType.DEFAULT);
mViewPager.setAdapter(mBrowseAdapter);
break;
case R.id.favs:
mTabLayout.setVisibility(View.GONE);
mViewPager.setAdapter(mCurrentAdapter);
break;
case R.id.calendar:
mTabLayout.setVisibility(View.GONE);
mViewPager.setAdapter(mCalendarAdapter);
break;
case R.id.setting:
mTabLayout.setVisibility(View.GONE);
mViewPager.setAdapter(mSettingsAdapter);
break;
default:
break;
}
return true;
}
});
mViewPager = (CustomViewPager) findViewById(R.id.pager);
mBrowseAdapter = new BrowseAdapter(this.getFragmentManager(), mEventList);
mTabLayout.setOnTabSelectedListener(new OnTabSelectedListener() {
#Override
// Unused
public void onTabReselected(Tab tab) {
}
#Override
public void onTabSelected(Tab tab) {
switch(tab.getPosition()) {
case 0:
mBrowseAdapter.setBrowsingType(BrowseType.DEFAULT);
break;
case 1:
mBrowseAdapter.setBrowsingType(BrowseType.POPULAR);
break;
default: // Unused
break;
}
mViewPager.setAdapter(mBrowseAdapter);
}
#Override
// Unused
public void onTabUnselected(Tab tab) {
}
});
mViewPager.setAdapter(mBrowseAdapter);
}
}
My adapter :
private class BrowseAdapter extends FragmentStatePagerAdapter {
private ArrayList<Event> eventList = new ArrayList<Event>();
private BrowseType browseType = BrowseType.DEFAULT;
private HashMap<Integer, EventFragment> fragmentReferenceMap = new HashMap<Integer, EventFragment>();
public BrowseAdapter(FragmentManager fragmentManager,
ArrayList<Event> mEventList) {
super(fragmentManager);
}
public void setBrowsingType(BrowseType type) {
this.browseType = type;
this.commitChanges();
}
public Event getEventById(int id) {
for(Event event : eventList) {
if(event.getId() == id)
return event;
}
return null;
}
public void setJSONData(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject obj = jsonArray.getJSONObject(i);
Event event = new Event();
event.setId(obj.getInt("id"));
event.setName(obj.getString("name"));
event.setShort_description(obj.getString("short_desc"));
event.setLong_description(obj.getString("long_desc"));
event.setPlace(obj.getString("place").split(";")[0]);
Location loc = new Location("");
loc.setLatitude(Double.valueOf(obj.getString("place")
.split(";")[1]));
loc.setLongitude(Double.valueOf(obj.getString("place")
.split(";")[2]));
event.setLocation(loc);
event.setDate(obj.getString("date"));
eventList.add(event);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getJSONData() {
JSONArray toReturn = new JSONArray();
for (Event event : eventList) {
JSONObject tmp = new JSONObject();
try {
tmp.put("name", event.getName());
tmp.put("short_desc", event.getShort_description());
tmp.put("long_desc", event.getLong_description());
tmp.put("id", event.getId());
tmp.put("date", event.getDate());
tmp.put("place",
event.getPlace()
+ ";"
+ String.valueOf(event.getLocation()
.getLatitude())
+ ";"
+ String.valueOf(event.getLocation()
.getLongitude()));
toReturn.put(tmp);
} catch (JSONException e) {
e.printStackTrace();
}
}
return toReturn.toString();
}
public boolean addItem(Event item) {
return eventList.add(item);
}
#SuppressWarnings("unused")
public Event removeAt(int position) {
return eventList.remove(position);
}
public void commitChanges() {
this.sort();
this.notifyDataSetChanged();
}
private void sort() {
Log.d("SORT", browseType.name());
Collections.sort(eventList, new Comparator<Event>() {
#Override
public int compare(Event arg0, Event arg1) {
float dis1 = arg0.getLocation().distanceTo(
LocationProvidor.getInstance().getLastLocation());
float dis2 = arg1.getLocation().distanceTo(
LocationProvidor.getInstance().getLastLocation());
int userNumber1 = Integer.parseInt(arg0.getUserNumber());
int userNumber2 = Integer.parseInt(arg1.getUserNumber());
switch(browseType) {
case DEFAULT:
return (int) (dis1 - dis2);
case POPULAR:
return userNumber2 - userNumber1;
case RANDOM:
return new Random().nextInt();
default:
return 0;
}
}
});
}
public void empty() {
eventList.clear();
}
#Override
public EventFragment getItem(int position) {
EventFragment frag = EventFragment.newInstance(eventList.get(position));
frag.setIsCurrents(mCurrentAdapter.containsEventId(eventList.get(position).getId()));
fragmentReferenceMap.put(position, frag);
return frag;
}
#Override
public void destroyItem(View container, int position, Object object) {
super.destroyItem(container, position, object);
fragmentReferenceMap.remove(position);
Log.d("fr.blopper.app", "destroy " + position);
}
public EventFragment getFragment(int position) {
return fragmentReferenceMap.get(position);
}
#Override
public int getCount() {
return eventList.size();
}
}
And CustomViewPager (I have created it only to measure the time taken by setAdapter):
import android.content.Context;
import android.util.AttributeSet;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.support.v4.view.PagerAdapter;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context c) {
super(c);
}
public CustomViewPager(Context c, AttributeSet as) {
super(c, as);
}
#Override
public void setAdapter(PagerAdapter adapter) {
long start = System.currentTimeMillis();
super.setAdapter(adapter);
Log.d("TAG", "Custom time " + (System.currentTimeMillis() - start));
}
}
Found the answer, it has nothing to do with the ViewPager.
The Fragments provided by the Adapter were making a call to a Google API which was slow to answer.
This code is based on UltimateAndroidCamera
CameraFragment.class
public class CameraFragment extends BaseFragment {
// Native camera.
private Camera mCamera;
// View to display the camera output.
private CameraPreview mPreview;
// Reference to the containing view.
private View mCameraView;
/**
* Default empty constructor.
*/
public CameraFragment(){
super();
}
/**
* Static factory method
* #param sectionNumber
* #return
*/
/**
* OnCreateView fragment override
* #param inflater
* #param container
* #param savedInstanceState
* #return
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_camera, container, false);
// Create our Preview view and set it as the content of our activity.
boolean opened = safeCameraOpenInView(view);
if(!opened){
Log.d("CameraGuide","Error, Camera failed to open");
return view;
}
// Trap the capture button.
Button captureButton = (Button) view.findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
return view;
}
/**
* Recommended "safe" way to open the camera.
* #param view
* #return
*/
private boolean safeCameraOpenInView(View view) {
boolean qOpened;
releaseCameraAndPreview();
mCamera = getCameraInstance();
mCameraView = view;
qOpened = (mCamera != null);
if(qOpened){
mPreview = new CameraPreview(getActivity().getBaseContext(), mCamera,view);
FrameLayout preview = (FrameLayout) view.findViewById(R.id.camera_preview);
preview.addView(mPreview);
mPreview.startCameraPreview();
}
return qOpened;
}
/**
* Safe method for getting a camera instance.
* #return
*/
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
releaseCameraAndPreview();
}
/**
* Clear any existing preview / camera.
*/
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if(mPreview != null){
mPreview.destroyDrawingCache();
mPreview.mCamera = null;
}
}
/**
* Surface on which the camera projects it's capture results. This is derived both from Google's docs and the
* excellent StackOverflow answer provided below.
*
* Reference / Credit: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails
*/
class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
// SurfaceHolder
private SurfaceHolder mHolder;
// Our Camera.
private Camera mCamera;
// Parent Context.
private Context mContext;
// Camera Sizing (For rotation, orientation changes)
private Camera.Size mPreviewSize;
// List of supported preview sizes
private List<Camera.Size> mSupportedPreviewSizes;
// Flash modes supported by this camera
private List<String> mSupportedFlashModes;
// View holding this camera.
private View mCameraView;
public CameraPreview(Context context, Camera camera, View cameraView) {
super(context);
// Capture the context
mCameraView = cameraView;
mContext = context;
setCamera(camera);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setKeepScreenOn(true);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/**
* Begin the preview of the camera input.
*/
public void startCameraPreview()
{
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
}
catch(Exception e){
e.printStackTrace();
}
}
/**
* Extract supported preview and flash modes from the camera.
* #param camera
*/
private void setCamera(Camera camera)
{
// Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails
mCamera = camera;
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
mSupportedFlashModes = mCamera.getParameters().getSupportedFlashModes();
// Set the camera to Auto Flash mode.
if (mSupportedFlashModes != null && mSupportedFlashModes.contains(Camera.Parameters.FLASH_MODE_AUTO)){
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
mCamera.setParameters(parameters);
}
requestLayout();
}
/**
* The Surface has been created, now tell the camera where to draw the preview.
* #param holder
*/
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Dispose of the camera preview.
* #param holder
*/
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null){
mCamera.stopPreview();
}
}
/**
* React to surface changed events
* #param holder
* #param format
* #param w
* #param h
*/
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
Camera.Parameters parameters = mCamera.getParameters();
// Set the auto-focus mode to "continuous"
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
// Preview size must exist.
if(mPreviewSize != null) {
Camera.Size previewSize = mPreviewSize;
parameters.setPreviewSize(previewSize.width, previewSize.height);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Calculate the measurements of the layout
* #param widthMeasureSpec
* #param heightMeasureSpec
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null){
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
/**
* Update the layout based on rotation and orientation changes.
* #param changed
* #param left
* #param top
* #param right
* #param bottom
*/
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
// Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails
if (changed) {
final int width = right - left;
final int height = bottom - top;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null){
Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
switch (display.getRotation())
{
case Surface.ROTATION_0:
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
mCamera.setDisplayOrientation(90);
break;
case Surface.ROTATION_90:
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
break;
case Surface.ROTATION_180:
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
break;
case Surface.ROTATION_270:
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
mCamera.setDisplayOrientation(180);
break;
}
}
final int scaledChildHeight = previewHeight * width / previewWidth;
mCameraView.layout(0, height - scaledChildHeight, width, height);
}
}
/**
*
* #param sizes
* #param width
* #param height
* #return
*/
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int width, int height)
{
// Source: http://stackoverflow.com/questions/7942378/android-camera-will-not-work-startpreview-fails
Camera.Size optimalSize = null;
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) height / width;
// Try to find a size match which suits the whole screen minus the menu on the left.
for (Camera.Size size : sizes){
if (size.height != width) continue;
double ratio = (double) size.width / size.height;
if (ratio <= targetRatio + ASPECT_TOLERANCE && ratio >= targetRatio - ASPECT_TOLERANCE){
optimalSize = size;
}
}
// If we cannot find the one that matches the aspect ratio, ignore the requirement.
if (optimalSize == null) {
// TODO : Backup in case we don't get a size.
}
return optimalSize;
}
}
/**
* Picture Callback for handling a picture capture and saving it out to a file.
*/
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null){
Toast.makeText(getActivity(), "Image retrieval failed.", Toast.LENGTH_SHORT)
.show();
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
// Restart the camera preview.
safeCameraOpenInView(mCameraView);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
/**
* Used to return the camera File output.
* #return
*/
private File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "UltimateCameraGuideApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("Camera Guide", "Required media storage does not exist");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
DialogHelper.showDialog( "Success!","Your picture has been saved!",getActivity());
return mediaFile;
}
}
CameraFragment.class extends BaseFragment.class below is the BaseFragment code:
public static final String ARG_SECTION_NUMBER = "ARG_SECTION_NUMBER";
/**
* Default empty constructor
*/
public BaseFragment(){
//
}
/**
* This interface must be implemented by activities that contain this
* mFragment to allow an interaction in this mFragment to be communicated
* to the mActivity and potentially other fragments contained in that
* mActivity.
* <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 {
public void onFragmentInteraction(Uri uri);
public void onFragmentInteraction(String id);
public void onFragmentInteraction(int actionId);
}
}
CameraActivity.class
// Storage for camera image URI components
private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath";
private final static String CAPTURED_PHOTO_URI_KEY = "mCapturedImageURI";
// Required for camera operations in order to save the image file on resume.
private String mCurrentPhotoPath = null;
private Uri mCapturedImageURI = null;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (mCurrentPhotoPath != null) {
savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath);
}
if (mCapturedImageURI != null) {
savedInstanceState.putString(CAPTURED_PHOTO_URI_KEY, mCapturedImageURI.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) {
mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY);
}
if (savedInstanceState.containsKey(CAPTURED_PHOTO_URI_KEY)) {
mCapturedImageURI = Uri.parse(savedInstanceState.getString(CAPTURED_PHOTO_URI_KEY));
}
super.onRestoreInstanceState(savedInstanceState);
}
/**
* Getters and setters.
*/
public String getCurrentPhotoPath() {
return mCurrentPhotoPath;
}
public void setCurrentPhotoPath(String mCurrentPhotoPath) {
this.mCurrentPhotoPath = mCurrentPhotoPath;
}
public Uri getCapturedImageURI() {
return mCapturedImageURI;
}
public void setCapturedImageURI(Uri mCapturedImageURI) {
this.mCapturedImageURI = mCapturedImageURI;
}
}
SectionsPagerAdapater.class
public class SectionsPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public SectionsPagerAdapter(Context context,FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a InboxFragment (defined as a static inner class below).
switch (position){
case 0:
return new InboxFragment();
case 1:
return new CameraFragment();
case 2:
return new FeedsFragment();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return mContext.getString(R.string.title_section1).toUpperCase();
case 1:
return mContext.getString(R.string.title_section2).toUpperCase();
case 2:
return mContext.getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
MainActvity.class calling the SectionsPagerAdapter.class
public class MainActivity extends FragmentActivity {
// private SmsPrefManager pref;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
SmsPrefManager pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(this,
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
AndroidManifest.xml Permissions:
<!-- Accessing Camera Hardware -->
<uses-permission android:name="android.hardware.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>
<uses-feature android:name="android.hardware.camera.flash"/>
<uses-feature android:name="android.hardware.location"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Layout XML fragment_camera
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<RelativeLayout
android:id="#+id/innerRelativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<Button
android:id="#+id/button_capture"
android:text="#string/btn_cam"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_margin="10dp"
android:layout_gravity="bottom"
/>
</RelativeLayout>
</RelativeLayout>
The Logcat does not return any Runtime error regarding the app running on my device which is API23 and on my Emulator API19. Kindly help me resolve this issue have been reffering to a lot of Stackoverflow Queries but found no solution. Thank you in advance!
My application pulls data from a web service that generates different sections for each user. Then I am going to use these sections to create tabs using FragmentPagerAdapter.
I have used an Async task to pull data from the web service. However the overridden methods such as getCount() and getPageTitle() in the FragmentPagerAdapter executed prior to my asynctask and completes its job. How can I prevent this and generate dynamic number of tabs and their title name based on the data fetched from the web service?
In other words how can I create dynamic number of tabs and titles based on the data fetch from the web service
My Code for FragmentPagerAdapter as below. As you can see I have hard coded the amount of tabs as well as their title names.
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new SectionFragment();
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Camera".toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return "SECTION 4";
}
return null;
}
//setting the section title
private void setSectionTitle(){
}
//count the number of sections
private int countNumberofSections(){
int numberOfSection = 0;
return numberOfSection;
}
}
Then I have my Fragment code as below which has the the caller to the Async Task
public static class SectionFragment extends Fragment implements OnTaskCompleted {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private Slider adapter;
private ViewPager viewPager;
public static final String ARG_SECTION_NUMBER = "section_number";
Button thumbUpBut;
Button thumbDownBut;
Button captureButton;
ImageView genImage;
TextView genCaption;
private Camera mCamera;
private CameraPreview mPreview;
private static File mediaFile;
private ProgressDialog progress;
private static String imageSaveLocation;
private static String file_name_without_extension;
private ImageView imageView;
private Button uploadButton;
private Button cancelButton;
private Collection<Place> places = null;
private Collection<Happenings> events = null;
private Collection<General> general = null;
private ArrayList<String> sections;
public int getNumberOfPages(){
return sections.size();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
FeedRequest task = new FeedRequest(this);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
captureButton = (Button) rootView.findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
thumbUpBut = (Button) rootView.findViewById(R.id.thumbUp);
thumbUpBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressUp");
thumb("up");
}
});
thumbDownBut = (Button) rootView.findViewById(R.id.thumbDown);
thumbDownBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressDown");
thumb("down");
}
});
//allocating the activity one to the camera
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
mCamera = getCameraInstance();
mPreview = new CameraPreview(this.getActivity(), mCamera);
FrameLayout preview = (FrameLayout)rootView.findViewById(R.id.camera_preview);
preview.addView(mPreview);
//hide buttons
thumbDownBut.setVisibility(rootView.INVISIBLE);
thumbUpBut.setVisibility(rootView.INVISIBLE);
}else{
thumbDownBut.setVisibility(rootView.VISIBLE);
thumbUpBut.setVisibility(rootView.VISIBLE);
captureButton.setVisibility(rootView.INVISIBLE);
}
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
return rootView;
}
//take photo function
private void takePhoto() {
//get coordinates of the location
UserLocation userLocation = new UserLocation();
userLocation.getUserLocation(getActivity());
coordinates[0] = userLocation.longitude;
coordinates[1] = userLocation.latitude;
PictureCallback pictureCB = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera cam) {
new SavePhotoAndMetadata().execute(data);
cam.startPreview();
}
};
mCamera.takePicture(null, null, pictureCB);
}
//get camera instance
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
//get the media out
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
file_name_without_extension = "IMG_" + timeStamp;
imageSaveLocation = mediaFile.toString();
return mediaFile;
}
//saving the image and metadata together
class SavePhotoAndMetadata extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... data) {
File picFile = getOutputMediaFile();
if (picFile == null) {
return null;
}
byte[] photoData = data[0];
try {
//save the image
FileOutputStream fos = new FileOutputStream(picFile);
fos.write(photoData);
fos.close();
} catch (FileNotFoundException e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Saving Picture..Please wait...");
progress.show();
}
#Override
protected void onPostExecute(String s) {
progress.dismiss();
imagePreviewDialog();
}
}
//save image metadata in async task
class SaveMetadataTask extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... params) {
serializeDeserialize.serializeData("This is for testing", file_name_without_extension, Double.toString(coordinates[0]), Double.toString(coordinates[1]), deviceId, deviceEmail);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void v) {
}
}
//image preview dialog and its functionality
private void imagePreviewDialog(){
//setting the bitmap
Bitmap bmp = BitmapFactory.decodeFile(mediaFile.toString());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Image Preview");
builder.setCancelable(false);
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup vg = (ViewGroup)inflater.inflate(R.layout.sanp_preview_layout, null);
ImageView image = (ImageView) vg.findViewById(R.id.imageView);
image.setImageBitmap(rotateBitmap(bmp));
builder.setView(vg);
//buttons
builder.setPositiveButton("Upload",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(checkInternetConnection.haveNetworkConnection(sContext)){
//upload the image
uploadImage();
//save image metadata
new SaveMetadataTask().execute();
}else{
Toast.makeText(sContext, "Error! No internet connection detected. Image will be uploaded on an active internet connection", Toast.LENGTH_LONG).show();
new SaveMetadataTask().execute();
}
}
});
builder.setNegativeButton("Discard",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
discardImage(mediaFile.toString());
dialog.dismiss();
}
});
builder.show();
}
private Bitmap rotateBitmap(Bitmap image){
int width=image.getHeight();
int height=image.getWidth();
Bitmap srcBitmap=Bitmap.createBitmap(width, height, image.getConfig());
for (int y=width-1;y>=0;y--)
for(int x=0;x<height;x++)
srcBitmap.setPixel(width-y-1, x,image.getPixel(x, y));
return srcBitmap;
}
//device email
private String getDeviceEmail(){
AccountManager accountManager = AccountManager.get(sContext);
Account[] account = accountManager.getAccountsByType("com.google");
//device email
for(Account accLoop : account){
deviceEmail = accLoop.name;
}
return deviceEmail;
}
//upload image to the server
private void uploadImage(){
//save metadata
//call upload service
Intent intent = new Intent(sContext, HttpUploader.class);
Bundle loc = new Bundle();
loc.putDoubleArray("ss", coordinates);
intent.putExtra("url", PHOTO_UPLOAD);
intent.putExtra("paths", mediaFile.toString());
intent.putExtra("deviceid", deviceId);
intent.putExtra("deviceemail", getDeviceEmail());
intent.putExtra("posttext", "This is for testing");
intent.putExtra("filename", file_name_without_extension);
intent.putExtra("geo", loc);
sContext.startService(intent);
Toast.makeText(getActivity(), "Your image is being uploaded", Toast.LENGTH_LONG).show();
}
//discard image when the discard button is pressed
private void discardImage(String imagePath){
File file = new File(imagePath);
try{
file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
#Override
public void onTaskCompleted(boolean status, String message) {
// TODO Auto-generated method stub
Log.e("onTaskCompleted", "success" + status);
if (message == "tumb UP success") {
thumbUpBut.setSelected(true);
thumbDownBut.setSelected(false);
Log.e("tumb", "tumb");
} else if (message == "tumb DOWN success") {
thumbDownBut.setSelected(true);
thumbUpBut.setSelected(false);
Log.e("tumb", "tumb");
}
}
//listener for fetching main objects
#Override
public void onFeedCompleted(ArrayList<Posts> postArray, Multimap<String, Object> multiMap) {
// TODO Auto-generated method stub
numberOfPages = postArray.size();
adapter = new Slider(getActivity(), postArray, getContext());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(postArray.size());
//saving the keyset
Set<String> keys = multiMap.keySet();
sections = new ArrayList<String>();
//sorting the categories and creating the category list
for(String key:keys){
//getting category list
if(!sections.contains(keys)){
sections.add(key);
}
//sorting categories
if(key.equals("Place")){
places.add((Place) multiMap.get(key));
}else if(key.equals("Events")){
events.add((Happenings) multiMap.get(key));
}else if(key.equals("General")){
general.add((General) multiMap.get(key));
}
}
}
//adding the pages to the adaptor dynamically
public void addPagesDynamically(){
}
}
//create the parent directory
private void createParentDiectory(){
File dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap");
if(!(dir.exists() && dir.isDirectory())) {
dir.mkdirs();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_post:
openPost();
return true;
case R.id.action_settings:
// openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openPost() {
/*
Intent i = new Intent(getApplicationContext(), PhotoActivity.class);
startActivity(i);
*/
}
public static void thumb(String type) {
SectionFragment d = new SectionFragment();
PostThumb task = new PostThumb(type, d);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
//broadcast receiver for picture upload
public class MyWebRequestReceiver extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "asia.ceynet.intent.action.PROCESS_RESPONSE";
#Override
public void onReceive(Context context, Intent intent) {
//String responseString = intent.getStringExtra(HttpUploader.RESPONSE_STRING);
String reponseMessage = intent.getStringExtra(HttpUploader.RESPONSE_MESSAGE);
String responseStatus = intent.getStringExtra(HttpUploader.RESPONSE_STATUS);
String file_to_be_deleted = intent.getStringExtra(HttpUploader.FILE_NAME_WITHOUT_EXTENSION);
Toast.makeText(getApplicationContext(), reponseMessage + " - " + file_to_be_deleted + ".jpg", Toast.LENGTH_LONG).show();
//if uploaded successfully delete or image and metadata
if(responseStatus.equals("true")){
File temp_image_dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".jpg");
File metadata_file = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".ser");
try{
temp_image_dir.delete();
metadata_file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
}
}
When you finnish pulling the async data, provide the adapter with the new data and call .notifyDataSetChanged() on that adapter instance and the framework will update the pages and count by itself.
If you wish a more detailed explanation post your FragmentPagerAdapter implementation.
First of all, let me apologize if I'm not making myself clear enough because this is one of my first participation(s) here. But I'll be always here to answer queries related to this answer and clear any confusions arose by my statements.
Since you're using fragments, so I'm assuming you must have included your fragments inside an activity (lets say MainActivity.java).
What you need, can be done inside that activity containing fragment.
Here is the example code of onCreate method inside the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
//Instance of viewpager included inside activity_main.xml
viewPager = (ViewPager) findViewById(R.id.vpMain);
SectionsPagerAdapter adapter = new SectionsPagerAdapter (fragmentManager);
//Adding some fragments right from the beginning, you could ignore it if not needed.
addFragments();
//This `OnPageChangeListener` will do the trick for you.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//Show the title of fragment
Toast.makeText(MainActivity.this, adapter.screens.get(position), Toast.LENGTH_SHORT).show();
//If fragment being loaded is later than the first one,
// then add one more fragment after the last fragment to the adapter.
// integer currentPosition is declared as a field, outside onCreate method and initially set to 0.
if(position>currentPosition){
currentPosition+=1;
adapter.addFragment(new SectionFragment(), "Fragment"+String.valueOf(position+3));
adapter.notifyDataSetChanged();
}else{
currentPosition--;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
} // onCreate ends here.
Create this method inside your MainActivity (just to add 3 fragments to give your application a head-start.
private void addFragments(){
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
}
Then modify your SectionsPagerAdapter's getItem and getCount methods as below:
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return screens.get(position);
}
#Override
public int getCount() {
return screens.size();
}
//This method will dynamically add a fragment each time it is called.
public void addFragment(Fragment fragment) {
screens.add(fragment);
}
Now, no work related to "adding new fragment to the list" needs to be done inside your SectionFragment class.