Search Results

Search found 561 results on 23 pages for 'inputstream'.

Page 11/23 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Only Execute Code on Certain Requests Java

    - by BillPull
    I am building a little API for class and the teacher supplied us with a link to a tutorial that provided a simple webserver that implements Runnable. I have already written some code that will parse arguments the arguments ( or at least get me the request string ) and some code that will return some simple xml. however I think certain requests like the one for the favicon are sent I think it is messing up my code. I wrapped that in an if else but it does not seem to be working. package server; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.*; import java.io.*; import java.net.*; import parkinglots.*; public class WorkerRunnable implements Runnable{ protected Socket clientSocket = null; protected String serverText = null; public WorkerRunnable(Socket clientSocket, String serverText) { this.clientSocket = clientSocket; this.serverText = serverText; } public Boolean authenticateAPI(String key){ //Authenticate Key against Stored Keys //TODO: Create Stored Keys and Compare return true; } public void run() { try { InputStream input = clientSocket.getInputStream(); OutputStream output = clientSocket.getOutputStream(); long time = System.currentTimeMillis(); //TODO: Parse args and output different formats and Authentication //Parse URL Arguments BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "8859_1")); String request = in.readLine(); //Server gets Favicon Request so skip that and goto args System.out.println(request); if ( request != "GET /favicon.ico HTTP/1.1" && request != "GET / HTTP/1.1" && request != null ){ String format = "", apikey =""; System.out.println("I am Here"); String request_location = request.split(" ")[1]; String request_args = request_location.replace("/",""); request_args = request_args.replace("?",""); String[] queries = request_args.split("&"); System.out.println(queries[0]); for ( int i = 0; i < queries.length; i++ ){ if( queries[i] == "format" ){ format = queries[i].split("=")[1]; } else if( queries[i] == "apikey" ){ apikey = queries[i].split("=")[1]; } } if( apikey == "" ){ apikey = "None"; } if( format == "" ){ format = "xml"; } Boolean auth = authenticateAPI(apikey); if ( auth ){ if ( format == "xml"){ // Retrieve XML Document String xml = LotFromDB.getParkingLotXML(); output.write((xml).getBytes()); }else{ //Retrieve JSON String json = LotFromDB.getParkingLotJSON(); output.write((json).getBytes()); } }else{ output.write(("Access Denied - User is Not Authenticated").getBytes()); } }else{ output.write(("Access Denied Must Pass API Key").getBytes()); } output.close(); input.close(); System.out.println("Request processed: " + time); } catch (IOException e) { //report exceptions e.printStackTrace(); } } } Console output I get I am Here format=json Request processed: 1333516648331 GET /favicon.ico HTTP/1.1 I am Here favicon.ico Request processed: 1333516648332 It always returns the XML as well. This is my first exposure to writing a web server and dealing with networking in Java, which frustrates me a lot in general, So any suggestions here are very appreciated.

    Read the article

  • Using AsyncTask, but experiencing unexpected behaviour

    - by capcom
    Please refer to the following code which continuously calls a new AsyncTask. The purpose of the AsyncTask is to make an HTTP request, and update the string result. package room.temperature; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class RoomTemperatureActivity extends Activity { String result = null; StringBuilder sb=null; TextView TemperatureText, DateText; ArrayList<NameValuePair> nameValuePairs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TemperatureText = (TextView) findViewById(R.id.temperature); DateText = (TextView) findViewById(R.id.date); nameValuePairs = new ArrayList<NameValuePair>(); for (int i = 0; i < 10; i++) { RefreshValuesTask task = new RefreshValuesTask(); task.execute(""); } } // The definition of our task class private class RefreshValuesTask extends AsyncTask<String, Integer, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://mywebsite.com/roomtemp/tempscript.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine()); is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return result; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); //System.out.println(result); setValues(result); } } public void setValues(String resultValue) { System.out.println(resultValue); String[] values = resultValue.split("&"); TemperatureText.setText(values[0]); DateText.setText(values[1]); } } The problem I am experiencing relates to the AsyncTask in some way or the function setValues(), but I am not sure how. Essentially, I want each call to the AsyncTask to run, eventually in an infinite while loop, and update the TextView fields as I have attempted in setValues. I have tried since yesterday after asking a question which led to this code, for reference. Oh yes, I did try using the AsyncTask get() method, but that didn't work either as I found out that it is actually a synchronous call, and renders the whole point of AsyncTask useless.

    Read the article

  • Jdbc - Connect remote Mysql Database error

    - by Guilherme Ruiz
    I'm using JDBC to connect my program to a MySQL database. I already put the port number and yes, my database have permission to access. When i use localhost work perfectly, but when i try connect to a remote MySQL database, show this error on console. java.lang.ExceptionInInitializerError Caused by: java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:454) at java.lang.Integer.parseInt(Integer.java:527) at serial.BDArduino.<clinit>(BDArduino.java:25) Exception in thread "main" Java Result: 1 CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo) Thank you in Advance ! MAIN CODE /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package serial; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author Ruiz */ public class BDArduino extends JFrame { static boolean connected = false; static int aux_sql8 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin8")); static int aux_sql2 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin2")); CommPort commPort = null; SerialPort serialPort = null; InputStream inputStream = null; static OutputStream outputStream = null; String comPortNum = "COM10"; int baudRate = 9600; int[] intArray = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; /** * Creates new form ArduinoTest */ public BDArduino() { //super("Arduino Test App"); initComponents(); } class Escrita extends Thread { private int i; public void run() { while (true) { System.out.println("Número :" + i++); } } } //public void actionPerformed(ActionEvent e) { // String arg = e.getActionCommand(); public static void writeData(int a) throws IOException { outputStream.write(a); } public void action(String arg) { System.out.println(arg); Object[] msg = {"Baud Rate: ", "9600", "COM Port #: ", "COM10"}; if (arg == "connect") { if (connected == false) { new BDArduino.ConnectionMaker().start(); } else { closeConnection(); } } if (arg == "disconnect") { serialPort.close(); closeConnection(); } if (arg == "p2") { System.out.print("Pin #2\n"); try { outputStream.write(intArray[0]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p3") { System.out.print("Pin #3\n"); try { outputStream.write(intArray[1]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p4") { System.out.print("Pin #4\n"); try { outputStream.write(intArray[2]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p5") { System.out.print("Pin #5\n"); try { outputStream.write(intArray[3]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p6") { System.out.print("Pin #6\n"); try { outputStream.write(intArray[4]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p7") { System.out.print("Pin #7\n"); try { outputStream.write(intArray[5]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p8") { System.out.print("Pin #8\n"); try { outputStream.write(intArray[6]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p9") { System.out.print("Pin #9\n"); try { outputStream.write(intArray[7]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p10") { System.out.print("Pin #10\n"); try { outputStream.write(intArray[8]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p11") { System.out.print("Pin #11\n"); try { outputStream.write(intArray[9]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p12") { System.out.print("Pin #12\n"); try { outputStream.write(intArray[10]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p13") { System.out.print("Pin #12\n"); try { outputStream.write(intArray[11]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } } //******************************************************* //Arduino Connection *************************************** //****************************************************** void closeConnection() { try { outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); String cantCloseConnectionMessage = "Can't Close Connection!"; JOptionPane.showMessageDialog(null, cantCloseConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } connected = false; System.out.print("\nDesconectado\n"); String disconnectedConnectionMessage = "Desconectado!"; JOptionPane.showMessageDialog(null, disconnectedConnectionMessage, "Desconectado", JOptionPane.INFORMATION_MESSAGE); }//end closeConnection() void connect() throws Exception { String portName = comPortNum; CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) { System.out.println("Error: Port is currently in use"); String portInUseConnectionMessage = "Port is currently in use!\nTry Again Later..."; JOptionPane.showMessageDialog(null, portInUseConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } else { commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); outputStream = serialPort.getOutputStream(); } else { System.out.println("Error: Only serial ports are handled "); String onlySerialConnectionMessage = "Serial Ports ONLY!"; JOptionPane.showMessageDialog(null, onlySerialConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } }//end else //wait some time try { Thread.sleep(300); } catch (InterruptedException ie) { } }//end connect //******************************************************* //*innerclasses****************************************** //******************************************************* public class ConnectionMaker extends Thread { public void run() { //try to make a connection try { connect(); } catch (Exception ex) { ex.printStackTrace(); System.out.print("ERROR: Cannot connect!"); String cantConnectConnectionMessage = "Cannot Connect!\nCheck the connection settings\nand/or your configuration\nand try again!"; JOptionPane.showMessageDialog(null, cantConnectConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } //show status serialPort.notifyOnDataAvailable(true); connected = true; //send ack System.out.print("\nConnected\n"); String connectedConnectionMessage = "Conectado!"; JOptionPane.showMessageDialog(null, connectedConnectionMessage, "Conectado", JOptionPane.INFORMATION_MESSAGE); }//end run }//end ConnectionMaker /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { btnp2 = new javax.swing.JButton(); btncon = new javax.swing.JButton(); btndesc = new javax.swing.JButton(); btnp3 = new javax.swing.JButton(); btnp4 = new javax.swing.JButton(); btnp5 = new javax.swing.JButton(); btnp9 = new javax.swing.JButton(); btnp6 = new javax.swing.JButton(); btnp7 = new javax.swing.JButton(); btnp8 = new javax.swing.JButton(); btn13 = new javax.swing.JButton(); btnp10 = new javax.swing.JButton(); btnp11 = new javax.swing.JButton(); btnp12 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnp2.setText("2"); btnp2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp2MouseClicked(evt); } }); btncon.setText("Conectar"); btncon.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnconMouseClicked(evt); } }); btndesc.setText("Desconectar"); btndesc.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btndescMouseClicked(evt); } }); btnp3.setText("3"); btnp3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp3MouseClicked(evt); } }); btnp4.setText("4"); btnp4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp4MouseClicked(evt); } }); btnp5.setText("5"); btnp5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp5MouseClicked(evt); } }); btnp9.setText("9"); btnp9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp9MouseClicked(evt); } }); btnp6.setText("6"); btnp6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp6MouseClicked(evt); } }); btnp7.setText("7"); btnp7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp7MouseClicked(evt); } }); btnp8.setText("8"); btnp8.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp8MouseClicked(evt); } }); btn13.setText("13"); btn13.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btn13MouseClicked(evt); } }); btnp10.setText("10"); btnp10.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp10MouseClicked(evt); } }); btnp11.setText("11"); btnp11.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp11MouseClicked(evt); } }); btnp12.setText("12"); btnp12.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp12MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(btncon) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btndesc)) .addGroup(layout.createSequentialGroup() .addComponent(btnp6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(btnp10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(btnp2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btncon) .addComponent(btndesc)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp2) .addComponent(btnp3) .addComponent(btnp4) .addComponent(btnp5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp6) .addComponent(btnp7) .addComponent(btnp8) .addComponent(btnp9)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp10) .addComponent(btnp11) .addComponent(btnp12) .addComponent(btn13)) .addGap(22, 22, 22)) ); pack(); }// </editor-fold> private void btnp2MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p2"); } private void btnconMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("connect"); } private void btndescMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("disconnect"); } private void btnp3MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p3"); } private void btnp4MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p4"); } private void btnp5MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here action("p5"); } private void btnp9MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p9"); } private void btnp6MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p6"); } private void btnp7MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p7"); } private void btnp8MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p8"); } private void btn13MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p13"); } private void btnp10MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p10"); } private void btnp11MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p11"); } private void btnp12MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p12"); } /** * @param args the command line arguments */ public static void main(String args[]) throws IOException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BDArduino().setVisible(true); } }); //} while (true) { // int sql8 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin8")); if (connected == true && sql8 != aux_sql8) { aux_sql8 = sql8; if(sql8 == 1){ writeData(2); }else{ writeData(3); } } int sql2 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin2")); if (connected == true && sql2 != aux_sql2) { aux_sql2 = sql2; if(sql2 == 1){ writeData(4); }else{ writeData(5); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } // Variables declaration - do not modify private javax.swing.JButton btn13; private javax.swing.JButton btncon; private javax.swing.JButton btndesc; private javax.swing.JButton btnp10; private javax.swing.JButton btnp11; private javax.swing.JButton btnp12; private javax.swing.JButton btnp2; private javax.swing.JButton btnp3; private javax.swing.JButton btnp4; private javax.swing.JButton btnp5; private javax.swing.JButton btnp6; private javax.swing.JButton btnp7; private javax.swing.JButton btnp8; private javax.swing.JButton btnp9; // End of variables declaration }

    Read the article

  • Passing data between android ListActivities in Java

    - by Will Janes
    I am new to Android! I am having a problem getting this code to work... Basically I Go from one list activity to another and pass the text from a list item through the intent of the activity to the new list view, then retrieve that text in the new list activity and then preform a http request based on value of that list item. Log Cat 04-05 17:47:32.370: E/AndroidRuntime(30135): FATAL EXCEPTION: main 04-05 17:47:32.370: E/AndroidRuntime(30135): java.lang.ClassCastException:android.widget.LinearLayout 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.thickcrustdesigns.ufood.CatogPage$1.onItemClick(CatogPage.java:66) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.ListView.performItemClick(ListView.java:3731) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1959) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Handler.handleCallback(Handler.java:587) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Handler.dispatchMessage(Handler.java:92) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Looper.loop(Looper.java:130) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.app.ActivityThread.main(ActivityThread.java:3691) 04-05 17:47:32.370: E/AndroidRuntime(30135): at java.lang.reflect.Method.invokeNative(Native Method) 04-05 17:47:32.370: E/AndroidRuntime(30135): at java.lang.reflect.Method.invoke(Method.java:507) 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 04-05 17:47:32.370: E/AndroidRuntime(30135): at dalvik.system.NativeStart.main(Native Method) ListActivity 1 package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class CatogPage extends ListActivity { ListView listView1; Button btn_bk; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.definition_main); btn_bk = (Button) findViewById(R.id.btn_bk); listView1 = (ListView) findViewById(android.R.id.list); ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "categories")); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view; String p = tv.getText().toString(); Intent i = new Intent(getApplicationContext(), Results.class); i.putExtra("category", p); startActivity(i); } }); btn_bk.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), UFoodAppActivity.class); startActivity(i); } }); } } **ListActivity 2** package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class Results extends ListActivity { ListView listView1; enum Category { Chicken, Beef, Chinese, Cocktails, Curry, Deserts, Fish, ForOne { public String toString() { return "For One"; } }, Lamb, LightBites { public String toString() { return "Light Bites"; } }, Pasta, Pork, Vegetarian } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.definition_main); listView1 = (ListView) findViewById(android.R.id.list); Bundle data = getIntent().getExtras(); String category = data.getString("category"); Category cat = Category.valueOf(category); String value = null; switch (cat) { case Chicken: value = "Chicken"; break; case Beef: value = "Beef"; break; case Chinese: value = "Chinese"; break; case Cocktails: value = "Cocktails"; break; case Curry: value = "Curry"; break; case Deserts: value = "Deserts"; break; case Fish: value = "Fish"; break; case ForOne: value = "ForOne"; break; case Lamb: value = "Lamb"; break; case LightBites: value = "LightBites"; break; case Pasta: value = "Pasta"; break; case Pork: value = "Pork"; break; case Vegetarian: value = "Vegetarian"; } ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "category")); nvp.add(new BasicNameValuePair("cat", value)); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); } } Request package com.thickcrustdesigns.ufood; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.content.Context; import android.util.Log; import android.widget.Toast; public class Request { @SuppressWarnings("null") public static ArrayList<JSONObject> fetchData(Context context, ArrayList<NameValuePair> nvp) { ArrayList<JSONObject> listItems = new ArrayList<JSONObject>(); InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://co350-11d.projects02.glos.ac.uk/php/database.php"); httppost.setEntity(new UrlEncodedFormEntity(nvp)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } // convert response to string String result = ""; try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); InputStream stream = null; StringBuilder sb = null; while ((result = reader.readLine()) != null) { sb.append(result + "\n"); } stream.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject jo = jArray.getJSONObject(i); listItems.add(jo); } } catch (Exception e) { Toast.makeText(context.getApplicationContext(), "None Found!", Toast.LENGTH_LONG).show(); } return listItems; } } Any help would be grateful! Many Thanks EDIT Sorry very tired so missed out my 2nd ListActivity package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class Results extends ListActivity { ListView listView1; enum Category { Chicken, Beef, Chinese, Cocktails, Curry, Deserts, Fish, ForOne { public String toString() { return "For One"; } }, Lamb, LightBites { public String toString() { return "Light Bites"; } }, Pasta, Pork, Vegetarian } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.definition_main); listView1 = (ListView) findViewById(android.R.id.list); Bundle data = getIntent().getExtras(); String category = data.getString("category"); Category cat = Category.valueOf(category); String value = null; switch (cat) { case Chicken: value = "Chicken"; break; case Beef: value = "Beef"; break; case Chinese: value = "Chinese"; break; case Cocktails: value = "Cocktails"; break; case Curry: value = "Curry"; break; case Deserts: value = "Deserts"; break; case Fish: value = "Fish"; break; case ForOne: value = "ForOne"; break; case Lamb: value = "Lamb"; break; case LightBites: value = "LightBites"; break; case Pasta: value = "Pasta"; break; case Pork: value = "Pork"; break; case Vegetarian: value = "Vegetarian"; } ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "category")); nvp.add(new BasicNameValuePair("cat", value)); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); } } Sorry again! Cheers guys!

    Read the article

  • Import Data from Excel sheet to DB Table through OAF page

    - by PRajkumar
    1. Create a New Workspace and Project File > New > General > Workspace Configured for Oracle Applications File Name – PrajkumarImportxlsDemo   Automatically a new OA Project will also be created   Project Name -- ImportxlsDemo Default Package -- prajkumar.oracle.apps.fnd.importxlsdemo   2. Add JAR file jxl-2.6.3.jar to Apache Library Download jxl-2.6.3.jar from following link – http://www.findjar.com/jar/net.sourceforge.jexcelapi/jars/jxl-2.6.jar.html   Steps to add jxl.jar file in Local Machine Right Click on ImportxlsDemo > Project Properties > Libraries > Add jar/Directory and browse to directory where jxl-2.6.3.jar has been downloaded and select the JAR file            Steps to add jxl.jar file at EBS middle tier On your EBS middile tier copy jxl.jar at $FND_TOP/java/3rdparty/standalone Add $FND_TOP/java/3rdparty/standalone\jxl.jar to custom classpath in Jser.properties file which is at $IAS_ORACLE_HOME/Apache/Jserv/etc wrapper.classpath=/U01/oracle/dev/devappl/fnd/11.5.0/java/3rdparty/stdalone/jxl.jar Bounce Apache Server   3. Create a New Application Module (AM) Right Click on ImportxlsDemo > New > ADF Business Components > Application Module Name -- ImportxlsAM Package -- prajkumar.oracle.apps.fnd.importxlsdemo.server   Check Application Module Class: ImportxlsAMImpl Generate JavaFile(s)   4. Create Test Table in which we will insert data from excel CREATE TABLE xx_import_excel_data_demo (    -- --------------------      -- Data Columns      -- --------------------      column1                 VARCHAR2(100),      column2                 VARCHAR2(100),      column3                 VARCHAR2(100),      column4                 VARCHAR2(100),      column5                 VARCHAR2(100),      -- --------------------      -- Who Columns      -- --------------------      last_update_date   DATE         NOT NULL,      last_updated_by    NUMBER   NOT NULL,      creation_date         DATE         NOT NULL,      created_by             NUMBER    NOT NULL,      last_update_login  NUMBER );   5. Create a New Entity Object (EO) Right click on ImportxlsDemo > New > ADF Business Components > Entity Object Name – ImportxlsEO Package -- prajkumar.oracle.apps.fnd.importxlsdemo.schema.server Database Objects -- XX_IMPORT_EXCEL_DATA_DEMO   Note – By default ROWID will be the primary key if we will not make any column to be primary key Check the Accessors, Create Method, Validation Method and Remove Method   6. Create a New View Object (VO) Right click on ImportxlsDemo > New > ADF Business Components > View Object Name -- ImportxlsVO Package -- prajkumar.oracle.apps.fnd.importxlsdemo.server   In Step2 in Entity Page select ImportxlsEO and shuttle it to selected list In Step3 in Attributes Window select all columns and shuttle them to selected list   In Java page Uncheck Generate Java file for View Object Class: ImportxlsVOImpl Select Generate Java File for View Row Class: ImportxlsVORowImpl -> Generate Java File -> Accessors   7. Add Your View Object to Root UI Application Module Right click on ImportxlsAM > Edit ImportxlsAM > Data Model > Select ImportxlsVO and shuttle to Data Model list   8. Create a New Page Right click on ImportxlsDemo > New > Web Tier > OA Components > Page Name -- ImportxlsPG Package -- prajkumar.oracle.apps.fnd.importxlsdemo.webui   9. Select the ImportxlsPG and go to the strcuture pane where a default region has been created   10. Select region1 and set the following properties:   Attribute Property ID PageLayoutRN AM Definition prajkumar.oracle.apps.fnd.importxlsdemo.server.ImportxlsAM Window Title Import Data From Excel through OAF Page Demo Window Title Import Data From Excel through OAF Page Demo   11. Create messageComponentLayout Region Under Page Layout Region Right click PageLayoutRN > New > Region   Attribute Property ID MainRN Item Style messageComponentLayout   12. Create a New Item messageFileUpload Bean under MainRN Right click on MainRN > New > messageFileUpload Set Following Properties for New Item --   Attribute Property ID MessageFileUpload Item Style messageFileUpload   13. Create a New Item Submit Button Bean under MainRN Right click on MainRN > New > messageLayout Set Following Properties for messageLayout --   Attribute Property ID ButtonLayout   Right Click on ButtonLayout > New > Item   Attribute Property ID Go Item Style submitButton Attribute Set /oracle/apps/fnd/attributesets/Buttons/Go   14. Create Controller for page ImportxlsPG Right Click on PageLayoutRN > Set New Controller Package Name: prajkumar.oracle.apps.fnd.importxlsdemo.webui Class Name: ImportxlsCO   Write Following Code in ImportxlsCO in processFormRequest import oracle.apps.fnd.framework.OAApplicationModule; import oracle.apps.fnd.framework.OAException; import java.io.Serializable; import oracle.apps.fnd.framework.webui.OAControllerImpl; import oracle.apps.fnd.framework.webui.OAPageContext; import oracle.apps.fnd.framework.webui.beans.OAWebBean; import oracle.cabo.ui.data.DataObject; import oracle.jbo.domain.BlobDomain; public void processFormRequest(OAPageContext pageContext, OAWebBean webBean) {  super.processFormRequest(pageContext, webBean);  if (pageContext.getParameter("Go") != null)  {   DataObject fileUploadData = (DataObject)pageContext.getNamedDataObject("MessageFileUpload");   String fileName = null;                 try   {    fileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");   }   catch(NullPointerException ex)   {    throw new OAException("Please Select a File to Upload", OAException.ERROR);   }   BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, fileName);   try   {    OAApplicationModule oaapplicationmodule = pageContext.getRootApplicationModule();    Serializable aserializable2[] = {uploadedByteStream};    Class aclass2[] = {BlobDomain.class };    oaapplicationmodule.invokeMethod("ReadExcel", aserializable2,aclass2);   }   catch (Exception ex)   {    throw new OAException(ex.toString(), OAException.ERROR);   }  } }     Write Following Code in ImportxlsAMImpl.java import java.io.IOException; import java.io.InputStream; import jxl.Cell; import jxl.CellType; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import oracle.apps.fnd.framework.server.OAApplicationModuleImpl; import oracle.jbo.Row; import oracle.apps.fnd.framework.OAViewObject; import oracle.apps.fnd.framework.server.OAViewObjectImpl; import oracle.jbo.domain.BlobDomain; public void createRecord(String[] excel_data) {   OAViewObject vo = (OAViewObject)getImportxlsVO1();            if (!vo.isPreparedForExecution())    {   vo.executeQuery();      }                      Row row = vo.createRow();  try  {   for (int i=0; i < excel_data.length; i++)   {    row.setAttribute("Column" +(i+1) ,excel_data[i]);   }  }  catch(Exception e)  {   System.out.println(e.getMessage());   }  vo.insertRow(row);  getTransaction().commit(); }      public void ReadExcel(BlobDomain fileData) throws IOException {  String[] excel_data  = new String[5];  InputStream inputWorkbook = fileData.getInputStream();  Workbook w;          try  {   w = Workbook.getWorkbook(inputWorkbook);                       // Get the first sheet   Sheet sheet = w.getSheet(0);                       for (int i = 0; i < sheet.getRows(); i++)   {    for (int j = 0; j < sheet.getColumns(); j++)    {     Cell cell = sheet.getCell(j, i);     CellType type = cell.getType();     if (cell.getType() == CellType.LABEL)     {      System.out.println("I got a label " + cell.getContents());      excel_data[j] = cell.getContents();     }     if (cell.getType() == CellType.NUMBER)     {        System.out.println("I got a number " + cell.getContents());      excel_data[j] = cell.getContents();     }    }    createRecord(excel_data);   }  }              catch (BiffException e)  {   e.printStackTrace();  } }   15. Congratulation you have successfully finished. Run Your page and Test Your Work   Consider Excel PRAJ_TEST.xls with following data --       Lets Try to import this data into DB Table --          

    Read the article

  • Nashorn in the Twitterverse, Continued

    - by jlaskey
    After doing the Twitter example, it seemed reasonable to try graphing the result with JavaFX.  At this time the Nashorn project doesn't have an JavaFX shell, so we have to go through some hoops to create an JavaFX application.  I thought showing you some of those hoops might give you some idea about what you can do mixing Nashorn and Java (we'll add a JavaFX shell to the todo list.) First, let's look at the meat of the application.  Here is the repackaged version of the original twitter example. var twitter4j      = Packages.twitter4j; var TwitterFactory = twitter4j.TwitterFactory; var Query          = twitter4j.Query; function getTrendingData() {     var twitter = new TwitterFactory().instance;     var query   = new Query("nashorn OR nashornjs");     query.since("2012-11-21");     query.count = 100;     var data = {};     do {         var result = twitter.search(query);         var tweets = result.tweets;         for each (tweet in tweets) {             var date = tweet.createdAt;             var key = (1900 + date.year) + "/" +                       (1 + date.month) + "/" +                       date.date;             data[key] = (data[key] || 0) + 1;         }     } while (query = result.nextQuery());     return data; } Instead of just printing out tweets, getTrendingData tallies "tweets per date" during the sample period (since "2012-11-21", the date "New Project: Nashorn" was posted.)   getTrendingData then returns the resulting tally object. Next, use JavaFX BarChart to display that data. var javafx         = Packages.javafx; var Stage          = javafx.stage.Stage var Scene          = javafx.scene.Scene; var Group          = javafx.scene.Group; var Chart          = javafx.scene.chart.Chart; var FXCollections  = javafx.collections.FXCollections; var ObservableList = javafx.collections.ObservableList; var CategoryAxis   = javafx.scene.chart.CategoryAxis; var NumberAxis     = javafx.scene.chart.NumberAxis; var BarChart       = javafx.scene.chart.BarChart; var XYChart        = javafx.scene.chart.XYChart; var Series         = XYChart.Series; var Data           = XYChart.Data; function graph(stage, data) {     var root = new Group();     stage.scene = new Scene(root);     var dates = Object.keys(data);     var xAxis = new CategoryAxis();     xAxis.categories = FXCollections.observableArrayList(dates);     var yAxis = new NumberAxis("Tweets", 0.0, 200.0, 50.0);     var series = FXCollections.observableArrayList();     for (var date in data) {         series.add(new Data(date, data[date]));     }     var tweets = new Series("Tweets", series);     var barChartData = FXCollections.observableArrayList(tweets);     var chart = new BarChart(xAxis, yAxis, barChartData, 25.0);     root.children.add(chart); } I should point out that there is a lot of subtlety going on in the background.  For example; stage.scene = new Scene(root) is equivalent to stage.setScene(new Scene(root)). If Nashorn can't find a property (scene), then it searches (via Dynalink) for the Java Beans equivalent (setScene.)  Also note, that Nashorn is magically handling the generic class FXCollections.  Finally,  with the call to observableArrayList(dates), Nashorn is automatically converting the JavaScript array dates to a Java collection.  It really is hard to identify which objects are JavaScript and which are Java.  Does it really matter? Okay, with the meat out of the way, let's talk about the hoops. When working with JavaFX, you start with a main subclass of javafx.application.Application.  This class handles the initialization of the JavaFX libraries and the event processing.  This is what I used for this example; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javafx.application.Application; import javafx.stage.Stage; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class TrendingMain extends Application { private static final ScriptEngineManager MANAGER = new ScriptEngineManager(); private final ScriptEngine engine = MANAGER.getEngineByName("nashorn"); private Trending trending; public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { trending = (Trending) load("Trending.js"); trending.start(stage); } @Override public void stop() throws Exception { trending.stop(); } private Object load(String script) throws IOException, ScriptException { try (final InputStream is = TrendingMain.class.getResourceAsStream(script)) { return engine.eval(new InputStreamReader(is, "utf-8")); } } } To initialize Nashorn, we use JSR-223's javax.script.  private static final ScriptEngineManager MANAGER = new ScriptEngineManager(); private final ScriptEngine engine = MANAGER.getEngineByName("nashorn"); This code sets up an instance of the Nashorn engine for evaluating scripts. The  load method reads a script into memory and then gets engine to eval that script.  Note, that load also returns the result of the eval. Now for the fun part.  There are several different approaches we could use to communicate between the Java main and the script.  In this example we'll use a Java interface.  The JavaFX main needs to do at least start and stop, so the following will suffice as an interface; public interface Trending {     public void start(Stage stage) throws Exception;     public void stop() throws Exception; } At the end of the example's script we add; (function newTrending() {     return new Packages.Trending() {         start: function(stage) {             var data = getTrendingData();             graph(stage, data);             stage.show();         },         stop: function() {         }     } })(); which instantiates a new subclass instance of Trending and overrides the start and stop methods.  The result of this function call is what is returned to main via the eval. trending = (Trending) load("Trending.js"); To recap, the script Trending.js contains functions getTrendingData, graph and newTrending, plus the call at the end to newTrending.  Back in the Java code, we cast the result of the eval (call to newTrending) to Trending, thus, we end up with an object that we can then use to call back into the script.  trending.start(stage); Voila. ?

    Read the article

  • Java Plist XML Parsing

    - by Jannis
    Hello everyone, I'm parsing a (not well formed) Apple Plist File with java. My Code looks like this: InputStream in = new FileInputStream( "foo" ); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader parser = factory.createXMLEventReader( in ); while (parser.hasNext()){ XMLEvent event = parser.nextEvent(); //code to navigate the nodes } The parts I"m parsing are looking like this: <dict> <key>foo</key><integer>123</integer> <key>bar</key><string>Boom &amp; Shroom</string> </dict> My problem is now, that nodes containing a ampersand are not parsed like they should because the ampersand is representing a entity. What can i do to get the value of the node as a complete String, instead of broken parts? Thank you in advance.

    Read the article

  • Spring JdbcTemplate - Insert blob and return generated key

    - by itsadok
    From the Spring JDBC documentation, I know how to insert a blob using JdbcTemplate final File blobIn = new File("spring2004.jpg"); final InputStream blobIs = new FileInputStream(blobIn); jdbcTemplate.execute( "INSERT INTO lob_table (id, a_blob) VALUES (?, ?)", new AbstractLobCreatingPreparedStatementCallback(lobhandler) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setLong(1, 1L); lobCreator.setBlobAsBinaryStream(ps, 2, blobIs, (int)blobIn.length()); } } ); blobIs.close(); And also how to retrieve the generated key of a newly inserted row: KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] {"id"}); ps.setString(1, name); return ps; } }, keyHolder); // keyHolder.getKey() now contains the generated key Is there a way I could combine the two?

    Read the article

  • OutOfMemoryError: bitmap size exceeds VM budget :- Android

    - by Shalini Singh
    Hi! i am downloading images from Url and displaying them,,, at the downloading time it is giving "out of memory error : bitmap size exceeds VM budget" i am using drawable ... code is giving bellow: HttpClient httpclient= new DefaultHttpClient(); HttpResponse response=(HttpResponse)httpclient.execute(httpRequest); HttpEntity entity= response.getEntity(); BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent(); Bitmap bm = BitmapFactory.decodeStream(instream);` Bitmap useThisBitmap = Bitmap.createScaledBitmap(bm,bm.getWidth(),bm.getHeight(), true); bm.recycle(); BitmapDrawable bt= new BitmapDrawable(useThisBitmap); System.gc(); Error: 05-28 14:55:47.251: ERROR/AndroidRuntime(4188): java.lang.OutOfMemoryError: bitmap size exceeds VM budget Please help me,,,,

    Read the article

  • sqllite and populating list view, android

    - by Rob Bushway
    I am populating a text and list view from a sqllite database. The data is populating from the cursor correctly (I see the list filling with text rows), but I'm not able to see the actual text in the rows - all I see are empty rows. For the life of me, I can't figure out what I'm not able to see the data in the text rows. My layouts: Tab layout: list layout: row layout: <?xml version="1.0" encoding="utf-8"?> / My topics activity package com.gotquestions.gqapp; import com.gotquestions.gqapp.R.layout; import android.R; import android.app.ListActivity; import android.database.Cursor; import android.database.SQLException; import android.os.Bundle; import android.widget.SimpleCursorAdapter; public class TopicsActivity extends ListActivity { private DataBaseHelper myDbHelper; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // DataBaseHelper myDbHelper = new DataBaseHelper(this); myDbHelper = new DataBaseHelper(this); //test try { myDbHelper.openDataBase(); }catch(SQLException sqle){ throw sqle; } setContentView(layout.list_layout); Cursor c = myDbHelper.fetchAllTopics(); startManagingCursor(c); String[] from = new String[] { DataBaseHelper.KEY_TITLE }; int[] to = new int[] { R.id.text1 }; // Now create an array adapter and set it to display using our row SimpleCursorAdapter notes = new SimpleCursorAdapter(this, layout.notes_row, c, from, to); setListAdapter(notes); myDbHelper.close(); } } My database helper: package com.gotquestions.gqapp; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DataBaseHelper extends SQLiteOpenHelper{ //The Android's default system path of your application database. private static String DB_PATH = "/data/data/com.gotquestions.gqapp/databases/"; private static String DB_NAME = "gotquestions_database.mp3"; public static final String KEY_TITLE = "topic_title"; public static final String KEY_ARTICLE_TITLE = "article_title"; public static final String KEY_ROWID = "_id"; private static final String TAG = null; private SQLiteDatabase myDataBase; // private final Context myContext; /** * Constructor * Takes and keeps a reference of the passed context in order to access to the application assets and resources. * @param context */ public DataBaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } /** * Creates a empty database on the system and rewrites it with your own database. * */ public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); if(dbExist){ //do nothing - database already exist }else{ //By calling this method and empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } /** * Check if the database already exist to avoid re-copying the file each time you open the application. * @return true if it exists, false if it doesn't */ private boolean checkDataBase(){ SQLiteDatabase checkDB = null; try{ String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); }catch(SQLiteException e){ //database does't exist yet. } if(checkDB != null){ checkDB.close(); } return checkDB != null ? true : false; } /** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. * */ private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { if(myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS titles"); onCreate(db); } public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = myDataBase.query(true, "topics", new String[] { KEY_ROWID, KEY_TITLE }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public Cursor fetchAllTopics() { return myDataBase.query("topics", new String[] {KEY_ROWID, KEY_TITLE}, null, null, null, null, null); }; public Cursor fetchAllFavorites() { return myDataBase.query("articles", new String[] { KEY_ROWID, KEY_ARTICLE_TITLE}, null, null, null, null, null); }; }

    Read the article

  • XML Reading org.xml.sax.SAXParseException: Expecting end of file.

    - by vivekbirdi
    Hi, I am getting problem while parsing XML File using JDE 4.6. FileConnection fconn = (FileConnection)Connector.open ("file:///SDCard/Dictionary.xml",Connector.READ_WRITE); InputStream din= fconn.openInputStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(din); here I am getting Exception at Document document = builder.parse(din); org.xml.sax.SAXParseException: Expecting end of file. please give me some solution. Thanks

    Read the article

  • Unable to use XSSF with Excel 2007

    - by Tarun
    Hello All, I am having tough time getting to read data from excel 2007. I am using XSSF to read data from a specific cell of excel but keep getting error - Exception in thread "main" java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setSaveAggressiveNamespaces()Lorg/apache/xmlbeans/XmlOptions; at org.apache.poi.POIXMLDocumentPart.(POIXMLDocumentPart.java:46) This is my piece of code - public static void main(String [] args) throws IOException { InputStream ins = new FileInputStream("C:\\Users\\Tarun3Kumar\\Desktop\\test.xlsx"); XSSFWorkbook xwb = new XSSFWorkbook(ins); XSSFSheet sheet = xwb.getSheetAt(0); Row row = sheet.getRow(1); Cell cell = row.getCell(0); System.out.println(cell.getStringCellValue()); System.out.println("a"); } I have following jars added to build path - poi-3.6 poi-ooxml-3.6 poi-ooxml-schemas-3.6 x-bean.jar I could only figure out that "setSaveAggressiveNamespaces" has replaced "setSaveAggresiveNamespaces"....

    Read the article

  • java.net.SocketException: Connection reset

    - by Darryl
    I am getting the following error trying to read from a socket. I'm doing a readInt() on that InputStream, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server. I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds? Many thanks, Darryl

    Read the article

  • Proper usage of JTidy to purify HTML

    - by Raj
    Hello, I am trying to use JTidy (jtidy-r938.jar) to sanitize an input HTML string, but I seem to have problems getting the default settings right. Often strings such as "hello world" end up as "helloworld" after tidying. I wanted to show what I'm doing here, and any pointers would be really appreciated: Assume that rawHtml is the String containing the input (real world) HTML. This is what I'm doing: InputStream is = new ByteArrayInputStream(rawHtml.getBytes("UTF-8")); Tidy tidy = new Tidy(); tidy.setQuiet(true); tidy.setShowWarnings(false); tidy.setXHTML(true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); tidy.parseDOM(is, baos); String pure = baos.toString(); First off, does anything look fundamentally wrong with the above code? I seem to be getting weird results with this. Thanks in advance!

    Read the article

  • Getting document.xml from a docx file using ZipInputStream

    - by meenakshik
    Hello, I have a inputStream of a docx file and I need to get hold of the document.xml which lies inside the docx. I am using ZipInputStream to read my stream and my code is something like ZipInputStream docXFile = new ZipInputStream(fileName); ZipEntry zipEntry; while ((zipEntry = docXFile.getNextEntry()) != null) { if(zipEntry.getName().equals("word/document.xml")) { System.out.println(" --> zip Entry is "+zipEntry.getName()); } } As you can see The output for zipEntry.getName comes as "word/document.xml" at some point. I need to pass this document.xml as a stream and unlike the ZipFile method where you can easily pass this on calling .getInputStream, I am wondering how can I do this docXFile? Thanks in advance, Meenakshi

    Read the article

  • [ASP.NET] Odd HttpRequest behaviour

    - by barguast
    I have a web service which runs with a HttpHandler class. In this class, I inspect the request stream for form / query string parameters. In some circumstances, it seemed as though these parameters weren't getting through. After a bit of digging around, I came across some behaviour I don't quite understand. See below: // The request contains 'a=1&b=2&c=3' // TEST ONLY: Read the entire request string contents; using (StreamReader sr = new StreamReader(context.Request.InputStream)) { contents = sr.ReadToEnd(); } // Here 'contents' is usually correct - containing 'a=1&b=2&c=3'. Sometimes it is empty. string a = context.Request["a"]; // Here, a = null, regardless of whether the 'contents' variable above is correct Can anyone explain to me why this might be happening? I'm using a .NET WebClient and UploadDataAsync to perform the request on the client if that makes any difference. If you need any more information, please let me know.

    Read the article

  • problem with my texture coordinates on a square.

    - by Evan Kimia
    Im very new to OpenGL ES, and have been doing a tutorial to build a square. The square is made, and now im trying to map a 256 by 256 image onto it. The problem is, im only seeing a very zoomed in portion of this bitmap; Im fairly certain my texture coords are whats wrong here. Thanks! package se.jayway.opengl.tutorial; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils; public class Square { // Our vertices. private float vertices[] = { -1.0f, 1.0f, 0.0f, // 0, Top Left -1.0f, -1.0f, 0.0f, // 1, Bottom Left 1.0f, -1.0f, 0.0f, // 2, Bottom Right 1.0f, 1.0f, 0.0f, // 3, Top Right }; //Our texture. private float texture[] = { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; // The order we like to connect them. private short[] indices = { 0, 1, 2, 0, 2, 3 }; // Our vertex buffer. private FloatBuffer vertexBuffer; // Our index buffer. private ShortBuffer indexBuffer; //texture buffer. private FloatBuffer textureBuffer; //Our texture pointer. private int[] textures = new int[1]; public Square() { // a float is 4 bytes, therefore we multiply the number if // vertices with 4. ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); vertexBuffer = vbb.asFloatBuffer(); vertexBuffer.put(vertices); vertexBuffer.position(0); // a float is 4 bytes, therefore we multiply the number of // vertices with 4. ByteBuffer tbb = ByteBuffer.allocateDirect(texture.length * 4); vbb.order(ByteOrder.nativeOrder()); textureBuffer = tbb.asFloatBuffer(); textureBuffer.put(texture); textureBuffer.position(0); // short is 2 bytes, therefore we multiply the number if // vertices with 2. ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2); ibb.order(ByteOrder.nativeOrder()); indexBuffer = ibb.asShortBuffer(); indexBuffer.put(indices); indexBuffer.position(0); } /** * This function draws our square on screen. * @param gl */ public void draw(GL10 gl) { // Counter-clockwise winding. gl.glFrontFace(GL10.GL_CCW); // Enable face culling. gl.glEnable(GL10.GL_CULL_FACE); // What faces to remove with the face culling. gl.glCullFace(GL10.GL_BACK); //Bind our only previously generated texture in this case gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); // Enabled the vertices buffer for writing and to be used during // rendering. gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //Enable texture buffer array gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Specifies the location and data format of an array of vertex // coordinates to use when rendering. gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer); gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer); // Disable the vertices buffer. gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); //Disable the texture buffer. gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable face culling. gl.glDisable(GL10.GL_CULL_FACE); } /** * Load the textures * * @param gl - The GL Context * @param context - The Activity context */ public void loadGLTexture(GL10 gl, Context context) { //Get the texture from the Android resource directory InputStream is = context.getResources().openRawResource(R.drawable.test); Bitmap bitmap = null; try { //BitmapFactory is an Android graphics utility for images bitmap = BitmapFactory.decodeStream(is); } finally { //Always clear and close try { is.close(); is = null; } catch (IOException e) { } } //Generate one texture pointer... gl.glGenTextures(1, textures, 0); //...and bind it to our array gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //Create Nearest Filtered Texture gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); //Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); //Use the Android GLUtils to specify a two-dimensional texture image from our bitmap GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Clean up bitmap.recycle(); } }

    Read the article

  • Method may fail to close stream on exception

    - by 01
    I get the critical error with finbugs The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed. try { ... stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); ... } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (stdInput != null) { stdInput.close(); } if (stdError != null) { stdError.close(); } } catch (IOException e) { throw new RuntimeException(e); } } do i need to close also InputStreamReader or p.getErrorStream(it returns InputStream) ??

    Read the article

  • How can I get the error/warning messages out of the parsed HTML using JTidy?

    - by chetu
    I am able to parse the HTML but I want to extract the warning messages from the parsed HTML and show them to the user. Here is my code: Tidy tidy = new Tidy(); StringBuffer StringBuffer1 = new StringBuffer("<b>Hello<u><b>I am tsting another one.....<i>another....."); InputStream in = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-8")); Writer stringWriter = new StringWriter(); tidy.setPrintBodyOnly(true); tidy.setQuiet(true); tidy.setShowWarnings(true); tidy.setTidyMark(false); tidy.setXHTML(true); tidy.setXmlTags(false); Node parsedNode = tidy.parse(in, stringWriter); System.out.print(stringWriter.toString());

    Read the article

  • Is url.openStream harmful?

    - by Casebash
    I was using the java.net.URL.openStream() method to retrieve content from the server. I recently ran into an issue where the HTTP Response code indicated an error, but instead of throwing an exception, the stream still was read anyway. This caused the error to appear much later in the execution and proved to be a red herring. As far as I can see, when you have opened a stream using this method, there is no way to check the HTTP response code. The only way I could find to handle this properly was to use code such as: HttpURLConnection conn=(HttpURLConnection) url.openConnection() if(conn.getResponseCode()!=HttpStatus.SC_OK) //Raise Exception; InputStream in=conn.getInputStream() So do you agree? Is it possible to use openStream safely, or is it a method that should be avoided at all costs. It is worth noting that Sun uses the method in their tutorial code for reading directly from a URL. Then again, the code throws Exception so it isn't exactly a bastion of good coding practices.

    Read the article

  • Struts and logging HTTP POST request body

    - by Ivan Vrtaric
    I'm trying to log the raw body of HTTP POST requests in our application based on Struts, running on Tomcat 6. I've found one previous post on SO that was somewhat helpful, but the accepted solution doesn't work properly in my case. The problem is, I want to log the POST body only in certain cases, and let Struts parse the parameters from the body after logging. Currently, in the Filter I wrote I can read and log the body from the HttpServletRequestWrapper object, but after that Struts can't find any parameters to parse, so the DispatchAction call (which depends on one of the parameters from the request) fails. I did some digging through Struts and Tomcat source code, and found that it doesn't matter if I store the POST body into a byte array, and expose a Stream and a Reader based on that array; when the parameters need to get parsed, Tomcat's Request object accesses its internal InputStream, which has already been read by that time. Does anyone have an idea how to implement this kind of logging correctly?

    Read the article

  • Problem while reading the File in a eclipse Plugin application

    - by Abhishek Choudhary
    I 've developed an eclipse plugin and in that I have a java file trying to read directories and then populate result accordingly. When I try to run the file from eclipse itself through RunJava application , it gives me proper result but as soon as I try to run the same through Eclipse Application, it is throwing NullPointerException because unable to find the directory. I tried the following ways- Suppose , I have a package as - Package - com.test.abhishek.file.java.TestWork.java Directories - com.test.abhishek.file.java.Dir1 com.test.abhishek.file.java.Dir2 Now in TestWork.java- InputStream is = LGHelpContentView.class.getResourceAsStream("/"+dirName);** The above line is getting failed. How should I keep my directory and where so that it will run as an eclipse plug-in as well.

    Read the article

  • URL encoding for latin characters in Java

    - by sammichy
    I'm trying to read in an image URL. As mentioned in the java documentation, I tried converting the URL to URI by String imageURL = "http://www.shefinds.com/files/Christian-Louboutin-Décolleté-100-pumps.jpg"; URL url = new URL(imageURL); url = new URI(url.getProtocol(), url.getHost(), url.getFile(), null).toURL(); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); I get the following error when the code is executed http://www.shefinds.com/files/Christian-Louboutin-Décolleté-100-pumps.jpg What am I doing wrong and what is the right way to encode this URL?

    Read the article

  • problem in loading images from web

    - by Lynnooi
    hi, I am new in android and had developed an app which get images from the website and display it. I got it working in emulator but not in real phones. In some device, it will crash or take very long loading period. Can anyone please help me or guide me in improving it as i'm not sure whether the way i loads the images is correct or not. Here are the code i use to get the images from the web and display accordingly. if (xmlURL.length() != 0) { try { URL url = new URL(xmlURL); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); /* Get the XMLReader of the SAXParser we created. */ XMLReader xr = sp.getXMLReader(); /* * Create a new ContentHandler and apply it to the * XML-Reader */ xr.setContentHandler(myExampleHandler); /* Parse the xml-data from our URL. */ xr.parse(new InputSource(url.openStream())); /* Parsing has finished. */ /* * Our ExampleHandler now provides the parsed data to * us. */ ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData(); } catch (Exception e) { } } if (s.equalsIgnoreCase("wallpapers")) { Context context = helloAndroid.this.getBaseContext(); for (int j = 0; j <= myExampleHandler.filenames.size() - 1; j++) { if (myExampleHandler.filenames.elementAt(j).toString() != null) { helloAndroid.this.ed = myExampleHandler.thumbs.elementAt(j) .toString(); if (helloAndroid.this.ed.length() != 0) { Drawable image = ImageOperations(context, helloAndroid.this.ed, "image.jpg"); file_info = myExampleHandler.filenames .elementAt(j).toString(); author = "\nby " + myExampleHandler.authors.elementAt(j) .toString(); switch (j + 1) { case 1: ImageView imgView1 = new ImageView(context); imgView1 = (ImageView) findViewById(R.id.image1); if (image.getIntrinsicHeight() > 0) { imgView1.setImageDrawable(image); } else imgView1 .setImageResource(R.drawable.empty_wallpaper); tv = (TextView) findViewById(R.id.filename1); tv.setText(file_info); tv = (TextView) findViewById(R.id.author1); tv.setText(author); imgView1 .setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Perform action on click Intent myIntent1 = new Intent( helloAndroid.this, galleryFile.class); Bundle b = new Bundle(); b.putString("fileID",myExampleHandler.fileid.elementAt(0).toString()); b.putString("page", "1"); b.putString("family", s); b.putString("fi",myExampleHandler.folder_id.elementAt(folder).toString()); b.putString("kw", keyword); myIntent1.putExtras(b); startActivityForResult( myIntent1, 0); } }); break; case 2: ImageView imgView2 = new ImageView(context); imgView2 = (ImageView) findViewById(R.id.image2); imgView2.setImageDrawable(image); tv = (TextView) findViewById(R.id.filename2); tv.setText(file_info); tv = (TextView) findViewById(R.id.author2); tv.setText(author); imgView2 .setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Perform action on click Intent myIntent1 = new Intent( helloAndroid.this, galleryFile.class); Bundle b = new Bundle(); b.putString("fileID",myExampleHandler.fileid.elementAt(1).toString()); b.putString("page", "1"); b.putString("family", s); b.putString("fi",myExampleHandler.folder_id.elementAt(folder).toString()); b.putString("kw", keyword); myIntent1.putExtras(b); startActivityForResult( myIntent1, 0); } }); break; case 3: //same code break; } } } } } private Drawable ImageOperations(Context ctx, String url, String saveFilename) { try { InputStream is = (InputStream) this.fetch(url); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } public Object fetch(String address) throws MalformedURLException, IOException { URL url = new URL(address); Object content = url.getContent(); return content; }

    Read the article

  • how to show attached files on a TMS WebGrid ???

    - by ahmed
    hi, i have a TMS WebGrid , I would like to attach some files ad show them on a Tms WebGrid. How can I do that in vb.net ? For now I am simply attaching like this on a attach file button ?? If Len(FileUpload1.PostedFile.FileName) > 5 Then length = FileUpload1.PostedFile.InputStream.Length() My_Img_Path = "Attachments/" k_upload_dir = "~/Attachments/" virtualPath = k_upload_dir + my_img_srno.ToString + Path.GetFileName(FileUpload1.PostedFile.FileName) My_Img_Path = My_Img_Path + my_img_srno.ToString + Path.GetFileName(FileUpload1.PostedFile.FileName) phyiscalPath = Server.MapPath(virtualPath) FileUpload1.PostedFile.SaveAs(phyiscalPath) my_html_code = "" lbl_AttahcmnetStatus.Text = "Sucessfully file attached..." end if

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >