I created this class, And I want to load thumbnails into the iconview as a different thread for efficiency reasons, because the gui load very slow if I do it in the same thread. But when I create the thread, it doesn't works, it draw some thumbnails and then they dissapear. When I use join, it works. This is my code:
public class FotoThumbnailPane : Gtk.ScrolledWindow{
private FotoThumbnailPane_i pane;
private string namet;
public FotoThumbnailPane(string name){
this.namet = name;
}
public void set_imagelist(fileutils.ImageList image_list){
pane = new FotoThumbnailPane_i(image_list);
this.add (pane);
this.set_min_content_width(140);
this.show_all();
}
//This is my threaded function
public void* load_thumbs(){
pane.set_visible(false);
pane.newmodel = new Gtk.ListStore (2, typeof (Gdk.Pixbuf), typeof (string));
pane.set_selection_mode (Gtk.SelectionMode.SINGLE);
pane.set_pixbuf_column (0);
pane.set_model(pane.newmodel);
string icon_style = """
.thumbnail-view {
background-color: #FFFFFF;
}
.thumbnail-view:selected {
background-color: #9D9D9D;
border-color: shade (mix (rgb (34, 255, 120), #fff, 0.5), 0.9);
}
""";
var icon_view_style = new Gtk.CssProvider ();
try {
icon_view_style.load_from_data (icon_style, -1);
} catch (Error e) {
warning (e.message);
}
pane.get_style_context ().add_class ("thumbnail-view");
pane.get_style_context ().add_provider (icon_view_style, Gtk.STYLE_PROVIDER_PRIORITY_THEME);
//Add thumbnails to the iconview
string buff;
for(int i=1; i<pane.image_list.size; i++){
buff = pane.image_list.get_full_filename(i);
stdout.printf("Added %s to thumbnail\n", buff);
var image = new Gdk.Pixbuf.from_file_at_scale(buff, 110, 80, false);
// Add the wallpaper name and thumbnail to the IconView
Gtk.TreeIter root;
pane.newmodel.append(out root);
pane.newmodel.set(root, 0, image, -1);
pane.newmodel.set(root, 1, pane.image_list.get_filename(i), -1);
// Select the thumbnail if it is the first in list
if (i==0) {
pane.select_path (pane.newmodel.get_path (root));
}
pane.iters.append (root);
}
pane.set_sensitive(true);
this.queue_draw();
return null;
}
}
You don't actually need to deal with threads in your program--you can just use an asynchronous method to load the content. Specifically, Gdk.Pixbuf.new_from_stream_at_scale_async.
Here is an example:
public async void load (Gtk.Image img, string filename) {
GLib.File file = GLib.File.new_for_commandline_arg (filename);
try {
GLib.InputStream stream = yield file.read_async ();
Gdk.Pixbuf pixbuf = yield Gdk.Pixbuf.new_from_stream_at_scale_async (stream, 320, -1, true);
img.set_from_pixbuf (pixbuf);
} catch ( GLib.Error e ) {
GLib.error (e.message);
}
}
private static int main (string[] args) {
GLib.return_val_if_fail (args.length > 1, -1);
Gtk.init (ref args);
Gtk.Window win = new Gtk.Window ();
win.destroy.connect (() => {
Gtk.main_quit ();
});
Gtk.Image image = new Gtk.Image ();
win.add (image);
load.begin (image, args[1], (obj, async_res) => {
GLib.debug ("Finished loading.");
});
win.show_all ();
Gtk.main ();
return 0;
}
Related
In my android studio project I am trying to select an image from external storage via startActivityForResult and load the selected image into memory. Also I have a BitmapLoader helper class. Here is the piece of code where I call the activity to get the result
private void pickFromGallery() {
//Create an Intent with action as ACTION_PICK
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// Sets the type as image/*. This ensures only components of type image are selected
intent.setType("image/*");
//We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
String[] mimeTypes = {"image/jpeg", "image/png"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
// Launching the Intent
startActivityForResult(intent, GALLERY_REQUEST_CODE); //GALLERY_REQUEST_CODE is a constant integer
}
And here is the activity result callback
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result code is RESULT_OK only if the user selects an Image
if(resultCode == Activity.RESULT_OK) {
Bitmap imageBitmap = null;
switch(requestCode) {
case GALLERY_REQUEST_CODE:
//data.getData returns the content URI for the selected Image
File file = new File(data.getData().getPath());
try {
//BitmapLoader is my helper class
imageBitmap = BitmapLoader.decodeSampleBitmapFromFile(file, 100, 100);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error while reading a file!", Toast.LENGTH_SHORT).show();
return;
}
userImage.setImageBitmap(imageBitmap);
break;
}
}
}
Finally, here is the BitmapLoader helper class.
public class BitmapLoader {
private BitmapLoader() {}
private static Bitmap rotateImageIfRequired(Bitmap img, File file) throws IOException {
ExifInterface ei = new ExifInterface(file);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize += 1;
}
}
return inSampleSize;
}
public static Bitmap decodeSampleBitmapFromFile(File file, int reqWidth, int reqHeight) throws IOException {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), options);
return rotateImageIfRequired(bitmap, file);
}
}
The problem is, when I call imageBitmap = BitmapLoader.decodeSampleBitmapFromFile(file, 100, 100); , it always throws an exception. I think the problem is the part where I create a File object from the Uri returned as a result. Can anyone please describe to me where the problem is coming from and help me write the correct code?
I found the right way to solve the problem. Here is the commented code describing the true way to solve the problem.
private void pickFromGallery() {
// intent with ACTION_OPEN_DOCUMENT to make
// content providers (gallery application, downloads application and so on)
// to show their files
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//and that files must be openable
intent.addCategory(Intent.CATEGORY_OPENABLE);
//setting mime type to get only image files
intent.setType("image/*");
//just invoking intent
startActivityForResult(intent, GALLERY_REQUEST_CODE);
}
//getting picked image
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result code is RESULT_OK only if the user selects an Image
if(resultCode == Activity.RESULT_OK) {
Bitmap imageBitmap;
switch(requestCode) {
case GALLERY_REQUEST_CODE:
if(data == null) return;
//ParcelFileDescriptor allowing you to close it when done with it.
ParcelFileDescriptor parcelFileDescriptor;
try {
//a method to get file descriptor via Uri(data.getData() returns a Uri, "r" means for reading)
parcelFileDescriptor = getContentResolver().openFileDescriptor(data.getData(), "r");
//getting a descriptor from ParcelFileDescriptor
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
// and sending that descriptor to BitmapLoader, which now takes only descriptor and required width and height to load bitmap
imageBitmap = BitmapLoader.decodeSampleBitmapFromDescriptor(fileDescriptor, 100, 100);
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error while reading a file!", Toast.LENGTH_SHORT).show();
return;
}
//here you can use the loaded bitmap as you like
userImage.setImageBitmap(imageBitmap);
break;
}
}
}
Finally the Bitmaploader class
public class BitmapLoader {
private BitmapLoader() {}
//this method uses ExifInterface to figure out how to rotate the image to bring it back to normal orientation, but that's another story.
private static Bitmap rotateImageIfRequired(Bitmap img, FileDescriptor descriptor) throws IOException {
ExifInterface ei = new ExifInterface(descriptor);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
//just a helper for the previous method
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
// calculates how many times a bitmap should be reduced
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize += 1;
}
}
return inSampleSize;
}
//main working method that throws an IOException because there might be problems reading the file
public static Bitmap decodeSampleBitmapFromDescriptor(#NonNull FileDescriptor descriptor, int reqWidth, int reqHeight) throws IOException {
// BitmapFactory.Options helps to load only the image information first.
final BitmapFactory.Options options = new BitmapFactory.Options();
// must set to true to load only the image information
options.inJustDecodeBounds = true;
/**null is just a padding*/
//loading into options the information about image
BitmapFactory.decodeFileDescriptor(descriptor, null, options);
// Calculation of the dimensions of the image for loading in accordance with the required width and height
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// now setting to false to load real bitmap with required dimensions
options.inJustDecodeBounds = false;
//decoding an image and returning a bitmap
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(descriptor, null, options);
return rotateImageIfRequired(bitmap, descriptor);
}
}
It is very important to load the image into memory at a reduced size, because a bitmap of a real image may require over 500MB of RAM.
Hello am new to Android studio
I have made recylerview for transaction details . I need to create pdf for this recylerview items.
Example: I have 24 cardviews in recylerview so need to create pdf with each page 4 cardviews only . So totally I need to get pdf as 6 pages .
How to do that . Thanks in advance.
This is sample image of my view
Am passing below code
recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);
String mpath2="/mnt/sdcard/mathanpaymentpdf";
File imageFile = new File(mpath2);
PDFHelper pdfHelper = new PDFHelper(imageFile,this);
pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This am tried am getting pdf on a single page only
Just I need to split into multiple pages.
Note: I need code in java, not in kotlin
Am solved this by using itext library
implementation 'com.itextpdf:itextpdf:5.0.6'
Then call with RecylerView
public void generatePDF(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
int sie2=adapter.getItemCount();
if (sie2 == 0) {
Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
}else{
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document=new Document();
final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
//Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
// Set on UI Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dialog.dismiss();
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent56 = Intent.createChooser(target, "Open File");
try {
startActivity(intent56);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}}
}
100% working.. This helps to anyone needs
I developed a simple bluetooth connection application in j2me.
I try it on emulator, both server and client can found each other, but when I deploy the application to blackberry mobile phone and connect to a bluetoothbee device it says service search no records.
What could it be possibly wrong? is it j2me can not find a service in bluetoothbee?
The j2me itself succeed to found the bluetoothbee device, but why it can not find the service?
My code is below. What I don't understand is the UUID? how to set UUID for unknown source? since I didn't know the UUID for the bluetoothbee device.
class SearchingDevice extends Canvas implements Runnable,CommandListener,DiscoveryListener{
//......
public SearchingDevice(MenuUtama midlet, Display display){
this.display = display;
this.midlet = midlet;
t = new Thread(this);
t.start();
timer = new Timer();
task = new TestTimerTask();
/*--------------------Device List------------------------------*/
select = new Command("Pilih",Command.OK,0);
back = new Command("Kembali",Command.BACK,0);
btDevice = new List("Pilih Device",Choice.IMPLICIT);
btDevice.addCommand(select);
btDevice.addCommand(back);
btDevice.setCommandListener(this);
/*------------------Input Form---------------------------------*/
formInput = new Form("Form Input");
nama = new TextField("Nama","",50,TextField.ANY);
umur = new TextField("Umur","",50,TextField.ANY);
measure = new Command("Ukur",Command.SCREEN,0);
gender = new ChoiceGroup("Jenis Kelamin",Choice.EXCLUSIVE);
formInput.addCommand(back);
formInput.addCommand(measure);
gender.append("Pria", null);
gender.append("Wanita", null);
formInput.append(nama);
formInput.append(umur);
formInput.append(gender);
formInput.setCommandListener(this);
/*---------------------------------------------------------------*/
findDevice();
}
/*----------------Gambar screen searching device---------------------------------*/
protected void paint(Graphics g) {
g.setColor(0,0,0);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(255,255,255);
g.drawString("Mencari Device", 20, 20, Graphics.TOP|Graphics.LEFT);
if(this.counter == 1){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
}
if(this.counter == 2){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
g.setColor(100,255,255);
g.fillRect(60, 80, 20, 40);
}
if(this.counter == 3){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
g.setColor(100,255,255);
g.fillRect(60, 80, 20, 40);
g.setColor(255,115,200);
g.fillRect(100, 60, 20, 60);
}
if(this.counter == 4){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
g.setColor(100,255,255);
g.fillRect(60, 80, 20, 40);
g.setColor(255,115,200);
g.fillRect(100, 60, 20, 60);
g.setColor(100,255,255);
g.fillRect(140, 40, 20, 80);
//display.callSerially(this);
}
}
/*--------- Running Searching Screen ----------------------------------------------*/
public void run() {
while(run){
this.counter++;
if(counter > 4){
this.counter = 1;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("interrupt"+ex.getMessage());
}
repaint();
}
}
/*-----------------------------cari device bluetooth yang -------------------*/
public void findDevice(){
try {
devices = new java.util.Vector();
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
local.setDiscoverable(DiscoveryAgent.GIAC);
agent.startInquiry(DiscoveryAgent.GIAC, this);
} catch (BluetoothStateException ex) {
System.out.println("find device"+ex.getMessage());
}
}
/*-----------------------------jika device ditemukan--------------------------*/
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
devices.addElement(rd);
}
/*--------------Selesai tes koneksi ke bluetooth server--------------------------*/
public void inquiryCompleted(int param) {
switch(param){
case DiscoveryListener.INQUIRY_COMPLETED: //inquiry completed normally
if(devices.size()>0){ //at least one device has been found
services = new java.util.Vector();
this.findServices((RemoteDevice)devices.elementAt(0));
this.run = false;
do_alert("Inquiry completed",4000);
}else{
do_alert("No device found in range",4000);
}
break;
case DiscoveryListener.INQUIRY_ERROR:
do_alert("Inquiry error",4000);
break;
case DiscoveryListener.INQUIRY_TERMINATED:
do_alert("Inquiry canceled",4000);
break;
}
}
/*-------------------------------Cari service bluetooth server----------------------------*/
public void findServices(RemoteDevice device){
try {
// int[] attributes = {0x100,0x101,0x102};
UUID[] uuids = new UUID[1];
//alamat server
uuids[0] = new UUID("F0E0D0C0B0A000908070605040302010",false);
//uuids[0] = new UUID("8841",true);
//menyiapkan device lokal
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
//mencari service dari server
agent.searchServices(null, uuids, device, this);
//server = (StreamConnectionNotifies)Connector.open(url.toString());
} catch (BluetoothStateException ex) {
// ex.printStackTrace();
System.out.println("Errorx"+ex.getMessage());
}
}
/*---------------------------Pencarian service selesai------------------------*/
public void serviceSearchCompleted(int transID, int respCode) {
switch(respCode){
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
if(currentDevice == devices.size() - 1){
if(services.size() > 0){
this.run = false;
display.setCurrent(btDevice);
do_alert("Service found",4000);
}else{
do_alert("The service was not found",4000);
}
}else{
currentDevice++;
this.findServices((RemoteDevice)devices.elementAt(currentDevice));
}
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
do_alert("Device not Reachable",4000);
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
do_alert("Service search error",4000);
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
do_alert("No records return",4000);
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
do_alert("Inquiry canceled",4000);
break;
} }
public void servicesDiscovered(int i, ServiceRecord[] srs) {
for(int x=0; x<srs.length;x++)
services.addElement(srs[x]);
try {
btDevice.append(((RemoteDevice)devices.elementAt(currentDevice)).getFriendlyName(false),null);
} catch (IOException ex) {
System.out.println("service discover"+ex.getMessage());
}
}
public void do_alert(String msg, int time_out){
if(display.getCurrent() instanceof Alert){
((Alert)display.getCurrent()).setString(msg);
((Alert)display.getCurrent()).setTimeout(time_out);
}else{
Alert alert = new Alert("Bluetooth");
alert.setString(msg);
alert.setTimeout(time_out);
display.setCurrent(alert);
}
}
private String getData(){
System.out.println("getData");
String cmd="";
try {
ServiceRecord service = (ServiceRecord)services.elementAt(btDevice.getSelectedIndex());
String url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
conn = (StreamConnection)Connector.open(url);
DataInputStream in = conn.openDataInputStream();
int i=0;
timer.schedule(task, 15000);
char c1;
while(time){
//while(((c1 = in.readChar())>0) && (c1 != '\n')){
//while(((c1 = in.readChar())>0) ){
c1 = in.readChar();
cmd = cmd + c1;
//System.out.println(c1);
// }
}
System.out.print("cmd"+cmd);
if(time == false){
in.close();
conn.close();
}
} catch (IOException ex) {
System.err.println("Cant read data"+ex);
}
return cmd;
}
//timer task fungsinya ketika telah mencapai waktu yg dijadwalkan putus koneksi
private static class TestTimerTask extends TimerTask{
public TestTimerTask() {
}
public void run() {
time = false;
}
}
}
I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.
How do I get JTextPane to scroll? In this example, JScrollPane is employed but as running the code will reveal, the scroll bar can be displayed but it is not functional.
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneTester
{
JTextPane jtp = new JTextPane();
StyledDocument doc;
Style style;
JScrollPane jsp = new JScrollPane(jtp);
JTextPaneTester()
{
doc = (StyledDocument)jtp.getDocument();
style = doc.addStyle("fancy", null);
jsp.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
}
void append(String s)
{
try
{
doc.insertString(doc.getLength(), s, style);
}
catch (BadLocationException e) { assert false: "problem"; }
}
public static void main(String[] args)
{
JTextPaneTester thing = new JTextPaneTester();
for (int i = 0; i < 100; i++)
thing.append("nouns verbs adjectives \n");
JFrame f = new JFrame();
JPanel center = new JPanel();
f.add(center, BorderLayout.CENTER);
center.add(thing.jsp);
f.setSize(400, 400);
f.setVisible(true);
}
}
If I place the snippet
for (int i = 0; i < 100; i++) {
thing.append("nouns verbs adjectives \n");
}
after
f.setVisible(true);
it seems to work.