Customizing InfowindowAdapter to add images from Content provider - android

I have an application of places shown on a map with markers, I have customized infowindow to show the contents of the places created, title, description and picture, these data are accessed via a content provider, my problem everything is going great until I delete a record from the database, the app goes crazy, or broken or just odd recognizes records id etc etc
The problem is clearly in the infowindow code customization, because to remove it all works correctly, create, delete, create markers etc. .. but even though I've tried have not given with the error.
The infernal code:
class MyInfoWindowAdapter implements InfoWindowAdapter {
View v;
MyInfoWindowAdapter() {
v = getLayoutInflater().inflate(R.layout.custom_info, null);
}
#SuppressWarnings("deprecation")
#Override
public View getInfoWindow(final Marker marker) {
MapaLugaresActivity.this.marker = marker;
c.requery();
TextView tvTitulo = (TextView) v.findViewById(R.id.tituloi);
tvTitulo.setText(marker.getTitle());
// TextView tvDescr = (TextView) v.findViewById(R.id.descripcioni);
// tvDescr.setText(marker.getSnippet());
ImageView imgi = (ImageView) v.findViewById(R.id.imgi);
if (marker.getSnippet() != null && marker != null
&& c.getCount() > 0) {
try {
if (c.moveToFirst()) {
c.moveToPosition(Integer.valueOf(marker.getSnippet()) - 1);
String img = c.getString(c.getColumnIndex("foto"));
if (img != null) {
resizedBitmap = DecodeImagen
.decodeSampledBitmapFromFile(img, 100, 100);
imgi.setAdjustViewBounds(true);
imgi.setImageBitmap(resizedBitmap);
} else {
imgi.setAdjustViewBounds(true);
imgi.setImageResource(R.drawable.paisaje);
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
// imgi.setImageResource(R.drawable.rdlv);
Typeface fuente = Typeface.createFromAsset(getAssets(),
"TravelingTypewriter.ttf");
tvTitulo.setTypeface(fuente);
// tvDescr.setTypeface(fuente);
return v;
}
#Override
public View getInfoContents(Marker marker) {
if (MapaLugaresActivity.this.marker != null
&& MapaLugaresActivity.this.marker.isInfoWindowShown()) {
MapaLugaresActivity.this.marker.hideInfoWindow();
MapaLugaresActivity.this.marker.showInfoWindow();
}
return null;
}
}
Add markers:
#SuppressWarnings("deprecation")
public void addMarker() {
map.clear();
c.requery();
if (c.getCount() > 0) {
c.moveToFirst();
do {
latlong = new LatLng(c.getFloat(c.getColumnIndex("latitud")),
c.getFloat(c.getColumnIndex("longitud")));
final MarkerOptions marker = new MarkerOptions().title(c
.getString(c.getColumnIndex("titulo")));
marker.snippet(c.getString(c.getColumnIndex("_id")));
marker.position(latlong);
map.addMarker(marker).showInfoWindow();
} while (c.moveToNext());
} else {
Toast.makeText(MapaLugaresActivity.this, "Añada un nuevo lugar",
Toast.LENGTH_SHORT).show();
}
}
I appreciate your help in advance, took several days trying to find the solution and I think it was time to ask for help, thanks. I have limited programming experience , hope your understanding
PS: I have uploaded the project on GitHub in case anyone wants to analyze it: D
The code in the activity MapaLugaresActivity
https://github.com/Shochlves/rdlv
Image infowindow:
https://lh5.ggpht.com/eBgrw0riQxfGph4FhxXvMRDxzYjlvdWw6L6qRqg_L1oV9yPGHPW9wV2Cal7zVGj1-HY=h900-rw

Solved! The solution has been implemented Hastable (http://developer.android.com/reference/java/util/Hashtable.html), I hit the code as it is helpful.
InfoWindowAdapter with image and title from SQLite (content provider)
InfoWindowAdapter:
public class MyInfoWindowAdapter implements InfoWindowAdapter {
private View v;
MyInfoWindowAdapter() {
v = getLayoutInflater().inflate(R.layout.custom_info, null);
}
#Override
public View getInfoContents(Marker marker) {
if (MapaLugaresActivity.this.marker != null
&& MapaLugaresActivity.this.marker.isInfoWindowShown()) {
MapaLugaresActivity.this.marker.hideInfoWindow();
MapaLugaresActivity.this.marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(Marker marker) {
MapaLugaresActivity.this.marker = marker;
String img = null;
if (marker.getId() != null && markers != null && markers.size() > 0) {
if ( markers.get(marker.getId()) != null &&
markers.get(marker.getId()) != null) {
img = markers.get(marker.getId());
}
}
final ImageView imgi = (ImageView) v.findViewById(R.id.imgi);
if (img != null && !img.equalsIgnoreCase("null")
&& !img.equalsIgnoreCase("")) {
Bitmap resizedBitmap = DecodeImagen
.decodeSampledBitmapFromFile(img, 100, 100);
imgi.setImageBitmap(resizedBitmap);
} else {
imgi.setAdjustViewBounds(true);
imgi.setImageResource(R.drawable.paisaje);
}
TextView tvTitulo = (TextView) v.findViewById(R.id.tituloi);
tvTitulo.setText(marker.getTitle());
//TextView tvDescr = (TextView) v.findViewById(R.id.descripcioni);
//tvDescr.setText(marker.getSnippet());
Typeface fuente = Typeface.createFromAsset(getAssets(),
"TravelingTypewriter.ttf");
tvTitulo.setTypeface(fuente);
// tvDescr.setTypeface(fuente);
return v;
}
}
addMarker:
public void addMarker() {
markers = new Hashtable<String, String>();
c.requery();
if (c.getCount() > 0) {
c.moveToFirst();
do {
latlong = new LatLng(c.getFloat(c.getColumnIndex("latitud")),
c.getFloat(c.getColumnIndex("longitud")));
final Marker marker = map.addMarker(new MarkerOptions().title(c
.getString(c.getColumnIndex("titulo"))).snippet(c.getString(c.getColumnIndex("_id"))).position(latlong));
markers.put(marker.getId(), c.getString(c.getColumnIndex("foto")));
} while (c.moveToNext());
} else {
Toast.makeText(MapaLugaresActivity.this, "Añada un nuevo lugar",
Toast.LENGTH_SHORT).show();
}
}
onCreate:
if (map != null) {
map.setInfoWindowAdapter(new MyInfoWindowAdapter());
addMarker();
}
a greeting

Related

Efficient loading of images and videos first frame in recyclerview

Working on media browser type of application where I read files from USB with custom drivers. File expose by NanoHTTPServer. Not important point here but just for information.
The following code logic works pretty well but it looks broken and start struggling with fast scrolling.
Is there any way to load videos frame faster and avoid hanging and delay in frames. Is there any flaws in this code? As I am using rxjava.
#Override
public void onBindViewHolder(BasicHolder holder,final int position) {
...
if(multiMedia.isImage()){
Glide.with(context)
.load(multiMedia.getUrl())
.crossFade()
.into(holder.imageThumbnail);
}else{
Bitmap bitmap = mThumbnailsCache.get(multiMedia.getUrl()+THUMBNAIL_AT_PERCENT);
if(bitmap == null || multiMedia.getLength() == 0){
//check for already running task
if(holder.imageThumbnail.getTag(R.string.tag_for_video) == null){
loadVideoThumbnail(holder,multiMedia,position);
}
}else {
holder.imageThumbnail.setImageBitmap(bitmap);
}
}
....
//this method will trigger rxjava task on io and set back results emitted by
private void loadVideoThumbnail(final BasicHolder holder, final MultiMedia multiMedia,final int position){
final SoftReference<BasicHolder> mHolderRef = new SoftReference<>(holder);
final Subscription sub = extractFrameAndDuration(multiMedia.getUrl(), THUMBNAIL_AT_PERCENT)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(emittedObject -> {
if (emittedObject == null || mHolderRef.get() == null) return;
if (mHolderRef.get().getLayoutPosition() != position) {
notifyItemChanged(position);
return;
}
if (emittedObject instanceof Bitmap) {
ImageView imageThumbnail = mHolderRef.get().imageThumbnail;
if (imageThumbnail.getTag(R.string.tag_for_video) != null) {
imageThumbnail.setTag(R.string.tag_for_video, null);
imageThumbnail.setImageBitmap((Bitmap) emittedObject);
}
} else {
multiMedia.setLength((long)emittedObject);
TextView textInfo = mHolderRef.get().textInfo;
if (textInfo.getTag() == Filetype.MOVIE) {
mHolderRef.get().viewHighlight.setData(multiMedia.getSavedClips(),multiMedia.getLength());
textInfo.setText(VideoUtils.getTotalClipDuration((long) emittedObject, App.context));
}
}
}, Throwable::printStackTrace);
if(reqSubQueue.size() > 8){
//cancel previous requests
reqSubQueue.pop().unsubscribe();
}
reqSubQueue.add(sub);
holder.imageThumbnail.setTag(R.string.tag_for_video,sub);
}
...
//this method will get thumbnail from video url
private Observable<Object> extractFrameAndDuration(String url, final long atPercent){
return Observable.create(subscriber -> {
final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
subscriber.add(new Subscription() {
#Override
public void unsubscribe() {
//this will actually cancel loading
Observable.fromCallable(() -> {
mediaMetadataRetriever.release();
return true;
}).subscribeOn(Schedulers.io())
.subscribe();
}
#Override
public boolean isUnsubscribed() {
return false;
}
});
try{
mediaMetadataRetriever.setDataSource(url, new HashMap<>());
String durationString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
final long duration = Long.parseLong(TextUtils.isEmpty(durationString)? "0": durationString);
//cache duration
clipsDurations.put(url,duration);
subscriber.onNext(duration);
long timeUs = (long) (duration / 100.0 * atPercent);
if(timeUs > duration) timeUs = duration;
Bitmap bitmap = mThumbnailsCache.get(url+THUMBNAIL_AT_PERCENT);
if(bitmap == null){
//1 milli sec = 1000 microseconds
bitmap = MediaUtils.getFrameFromVideoAt(mediaMetadataRetriever, timeUs * 1000);
if(bitmap != null){
bitmap = MediaUtils.resize(bitmap,thumbSize,thumbSize);
mThumbnailsCache.put(url+THUMBNAIL_AT_PERCENT,bitmap);
subscriber.onNext(bitmap);
}
}else {
subscriber.onNext(bitmap);
}
}
catch (Exception e){
e.printStackTrace();
}
finally{
if (mediaMetadataRetriever != null){
mediaMetadataRetriever.release();
}
}
//remove item from queue
subscriber.onCompleted();
reqSubQueue.remove(subscriber);
});
}
All requests get canceled in Activity.onStop. reqSubQueue is ArrayDeque
Edit method description is added
I am sure some pro-developers will find out flaws.

Ideas to refactor code with many Lists

I need a little help to get an idea of how to refactor my code, but I can't see options besides what's done, I would like to add the objects but not using so many lists (and if's conditions).
Here is my code, if anyone could help, I appreciate. Thanks
#ViewById
BannerHomeViewPager place1, place2, place3, place4, place5, place6, place7,
place8, place9;
The lists:
private List<HomeItem> allHomeItems = new ArrayList<HomeItem>(),
placeItems1 = new ArrayList<HomeItem>(),
placeItems2 = new ArrayList<HomeItem>(),
placeItems3 = new ArrayList<HomeItem>(),
placeItems4 = new ArrayList<HomeItem>(),
placeItems5 = new ArrayList<HomeItem>(),
placeItems6 = new ArrayList<HomeItem>(),
placeItems7 = new ArrayList<HomeItem>(),
placeItems8 = new ArrayList<HomeItem>(),
placeItems9 = new ArrayList<HomeItem>();
1) Items mocked, ok.
2)
#UiThread
void updateUI() {
if (allHomeItems != null && allHomeItems.size() > 0) {
for (HomeItem item : allHomeItems) {
if (item.getPlacement().contains("1")) {
placeItems1.add(item);
} else if (item.getPlacement().contains("2")) {
placeItems2.add(item);
} else if (item.getPlacement().contains("3")) {
placeItems3.add(item);
} else if (item.getPlacement().contains("4")) {
placeItems4.add(item);
} else if (item.getPlacement().contains("5")) {
placeItems5.add(item);
} else if (item.getPlacement().contains("6")) {
placeItems6.add(item);
} else if (item.getPlacement().contains("7")) {
placeItems7.add(item);
} else if (item.getPlacement().contains("8")) {
placeItems8.add(item);
} else {
placeItems9.add(item);
}
}
}
setupAdapters();
}
3) setupAdapters()
private void setupAdapters() {
if (place1 != null)
place1.update(placeItems1);
if (place2 != null)
place2.update(placeItems2);
if (place3 != null)
place3.update(placeItems3);
if (place4 != null)
place4.update(placeItems4);
if (place5 != null)
place5.update(placeItems5);
if (place6 != null)
place6.update(placeItems6);
if (place7 != null)
place7.update(placeItems7);
if (place8 != null)
place8.update(placeItems8);
if (place9 != null)
place9.update(placeItems9);
}
As #DanielBo answer:
private Map<String, ArrayList<HomeItem>> placeItems = new HashMap<String,ArrayList<HomeItem>>();
void updateUI() {
if (allHomeItems != null && allHomeItems.size() > 0) {
for (HomeItem item : allHomeItems) {
if(!placeItems.containsKey(item.getPlacement())){
placeItems.put(item.getPlacement(), new ArrayList<HomeItem>());
}
placeItems.get(item.getPlacement()).add(item);
}
}
setupAdapters();
}
But why are you using so many views? I really can't say if this is correct bcs i don't know the purpose of this, but I can't figure a good use to so many list views in the same layout...

GoogleMap markers weird behaviour

This is a strange one and I hope that someone can at least give me a direction to look in.
My Android application uses GoogleMap API v2. In the app, I run an activity off OnClickInfoWindowListener on one of the markers. In detail, when I click on the particular marker, an InfoWindow of that marker appears. Next when I click on the InfoWindow, it launches another activity.
The problem is that when I return to GoogleMap from that activity, the particular marker which launched the activity, is not responsive. By responsive, I mean when I click on it, I do not get an InfoWindow. There is no such problem with the other markers. To fix the problem, I either move or zoom on the map or click on another marker to show its InfoWindow, then the original marker works normally. I cannot see any red stuff on the LogCat.
I also run the map off a ListView and there is no problem (that I can see).
Any suggestions on what to look at are very welcome!
Edit 1 :
This part is the InfoWindowClickListener setup ...
// Set up info Window Click Listener
googleMap
.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker mkr) {
// Default open file
// menu option : edit file information
// menu option : delete
Log.d(TAG, "InfoWindow Click detected.");
final GeoFileData gfd = getFromHashMap(mkr);
if (editGeoFile) {
editGeoFile = false;
editFileInfo(gfd);
} else if (deleteGeoFile) {
deleteGeoFile = false;
deleteFile(gfd, mkr);
} else {
openFile(gfd);
}
}
});
The openFile routine which launches the Activity
// Public and Routines used by the main loop
private void openFile (GeoFileData gfd) {
int typeIndex = gfd.getTypeIndex();
switch(typeIndex) {
case 0 :
case 1 :
case 2 :
case 3 :
// Spen file by default
Intent notePadIntent = new Intent(getBaseContext(), NotePad.class);
Bundle b = new Bundle();
b.putParcelable(MAIN_NOTEPAD_GFD, gfd);
notePadIntent.putExtras(b);
startActivityForResult(notePadIntent, SPEN_NOTEPAD_CODE);
break;
default :
Log.w(TAG, "Unknown file.");
Toast.makeText(this, getString(R.string.toast_unknown_file), Toast.LENGTH_LONG).show();
break;
}
}
The starting part of the launched activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spen_notepad);
Bundle extras = getIntent().getExtras();
if (extras != null) {
inputGfd = extras.getParcelable(PreznsActivity.MAIN_NOTEPAD_GFD);
}
extras.clear();
mContext = this;
// Spen
boolean isSpenFeatureEnabled = false;
Spen spenPackage = new Spen();
try {
spenPackage.initialize(this);
isSpenFeatureEnabled = spenPackage.isFeatureEnabled(Spen.DEVICE_PEN);
} catch (SsdkUnsupportedException e) {
if( SDKUtils.processUnsupportedException(this, e) == true) {
return;
}
} catch (Exception e1) {
Toast.makeText(mContext, "Cannot initialize Spen.",
Toast.LENGTH_SHORT).show();
e1.printStackTrace();
finish();
}
FrameLayout spenViewContainer =
(FrameLayout) findViewById(R.id.spenViewContainer);
RelativeLayout spenViewLayout =
(RelativeLayout) findViewById(R.id.spenViewLayout);
// PenSettingView
mPenSettingView =
new SpenSettingPenLayout(mContext, new String(),
spenViewLayout);
if (mPenSettingView == null) {
Toast.makeText(mContext, "Cannot create new PenSettingView.",
Toast.LENGTH_SHORT).show();
finish();
}
// EraserSettingView
mEraserSettingView =
new SpenSettingEraserLayout(mContext, new String(),
spenViewLayout);
if (mEraserSettingView == null) {
Toast.makeText(mContext, "Cannot create new EraserSettingView.",
Toast.LENGTH_SHORT).show();
finish();
}
// TextSettingView
mTextSettingView = new SpenSettingTextLayout(mContext, new String(), new HashMap<String, String>(), spenViewLayout);
if (mTextSettingView == null) {
Toast.makeText(mContext, "Cannot craeate new TextSettingView.", Toast.LENGTH_SHORT).show();
finish();
}
spenViewContainer.addView(mPenSettingView);
spenViewContainer.addView(mEraserSettingView);
spenViewContainer.addView(mTextSettingView);
// SpenSurfaceView
mSpenSurfaceView = new SpenSurfaceView(mContext);
if (mSpenSurfaceView == null) {
Toast.makeText(mContext, "Cannot create new SpenSurfaceView.",
Toast.LENGTH_SHORT).show();
finish();
}
spenViewLayout.addView(mSpenSurfaceView);
mPenSettingView.setCanvasView(mSpenSurfaceView);
mEraserSettingView.setCanvasView(mSpenSurfaceView);
mTextSettingView.setCanvasView(mSpenSurfaceView);
//
Display display = getWindowManager().getDefaultDisplay();
mScreenRect = new Rect();
display.getRectSize(mScreenRect);
// SpenNoteDoc
try {
mSpenNoteDoc =
new SpenNoteDoc(mContext, mScreenRect.width(), mScreenRect.height());
} catch (IOException e) {
Toast.makeText(mContext, "Cannot create new NoteDoc",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
finish();
} catch (Exception e) {
e.printStackTrace();
finish();
}
// NoteDoc
mSpenPageDoc = mSpenNoteDoc.appendPage();
mSpenPageDoc.setBackgroundColor(0xFFD6E6F5);
mSpenPageDoc.clearHistory();
// PageDoc
mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);
initSettingInfo();
// Listener
mSpenSurfaceView.setTouchListener(mPenTouchListener);
mSpenSurfaceView.setColorPickerListener(mColorPickerListener);
mSpenSurfaceView.setTextChangeListener(mTextChangeListener);
mSpenSurfaceView.setReplayListener(mReplayListener);
mSpenPageDoc.setHistoryListener(mHistoryListener);
mEraserSettingView.setEraserListener(mEraserListener);
mSpenSurfaceView.setFlickListener(mFlickListener);
// Button
mTextObjBtn = (ImageView) findViewById(R.id.textObjBtn);
mTextObjBtn.setOnClickListener(mTextObjBtnClickListener);
mPenBtn = (ImageView) findViewById(R.id.penBtn);
mPenBtn.setOnClickListener(mPenBtnClickListener);
mEraserBtn = (ImageView) findViewById(R.id.eraserBtn);
mEraserBtn.setOnClickListener(mEraserBtnClickListener);
mUndoBtn = (ImageView) findViewById(R.id.undoBtn);
mUndoBtn.setOnClickListener(undoNredoBtnClickListener);
mUndoBtn.setEnabled(mSpenPageDoc.isUndoable());
mRedoBtn = (ImageView) findViewById(R.id.redoBtn);
mRedoBtn.setOnClickListener(undoNredoBtnClickListener);
mRedoBtn.setEnabled(mSpenPageDoc.isRedoable());
mImgObjBtn = (ImageView) findViewById(R.id.imgObjBtn);
mImgObjBtn.setOnClickListener(mImgObjBtnClickListener);
mAddPageBtn = (ImageView) findViewById(R.id.addPageBtn);
mAddPageBtn.setOnClickListener(mAddPageBtnClickListener);
mTxtView = (TextView) findViewById(R.id.spen_page);
mTxtView.setText("Page" + mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId()));
selectButton(mPenBtn);
String filePath = inputGfd.getFileDirectory();
mFilePath = new File(filePath);
if (!mFilePath.exists()) {
if (!mFilePath.mkdirs()) {
Toast.makeText(mContext, "Save Path Creation Error", Toast.LENGTH_SHORT).show();
return;
}
}
mSpenPageDoc.startRecord();
File loadFile = new File(inputGfd.getFileDirectory(), inputGfd.getFileName());
if (loadFile.exists()) {
loadNoteFile();
} else {
Log.w(TAG, "File does not exist!");
}
if(isSpenFeatureEnabled == false) {
mToolType = SpenSurfaceView.TOOL_FINGER;
mSpenSurfaceView.setToolTypeAction(mToolType,
SpenSurfaceView.ACTION_STROKE);
Toast.makeText(mContext,
"Device does not support Spen. \n You can draw stroke by finger",
Toast.LENGTH_SHORT).show();
}
}
One of the returns for the activity
private boolean saveNoteFile(final boolean isClose) {
// file save
// note file
String saveFilePath = inputGfd.getFileDirectory() + File.separator;
String fileName = inputGfd.getFileName();
if (!fileName.equals("")) {
saveFilePath += fileName;
saveNoteFile(saveFilePath);
if (isClose)
finish();
} else {
Toast
.makeText(mContext, "Invalid filename !!!", Toast.LENGTH_LONG)
.show();
}
return true;
}
and finally the destroy routine,
#Override
protected void onDestroy() {
Log.d(TAG, "NotePad onDestroy()");
super.onDestroy();
if (mSpenNoteDoc != null && mSpenPageDoc.isRecording()) {
mSpenPageDoc.stopRecord();
}
if (mPenSettingView != null) {
mPenSettingView.close();
}
if (mEraserSettingView != null) {
mEraserSettingView.close();
}
if (mTextSettingView != null) {
mTextSettingView.close();
}
if(mSpenSurfaceView != null) {
if (mSpenSurfaceView.getReplayState() == SpenSurfaceView.REPLAY_STATE_PLAYING) {
mSpenSurfaceView.stopReplay();
}
mSpenSurfaceView.closeControl();
mSpenSurfaceView.close();
mSpenSurfaceView = null;
}
if(mSpenNoteDoc != null) {
try {
if (isDiscard)
mSpenNoteDoc.discard();
else
mSpenNoteDoc.close();
} catch (Exception e) {
e.printStackTrace();
}
mSpenNoteDoc = null;
}
};
Thanks!
This is likely a bug in Google Maps Android API v2 itself.
I encounter it in my app. When you open "Declusterification" demo, click on yellow marker with 10 in the center and a new marker (red default) appears in the same spot, this new marker cannot be interacted with to show info window without moving the map.
If you happen to figure out SSCCE for it, I suggest posting it on gmaps-api-issues. I'll support it. If I do find simple example to show this issue, I'll also post an update here.
To close up this question.
GoogleMap markers exhibit the anomalies mentioned in this thread and currently the issue has been fed back to Google. There are two apparent "workarounds" to the problem but how effective they are is not clear:
1st workaround : work within the limitations of .clear(). An activated marker cannot be deactivated with .clear().
2nd workaround : after returning from the activity, perform a camera update. This apparently resets the activation of the marker.

Horizontal and Vertical ViewPager

Do anyone have successfully implemented ViewPager which scrolls Horizontally and Vertically?
I know Directional ViewPager,When i use it it gives
<i>31 12:11:29.954: E/AndroidRuntime(14670): java.lang.NoClassDefFoundError: com.directionalviewpager.DirectionalViewPager$DataSetObserver
10-31 12:11:29.954: E/AndroidRuntime(14670): at com.directionalviewpager.DirectionalViewPager.setAdapter(DirectionalViewPager.java:164)</i>
line no 164:mObserver = new DataSetObserver();
public void setAdapter(PagerAdapter adapter) {
if (mAdapter != null) {
VerticalViewPagerCompat.setDataSetObserver(mAdapter, null);
}
mAdapter = adapter;
if (mAdapter != null) {
if (mObserver == null) {
mObserver = new DataSetObserver();
}
VerticalViewPagerCompat.setDataSetObserver(mAdapter, mObserver);
mPopulatePending = false;
if (mRestoredCurItem >= 0) {
mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);
setCurrentItemInternal(mRestoredCurItem, false, true);
mRestoredCurItem = -1;
mRestoredAdapterState = null;
mRestoredClassLoader = null;
} else {
populate();
}
}
}
Thanks,
I found your answer You just add the DirectionalViewPager as a library into your project
This libray is located at Android-DirectionalViewPager-master\Android-DirectionalViewPager-master\library\bin
and ya dont forget to include it from order and export tab

AsyncTask does not stop if a long running loop is working in it?

friends,
i am using following code inside asyncTask
public class AsycLoaderFromDbAndMapInjector extends AsyncTask
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... arg0) {
Log.d("Asynctask", ""+arg0);
boolean show = false;
if(db == null)
db = new dbHelper(me);
ATM results = null;
try {
results = db.getAtmsBySelectedBanks(atm.getSelectedBankList(), selectedCity);
if (results != null) {
LoopThroughEachATMToDisplayOnMap();
}
return show;
}
#Override
protected void onPostExecute(Boolean result) {
stopProgress();
}
private void LoopThroughEachATMToDisplayOnMap()
{
Drawable drawable = getResources().getDrawable(
R.drawable.marker);
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
for (int i = 0; i < atm.getAtmList().size(); i++) {
ATM a = atm.getAtmList().get(i);
if (a != null) {
int[] coordinates = getIntCoordinates(a
.getCoordinates());
if (coordinates != null) {
GeoPoint point = new GeoPoint(coordinates[0],
coordinates[1]);
OverlayItem overlayItem = new OverlayItem(
point, a.getBankName(), a.getAddress()
+ "##" + a.getPhone() + "##"
+ a.getWebAddress() + "##"
+ a.getCoordinates());
itemizedOverlay.addOverlay(overlayItem);
System.out
.println("coordinates-------------------------"
+ i + " "
+ coordinates[0]
+ ","
+ coordinates[1]);
}
}
}
}
}
now when i press back button this runable populate keeps running in the backend i have used
AsyncTask.cancel() on backbuttonpressed event but still it keeps running any one guide me how to solve this issue?
Try this,
private ATM results = null;
#Override
protected Boolean doInBackground(Void... arg0) {
Log.d("Asynctask", ""+arg0);
boolean show = false;
if(db == null)
db = new dbHelper(me);
ATM results = null;
try {
results = db.getAtmsBySelectedBanks(atm.getSelectedBankList(), selectedCity);
if (results != null) {
publishProgress(0);
}
return show;
}
#Override
protected void onProgressUpdate(Integer... values) {
if (results != null) {
LoopThroughEachATMToDisplayOnMap();
}
}
set a flag in LoopThroughEachATMToDisplayOnMap(), to stop the for loop when the back button is pressed.
That is,
Detect when the back button is pressed, set the condition variable.
Inside the loop through method there is a condition variable which will break the for loop.
You'll need to explicitly provide your populate runnable a way to detect that you don't want it to complete. Often people use Thread.interrupt() for this, but since your code doesn't fully control the UI thread that might not be a great idea here.

Categories

Resources