Accessing ArrayList<Mat> across Activities, OpenCV, Android - java

I am trying to use an ArrayList() across two different Activities. It is declared:
public static ArrayList<Mat> Video = new ArrayList<Mat>();
I read in frames from the camera and when I have 50 I go to my next activity.
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
Mat frame = inputFrame.rgba();
if(Video.size() < 50)
{
Log.i(TAG, "Added frame");
Video.add(frame);
}
else
{
String e = Integer.toString(Video.get(1).cols());
Log.v(TAG1, e);
e = Integer.toString(Video.get(1).rows());
Log.v(TAG1, e);
Intent intent = new Intent(this, Analysis.class);
startActivity(intent);
}
return inputFrame.rgba();
}
The log output for this method is:
11-15 22:53:30.225: V/Values(32362): 800
11-15 22:53:30.225: V/Values(32362): 480
This is the correct height and width for the device this is running on(Galaxy S2).
Then in my next activities onCreate() I directly access "Video":
String e = Integer.toString(HomeScreen.Video.get(1).cols());
Log.v(TAG, e);
String h = Integer.toString(HomeScreen.Video.get(1).rows());
Log.v(TAG, h);
But this time the log reads:
11-15 22:53:30.840: V/Values2:(32362): 800
11-15 22:53:30.840: V/Values2:(32362): 0
So my question is, why is the row() value not 480 in both Logs? I need a List of frames because I am recording all the frames and then in another Activity I am going to operate on them and output the display(which I need to number of rows for).

I replaced the line:
Video.add(frame);
With
Video.add(frame.clone());
and it works perfectly!
I think in the top line i was only copying the header part of the frame and not the entire frame's contents.

Related

OPENCV crash when saving to file trained machine learning data (like SVM or ANN)

I have built a simple project in android studio, and included OpenCV in order to train either an SVM (support vector machine) or an ANN (artificial neural network). Everything seems to go well, including data creation, training and inspection of trained data, except for saving. Whenever I save a opencv ml-object (like ann.save(...) or svm.save(...)), android studio crashes.
SVM -
When I extract supportvectors using the line
classifier.getSupportVectors()
the numbers seem sain. However, the app crashes when I move past a breakpoint placed at
classifier.save("C:\\foo\\trentsvm.txt");
In logCat I dig up the following feedback:
07-04 14:36:10.939 25258-25258/com.example.tbrandsa.opencvtest A/libc:
Fatal signal 11 (SIGSEGV), code 2, fault addr 0x7f755f53f0 in tid
25258 (ndsa.opencvtest) [ 07-04 14:36:10.942 439: 439 W/]
debuggerd: handling request: pid=25258 uid=10227 gid=10227 tid=25258
I get a similar error if i instead try to save an artificial neural network (ANN), see update far below.
I have tried saving the file as XML and txt, and as "C:\trentsvm.someformat", and as "trentsvm.someformat". I also get the same error in my Eclipse java project. High pain, no gain. Full code is below. Could you help?
PS: I use OpenCv version 3.2.0. and Android Studio 2.3.2
// I based this code on stuff i found online. Not sure if all is as important or good.
// Purpose: multilabel classification - digit recognition for android app.
// Create data and labels for a digit recognition algorithm
int numTargets = 10; // (0-9 => 10 types of labels)
int totalSamples = 100; // Could have been number of images of digits
int totalIndicators = 10; // Could have been number of properites per digit image.
Mat labels = new Mat(totalSamples,1, CvType.CV_16S);
Mat data = new Mat(totalSamples, totalIndicators,CvType.CV_16S);
// Fill with dummy values:
for (int s = 0; s<totalSamples; s++)
{
int someLabel = s%numTargets;
labels.put(s,0, (double)someLabel);
for (int m = 0; m<totalIndicators; m++)
{
int someDataValue = (s%numTargets)*totalIndicators + m;
data.put(s, m, (double)someDataValue);
}
}
data.convertTo(data, CvType.CV_32F);
labels.convertTo(labels, CvType.CV_32S);
SVM classifier = SVM.create();
TermCriteria criteria = new TermCriteria(TermCriteria.EPS + TermCriteria.MAX_ITER,100,0.1);
classifier.setKernel(SVM.LINEAR);
classifier.setType(SVM.C_SVC); //We choose here the type CvSVM::C_SVC that can be used for n-class classification (n >= 2).
classifier.setGamma(0.5);
classifier.setNu(0.5);
classifier.setC(1);
classifier.setTermCriteria(criteria);
classifier.train(data, Ml.ROW_SAMPLE, labels);
// Check how trained SVM predicts the training data
Mat estimates = new Mat(totalSamples, 1, CvType.CV_32F);
classifier.predict(data, estimates, StatModel.RAW_OUTPUT);
for (int i = 0; i<totalSamples; i++)
{
double l = labels.get(i, 0)[0];
double e = estimates.get(i, 0)[0];
System.out.print("\n fact: "+l+", estimat: "+e);
}
Mat suppV = classifier.getSupportVectors();
try {
if (classifier.isTrained()){
// It crashes at the next line!
classifier.save("C:\\foo\\trentsvm.txt");
}
}
catch (Exception e)
{
}
Update july 5th: As suggested by ZdaR, I tried the to use an in-phone adress, but it did not solve the problem.
String address = Environment.getExternalStorageDirectory().getPath()+"/trentsvm.xml";
// address now has value "storage/emulated/0/trentsvm.xml"
classifier.save(address);
In logcat:
07-05 14:50:12.420 11743-11743/com.example.tbrandsa.opencv2 A/libc:
Fatal signal 11 (SIGSEGV), code 2, fault addr 0x7d517f1990 in tid
11743 (brandsa.opencv2)
[ 07-05 14:50:12.424 3134: 3134 W/ ] debuggerd: handling
request: pid=11743 uid=10319 gid=10319 tid=11743
Update july 6th:
When I run the same script in eclipse and use a debugger (JUnit 4, VM arguments: -Djava.library.path=C:\Users\tbrandsa\Downloads\opencv\build\java\x64;src\test\jniLibs, ) debugging on the pc without device, the caught exception "e" says the following
cause= Exception,
detailMessage= "Unknown Exception" ,
stackTrace=> StackTraceElement[0] ,
suppressedExeptions= Collections$UnmodifiableRandomAccessList,
Update july 13th:
I just tried with an artificial neural network (ANN) too, and it crashes when trying to save.
Error:
Fatal signal 11 (SIGSEGV), code 1, fault addr 0x15a57e688000c in tid
8507 (brandsa.opencv2) debuggerd: handling request: pid=8507
uid=10319 gid=10319 tid=8507
Code:
// Mat data is of size 100*20*CV_32FC1,
// Mat labels is of size 100*1*CV_32FC1
// layerSizes is of size 3*1*CV_8UC1
int[] hiddenLayers = {10};
Mat layerSizes = new Mat(2 + hiddenLayers.length,1,CvType.CV_8U);
layerSizes.put(0, 0, data.width());
for (int l = 0; l< hiddenLayers.length; l++){
layerSizes.put(1 + l, 0,hiddenLayers[l]);}
layerSizes.put(1 + hiddenLayers.length, 0,labels.width());
ANN_MLP ann = ANN_MLP.create();
ann.setLayerSizes(layerSizes);
ann.setActivationFunction(ANN_MLP.SIGMOID_SYM);
ann.train(data, Ml.ROW_SAMPLE , labels);
ann.save("/storage/emulated/0/Pictures/no.rema.priceagent.test/trentann.xml");

CursorWindow: Window is full

I'm new and after days, maybe I found that I have this issue, I have a very big data in a big listView
W/CursorWindow: Window is full: requested allocation 1432389 bytes, free space 750700 bytes, window size 2097152 bytes
E/CursorWindow: Failed to read row 0, column 0 from a CursorWindow which has 0 rows, 64 columns.
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x420aeda0)
03-03 15:50:00.162 16239-16239/id.co.bumisentosa.yantek E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I have read some same issue
android java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow
And I found my issue is my image in blob (byte) will not load into my listView.
Then how can I solve my cameraIntent and save it to a specific folder then put it in database and load it in ListView. I really need your help and by examples. Thank You
What I was use is like this
public void openCamera(int resultCode) {
Inspection_JTR_Fragment_Foto_Tab.gallery = false;
File image = new File(appFolderCheckandCreate(resultCode), "img" + getTimeStamp()
+ ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
id.co.bumisentosa.yantek.fragment_JTM.Inspection_JTM_Fragment_Foto_Tab.cameraImagePath = image.getAbsolutePath();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, resultCode);
}
private String appFolderCheckandCreate(int resultCode) {
String appFolderPath = "";
File externalStorage = Environment.getExternalStorageDirectory();
switch (resultCode) {
case 1:
if (externalStorage.canWrite()) {
appFolderPath = externalStorage.getAbsolutePath() + "/yantek-babel-android/jtr/Keseluruhan Tiang";
File dir = new File(appFolderPath);
if (!dir.exists()) {
dir.mkdirs();
}
} else {
}
break;
}
return appFolderPath;
}
And save it to database
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
if (id == R.id.action_upload) {
// Upload data ke server
imageArray = Inspection_JTM_Fragment_Foto_Tab.getimageArray();
imageArray_2 = Inspection_JTM_Fragment_Foto_Tab.getimageArray_2();
databaseHandler.saveTest(new ItemsDetails(
imageArray,
imageArray_2
));
}
return super.onOptionsItemSelected(item);
}
my database
public String saveTest(ItemsDetails details) {
try {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, post.getId());
// cv.put(KEY_ID, "null");
cv.put(COL_LOCATION_ID, details.getunitID());
cv.put(COL_SECTION_ID, details.getjaringanID());
cv.put(COL_INSPECTION_DATE, details.gettanggalInspeksi());
cv.put(COL_INSPECTION_TYPE_ID, details.gettipeInspeksiID());
cv.put(COL_PHOTO_ENTIRE_PATH, details.getimageArray());
cv.put(COL_PHOTO_ISOLATOR_PATH, details.getimageArray_2());
cv.put(COL_POLE_NO, details.getnoTiang());
cv.put(COL_POLE_IRON, details.gettiangBesi());
cv.put(COL_POLE_CONCRETE, details.gettiangBeton());
cv.put(COL_POLE_WOOD, details.gettiangKayu());
cv.put(COL_POLE_CONDITION_BROKEN, details.getkondisiTiangRetak());
cv.put(COL_POLE_CONDITION_TILT, details.getkondisiTiangMiring());
cv.put(COL_POLE_CONDITION_SHIFT, details.getkondisiTiangPindah());
cv.put(COL_CROSS_ARM_TWIST, details.getcrossArmMelintir());
cv.put(COL_CROSS_ARM_RUST, details.getcrossArmKarat());
cv.put(COL_CROSS_ARM_TILT, details.getcrossArmMiring());
cv.put(COL_ARM_TIE_REPAIR, details.getarmTiePerbaiki());
cv.put(COL_ARM_TIE_RUST, details.getarmTieKarat());
cv.put(COL_ARM_TIE_BRACE, details.getarmTiePasang());
cv.put(COL_ISOLATOR_FULCRUM_R_LEAK, details.getisolatorTumpuRGompel());
cv.put(COL_ISOLATOR_FULCRUM_R_BROKEN, details.getisolatorTumpuRPecah());
cv.put(COL_ISOLATOR_FULCRUM_S_LEAK, details.getisolatorTumpuSGompel());
cv.put(COL_ISOLATOR_FULCRUM_S_BROKEN, details.getisolatorTumpuSPecah());
cv.put(COL_ISOLATOR_FULCRUM_T_LEAK, details.getisolatorTumpuTGompel());
cv.put(COL_ISOLATOR_FULCRUM_T_BROKEN, details.getisolatorTumpuTPecah());
cv.put(COL_ISOLATOR_PULL_R_LEAK, details.getisolatorTarikRGompel());
cv.put(COL_ISOLATOR_PULL_R_BROKEN, details.getisolatorTarikRPecah());
cv.put(COL_ISOLATOR_PULL_S_LEAK, details.getisolatorTarikSGompel());
cv.put(COL_ISOLATOR_PULL_S_BROKEN, details.getisolatorTarikSPecah());
cv.put(COL_ISOLATOR_PULL_T_LEAK, details.getisolatorTarikTGompel());
cv.put(COL_ISOLATOR_PULL_T_BROKEN, details.getisolatorTarikTPecah());
cv.put(COL_ARRESTER_R_BROKEN, details.getarresterRusakR());
cv.put(COL_ARRESTER_S_BROKEN, details.getarresterRusakS());
cv.put(COL_ARRESTER_T_BROKEN, details.getarresterRusakT());
cv.put(COL_CONDUCTOR_R_BUYER, details.getkonduktorRBuyer());
cv.put(COL_CONDUCTOR_R_LOOSE, details.getkonduktorRKendor());
cv.put(COL_CONDUCTOR_S_BUYER, details.getkonduktorSBuyer());
cv.put(COL_CONDUCTOR_S_LOOSE, details.getkonduktorSKendor());
cv.put(COL_CONDUCTOR_T_BUYER, details.getkonduktorTBuyer());
cv.put(COL_CONDUCTOR_T_LOOSE, details.getkonduktorTKendor());
cv.put(COL_CONNECTOR_PG_R_35MM, details.getkonektorPGR35mm());
cv.put(COL_CONNECTOR_PG_R_70MM, details.getkonektorPGR70mm());
cv.put(COL_CONNECTOR_PG_R_150MM, details.getkonektorPGR150mm());
cv.put(COL_CONNECTOR_PG_S_35MM, details.getkonektorPGS35mm());
cv.put(COL_CONNECTOR_PG_S_70MM, details.getkonektorPGS70mm());
cv.put(COL_CONNECTOR_PG_S_150MM, details.getkonektorPGS150mm());
cv.put(COL_CONNECTOR_PG_T_35MM, details.getkonektorPGT35mm());
cv.put(COL_CONNECTOR_PG_T_70MM, details.getkonektorPGT70mm());
cv.put(COL_CONNECTOR_PG_T_150MM, details.getkonektorPGT150mm());
cv.put(COL_BENDING_WIRE_R, details.getbendingWireR());
cv.put(COL_BENDING_WIRE_S, details.getbendingWireS());
cv.put(COL_BENDING_WIRE_T, details.getbendingWireT());
cv.put(COL_ULTRASONIC_R, details.getultrasonicR());
cv.put(COL_ULTRASONIC_S, details.getultrasonicS());
cv.put(COL_ULTRASONIC_T, details.getultrasonicT());
cv.put(COL_GSW_EXIST, details.getgswAda());
cv.put(COL_GSW_NOT_EXIST, details.getgswTidakAda());
cv.put(COL_TREE_EXIST, details.getpohonAda());
cv.put(COL_TREE_NOT_EXIST, details.getpohonTidakAda());
cv.put(COL_LONGITUDE, details.getlongitude());
cv.put(COL_LATITUDE, details.getlatitude());
cv.put(COL_SUGGESTION, details.getSaran());
cv.put(COL_DESCR, details.getketerangan());
db.insert(INSPECTIONS_MV_TABLE_NAME, null, cv);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return getNewTestID();
}
Then how can I solve my cameraIntent and save it to a specific folder
then put it in database and load it in ListView. I really need your
help and by examples.
In short you can't. Although you can store the image in the database you cannot retrieve it from the database because it is too large to fit into a CursorWindow which has a limitation of 2MB (2097152).
The image itself is around 1432389 bytes but the CursorWindow only has 750700 bytes. So as 1432389 is greater than 750700 image (blob) it can't be extracted.
You can get around the issue if you :-
save it to a specific folder, then
save the path (or part of the path) in the database rather than the image, and then
extract the path and then get the image via the path when loading the ListView.

Java application on Microsoft Surface not full screen

I have a Java application, developed in eclipse and with an exe wrapper. It runs full screen on a win 7 desktop, but not on a Win 8 surface (original) with Intel HD Graphics 4000. When run on the surface it has black space all around it. I found multiple references to updating the graphics driver to get extra options about how the screen scales. The latest drivers from Intel are rejected when I try to install them. If I try to do an update via device manager it says I am current. Looking for any suggestions/info. Thank you.
--- add ons ---
Surface has Java 8 update 65
public class Fullscreen
{
private static GraphicsDevice _device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private static DisplayMode _oldMode = null;
public static Drawable _drawable;
public static BufferStrategy _bufStrat;
public static int _frameCount;
public static long _secondTrack;
//==========================================================================
/**
* Set some video related stuff
* #param frame - The App's JFrame
* #return - true if sucessful
*/
public static boolean set( JFrame frame )
{
frame.setResizable ( false );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
if (MainBase._fullScreen) // Is true for this version
{
frame.setUndecorated ( true );
frame.setIgnoreRepaint ( true );
if (MainBase._fullScreen && !_device.isFullScreenSupported())
{
System.err.println( "Full screen not supported" );
return false;
}
try
{
_device.setFullScreenWindow( frame );
}
catch ( Exception e )
{
_device.setFullScreenWindow( null );
System.err.println( "Failed setting full screen" );
return false;
}
_oldMode = _device.getDisplayMode();
//TODO: what to do about display refresh vs frame rate
DisplayMode displayMode = new DisplayMode( MainBase._screenW, MainBase._screenH, 32, 60); //MainBase._fps );
if (displayMode != null && _device.isDisplayChangeSupported())
{
try
{
_device.setDisplayMode( displayMode );
}
catch (Exception e)
{
_device.setDisplayMode( _oldMode );
_device.setFullScreenWindow( null );
System.err.println( "Failed setting full screen mode" );
return false;
}
}
}
//System.out.println( "Display Mode W " + MainBase._screenW + " H " + MainBase._screenH + " BitDepth " + 32 );
return true;
}
----- Important info although not solved -----
I tried to update the surface to Win 10. The update failed. I then rolled back to Win 8. After I reinstalled my extra stuff the application ran at full screen. Until it crashed and I had to kill it in Task Manager. After that it was back to not full screen. Something obviously got tweaked or carried of from that run. Not a solution but an important lead to follow.

Adding Two Mat of type 32FC4 in OpenCV for Android

To reduce the noise in an image, I am trying to get the average of 10 images.
Mat imgMain = new Mat(n_height, n_width, CvType.CV_32FC4);
Mat imgFin = new Mat(n_height, n_width, CvType.CV_32FC4);
for(int i=1; i <= 10; i++) {
//Crop the image
image.recycle();
image = null;
image = BitmapFactory.decodeFile("/storage/sdcard0/DCIM/A" + String.valueOf(i) + ".jpg");
pimage = Bitmap.createBitmap(image, leftOff1, topOff1, n_width, n_height);
Utils.bitmapToMat(pimage, imgMain);
scaleAdd(imgMain, 0.1, imgFin, imgFin);
}
Running the application, I get the following msg:
Caused by: CvException [org.opencv.core.CvException: cv::Exception:
/hdd2/buildbot/slaves/slave_ardbeg1/50-SDK/opencv/modules/core/src/matmul.cpp:2079:
error: (-215) src1.type() == src2.type() in function void
cv::scaleAdd(cv::InputArray, double, cv::InputArray, cv::OutputArray)
]
at org.opencv.core.Core.scaleAdd_0(Native Method)
at org.opencv.core.Core.scaleAdd(Core.java:6690)
at MainActivity.imageAnalysis(MainActivity.java:123)
where line 123 is scaleAdd(imgMaing, 0.1, imgFin, imgFin);
According to the reference, src1, src2 and dst MAT should be of same size and type. However, I get this error when I set imgFin type to 32FC4 but do not get any errors when imgFin is set to 8UC4. Any experience of this kind? I need to keep the floating numbers in imgFin which is why I can't go with 8UC4.
// this line will overwrite your imgMain,
// the type will be CV_8UC4, regardless, what you said before.
Utils.bitmapToMat(pimage, imgMain);
// so, convert to float:
imgMain.convertTo(imgMain, CvType.CV_32FC4);
// now add float images, to avoid precision loss:
scaleAdd(imgMain, 0.1, imgFin, imgFin);

Android - add table rows after table loading

I am reading UDP packets and i wanna display that info on UI as table in android app.
Here is my code,
try {
byte buffer[] = new byte[10000];<br/>
InetAddress address = InetAddress.getByName("192.168.xx.xx");<br/>
int port = xxx;<br/>
Log.d("..........","What will Happen ?? ");<br/>
for(int k=0;k<50;k++) { // 50 rows are added , This i wanna make it 5000+ rows so it takes plenty of time to load that table <br/>
DatagramPacket p = new DatagramPacket(buffer, buffer.length, address, port);<br/>
DatagramSocket ds = new DatagramSocket(port);<br/>
Log.d("..........","Perfect Binding .... Waiting for Data");<br/>
ds.receive(p);<br/>
Log.d("..........","Packet Received");<br/>
byte[] data = p.getData();<br/>
String result = "";<br/>
int b[] = new int[data.length];</br>
for (int i=0; i < 150; i++) {<br/>
result += Integer.toString( ( data[i] & 0xff ) + 0x100, 16).substring( 1 );<br/>
result += "_";<br/>
}<br/>
Log.d("Result => ",result); <br/>
TableLayout tl=(TableLayout)findViewById(R.id.TableLayout01);<br/>
TableRow tr=new TableRow(this);
TextView tv= new TextView(this);
TextView tv2 = new TextView(this);
tv.setPadding(5, 0, 5, 0);
tv2.setPadding(5,0,5,0);
String k1 = Integer.toString(k);
tv.setText(k1);
tv2.setText(it_version);
tr.addView(tv);
tr.addView(tv2);
tl.addView(tr,1);
ds.close();
}
} catch (Exception e) {
Log.e("UDP", "Client error", e);
}
If i keep 50 rows am able to display it properly without any time delay, if i put 3000 rows its taking too long time and sometimes app is hanging... I wanna add 50 entries to a table and load the table and again read 50 entries and append to the table without touching any button or anything so i have a table in UI and it will update automatically by reading UDP packets ... how i can achieve that ?? Any clue appreciated.
or once i read the UDP packet i wanna display it on UI[appending to the table],How i can do this ??[Scrolling and all i will take care] please let me know
I already tried using threads but no use
Basically, you need to implement an infinite listview. There are a couple strategies to do this:
You can get all the data and store it in a database and only show the user 50 at a time.
You can fetch only 50 at first and then fetch the next 50 when the user scrolls past them.
You can fetch 100, show 50 and then show next 50 when the user scrolls past the first 50. Pre-fetch the next 100 to show next and so on.
Once you figured out your fetching strategy, you need to implement the actual adapter and listview. Here's a good technique to do this. I would recommend that you don't re-invent the wheel and use this great library called EndlessAdapter unless you want to implement it for learning purposes.
Something like this is what you might use in order to get a infinite list effect when you don't have a cursor.
Please note this is a very rough draft since I deleted the code only relevant to my app, to help for you clarity, and for my privacy and the apps privacy. Also it may not be the best way of doing everything, but it worked the first time I wrote it (which took like 10 minutes) and worked beautifully for a very complex list, so I haven't bothered coming back to it.
class AsyncGetUpdates extends AsyncTask<Void, Void, List<UpdateDTO>>
{
#Override
protected void onPreExecute()
{
showDialog();
super.onPreExecute();
}
#Override
protected List<UpdateDTO> doInBackground(Void... params)
{
return APIHelper.getUpdates(count);
}
#Override
protected void onPostExecute(List<UpdateDTO> result)
{
killDialog();
isCurrentlyUpdating = false;
setAdapterData(result);
super.onPostExecute(result);
}
}
public void setAdapterData(List<UpdateDTO> result)
{
killDialog();
if (this != null && this.getActivity() != null)
{
Log.d(TAG, "setAdapterData");
if (lvUpdatesList.getAdapter() != null)
{
// save index and top position
int index = lvUpdatesList.getFirstVisiblePosition();
View v = lvUpdatesList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
updateListAdapter = new UpdateListAdapter(this.getActivity().getLayoutInflater(), result, this);
lvUpdatesList.setAdapter(updateListAdapter);
lvUpdatesList.refreshDrawableState();
lvUpdatesList.setSelectionFromTop(index, top);
}
else
{
updateListAdapter = new UpdateListAdapter(this.getActivity().getLayoutInflater(), result, this);
lvUpdatesList.setAdapter(updateListAdapter);
lvUpdatesList.refreshDrawableState();
}
}
// add in a listener to know when we get to the bottom
lvUpdatesList.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
// we do not want to update if we already are
if (isCurrentlyUpdating == false)
{
if (lvUpdatesList.getAdapter() != null && lvUpdatesList.getAdapter().getCount() == count)
{
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount)
{
isCurrentlyUpdating = true;
// add to the count of views we want loaded
count += 20;
// start a update task
new AsyncGetUpdates().execute();
}
}
}
}
});
}
Finally I would like to say that copy pasting might get you the results you want, but it will hinder you future ability. I would say study, read, learn, try, fail, and try again.

Categories