I am getting an cannot resolve method error when i do this:
DataOutputStream os = newDataOutputStream(client.getOutputStream());
My imports:
import android.os.Bundle;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Code for class
#SuppressWarnings("deprecation")
class sentMessage implements Runnable {
public void run() {
try {
Socket client = serverSocket.accept();
DataOutputStream os = newDataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
msg = msg + "\n Server : " + str;
handler.post(new Runnable() {
public void run() {
chat.setText(msg);
}
});
os.writeBytes(str);
os.flush();
os.close();
client.close();
} catch (IOException e) {
}
}
}
You're missing a space.
DataOutputStream os = new DataOutputStream(client.getOutputStream());
^
Related
I am attempting to play audio for a program and I need the AudioStream class and the AudioPlayer class, but when I attempt to import them Eclipse gives me an error.
Method where used:
public static void playMusic(String filepath) {
InputStream music;
try {
music = new FileInputStream(new File(filepath));
AudioStream audio = new AudioStream(music);
AudioPlayer.player.start(audio);
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
}
Imports:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
i have a little problem with my code, meaning that hyperlink not showing under JLabel. I tried to resolve that problem by creating JLabel in different class and run the method in main class, but when i do that, it returning me only white square instead of label. no errors while compiling.
Main class:
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Desktop;
import java.awt.event.ActionListener;
import java.net.URI;
public class Main extends JFrame
{
static JLabel appicationStatute;
public Main() throws Exception
{
super();
registerWindowFrame = new JFrame("name");
registerWindowFrame.setSize(500,750);
registerWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
registerWindowFrame.setLayout(null);
registerWindowFrame.getContentPane().setBackground(Color.RED);
Statute status = new Statute();
status.setSize(status.getPreferredSize());
status.setLocation(10,450);
registerWindowFrame.getContentPane().add(status);
registerWindowFrame.setVisible(true);
}
public static void main (String [] args) throws Exception
{
new Main();
}
}
Statue class
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.*;
public class Statute extends JPanel {
private String text = "application statute";
private JLabel hyperlink = new JLabel(text);
public Statute() throws HeadlessException {
super();
hyperlink.setForeground(Color.BLUE.darker());
hyperlink.setCursor(new Cursor(Cursor.HAND_CURSOR));
hyperlink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI("http://www.codejava.net"));
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
public void mouseExited(MouseEvent e) {
hyperlink.setText(text);
}
#Override
public void mouseEntered(MouseEvent e) {
hyperlink.setText("<html><a href=''>" + text + "</a></html>");
}
});
}
}
I am using this code for read the pdf file from shared folder, but i cannot read the file
package com.example.kuldeep.myapplication;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.playlog.internal.LogEvent;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileFilter;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import static com.example.kuldeep.myapplication.R.id.textView1;
import static com.example.kuldeep.myapplication.R.layout.activity_main14;
import static org.apache.commons.io.comparator.LastModifiedFileComparator.*;
public class Main14Activity extends AppCompatActivity {
private static final String TAG = "Main14Activity";
TextView textView, textiew1;
String CustomerNameRegex = "Customer Name: [a-zA-Z\\s]*",
MobileNumberRegex = "PH:\\s[0-9]*",
JobCardNoRegex = "Jobcard No :\\sJC-[a-zA-Z0-9\\S]*\n[a-zA-Z0-9\\S]*",
ServiceTypeRegex = "Service Type:([a-zA-Z0-9\\s\\S])*GSTIN",
RegistrationNumberRegex = "Reg. No.:\\s[a-zA-Z0-9\\S]*";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main14);
/*listView=(ListView)findViewById(R.id.list);*/
textView = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.text1);
jcifs.Config.setProperty("jcifs.netbios.wins", "192.168.1.12");
Thread th = new Thread(new Runnable() {
#Override
public void run() {
SmbFile choice = null;
try {
String yourPeerName = "kuldeep";
String yourPeerPassword = "123";
String yourPeerIP = "192.168.1.12";
final String path = "smb://" + yourPeerIP + "/Scan/";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, yourPeerName, yourPeerPassword);
Log.e("Connected", "Yes");
SmbFile file = new SmbFile(path, auth);
SmbFile[] mFile = file.listFiles();
if (mFile == null || mFile.length == 0) {
return;
}
SmbFile lastmode = mFile[0];
for (int i = 1; i < mFile.length; i++) {
if (lastmode.lastModified() < mFile[i].lastModified()) {
lastmode = mFile[i];
}
}
Log.v(TAG, "File" + lastmode);
String s = String.valueOf(lastmode);
Log.v(TAG, "File" + s);
Log.v(TAG, "File" + lastmode.getInputStream().read());
Log.v(TAG, "File" + lastmode.getName());
final String dat = lastmode.getName().toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(dat);
try {
String parsedText = "";
PdfReader reader = new PdfReader(path + dat);
Log.v(TAG, "File" + reader);
int n = reader.getNumberOfPages();
for (int i = 0; i < n; i++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, i + 1).trim() + "\n"; //Extracting the content from the different pages
}
Log.v(TAG, "File" + parsedText);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}
you declare same textview both
textView=(TextView)findViewById(R.id.text);
textiew1=(TextView)findViewById(R.id.text1);
I'm creating an application which I have to send multiple images one after another and I use Object(Output/Input)Stream inside of a while loop. But It only send one file I guess its the first image. Can I send multiple files with Object(Output/Input)Stream? If so, What's the issue with my code?
Server : (Sends Screenshots from PC )
package application;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ScreenCapture {
Socket socket;
ObjectOutputStream os;
Robot robot;
PrintStream ps;
public ScreenCapture() throws IOException, AWTException {
// TODO Auto-generated constructor stub
socket = SocketWrapper.getSocket();
os = new ObjectOutputStream(socket.getOutputStream());
robot = new Robot();
ps = new PrintStream(socket.getOutputStream());
new Record().start();
}
private class Record extends Thread{
#Override
public void run() {
while(true){
getScreenShot();
FileInputStream fis;
try {
File f = new File("/Users/Tomahawk/Documents/send.jpg");
fis = new FileInputStream(f);
byte[] byteArray = new byte[fis.available()];
fis.read(byteArray);
os.writeObject(byteArray);
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Sent File");
}
}
}
public void getScreenShot(){
Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage img = robot.createScreenCapture(rect);
try {
ImageIO.write(img, "jpg", new File("/Users/Tomahawk/Documents/send.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client : (Receives Screenshots and save It on the phone)
package com.pcontrol.tomahawk.pcontrol;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ScreenCapture extends Activity {
Socket socket;
ObjectInputStream is;
OutputStream os;
Scanner scanner;
ImageView screenCap;
int filesize = 0;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_capture);
socket = SocketWrapper.getSocket();
screenCap = (ImageView) findViewById(R.id.screenCap);
new ReceiveFiles().execute();
}
private class ReceiveFiles extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
while(true) {
try {
is = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
os = new FileOutputStream("/sdcard/"+i+".jpg");
byte[] sentArray = (byte[]) is.readObject();
os.write(sentArray);
os.flush();
publishProgress();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onProgressUpdate(Void... values) {
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/"+i+".jpg");
screenCap.setImageBitmap(bmp);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_screen_capture, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
That endless loop is not so endless -- in fact, it will not even loop once.
You have a "return null" at the end of your "while(true)" block. After the first iteration, your method will return.
I am at this with ages and the problem i am having is simple i am not able to print out the data from the server to client everything else is working just that when the server sends a message to the client the phone it never gets or prints it out any insight or help would be great and i am getting no errors
client
package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
new Incomingdata().execute();
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{ System.out.println("Test123");
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
System.out.println("Test1234");
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
System.out.println("Test1235");
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Server
package handy_server.simple_gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//imports for server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Pandaboy
*/
class ServerGUI extends JFrame implements ActionListener
{
private Socket connection;
private InetAddress ip;
private JTextField t1 = new JTextField(null);
private JTextField t2 = new JTextField(null);
private JTextField t3 = new JTextField(null);
private JButton b2 = new JButton("Send");
private JButton b1 = new JButton("Working");
private JPanel p1 = new JPanel();
private ServerSocket listeningSocket;
private int port= 0;
private ArrayList<Contact> myContacts = new ArrayList<Contact>();
//-------------------------serverGui------------------------------------------------------------
public ServerGUI(int port){
this.port = port;
init();
}
public void init()
{
Container content = getContentPane();
content.setLayout(new FlowLayout());
Font f = new Font("TimesRoman", Font.BOLD, 20);
p1.setLayout(new GridLayout(2, 2));
content.add(p1);
p1.add(t1);
p1.add(b1);
p1.add(t2);
p1.add(t3);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(210, 300);
setVisible(true);
System.out.println("Just about to start the server...");
startServer();
}
public void actionPerformed(ActionEvent e)
{
Object target = e.getSource();
if (target == b1)
{
t1.setText("Button working");
MyHelpers.buildConversations(this, myContacts);
}
if(target == b2)
{
t1.setText("button working2");
String number = t2.getText();
int phone_length = number.length();
if (phone_length <= 20)
{
for(int a=1; a <=(20 - phone_length); a++ )
{
number += " ";
}
}
String msg = t3.getText();
String text = "7"+number+msg;
System.out.print(""+text);
OutputStream o = null;
try
{
o = connection.getOutputStream();
}
catch (IOException ex)
{
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------startServer------------------------------------------------------------
private void startServer()
{
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground()
{
System.out.println("in startserver...");
try
{
listeningSocket = new ServerSocket(port);
try
{
ip = InetAddress.getLocalHost();
System.out.println("Please enter this in your phone " + ip.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
while (true)
{
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
InputStream in = connection.getInputStream();
Scanner r = new Scanner(in);
OutputStream o = connection.getOutputStream();
PrintWriter p = new PrintWriter(o);
String message = r.nextLine();
System.out.println("" + message);
t1.setText(message);
// get the message type
// 0 sms 1 contact 2 incoming call
System.out.println(message);
if(message.startsWith("0"))
{
System.out.println(message);
String type = message.substring(1,2);
int theType = Integer.parseInt( type );
String number = message.substring(7, 21).trim();
String theText = message.substring(21);
String theName = MyHelpers.getName(number, myContacts);
System.out.println("Number = "+number);
System.out.println("Sender = "+theName);
System.out.println("Text = "+theText);
Contact cRef = MyHelpers.getContactReference(number, myContacts);
if (cRef != null)
{
cRef.addsms(theType, theName, theText);
}
}
if(message.startsWith("1"))
{
System.out.println(message);
String name = message.substring(1, 31).trim();
String pnumber = message.substring(31, 51).trim();
String email = message.substring(51, 91).trim();
myContacts.add(new Contact(name, pnumber, email));
System.out.println( name + pnumber + email);
}
if(message.startsWith("2"))
{
String unkown = message.substring(0, 1).trim();
String number = message.substring(1, 14).trim();
String theName = MyHelpers.getName(number, myContacts);
System.out.println(""+unkown+""+theName+" Is calling you");
}
if(message.startsWith("5"))
{
System.exit(0);
}
Any Help would be great i am stumped by this
In your server append '\n' to the end of the response so change this
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
to this:
PrintWriter p = new PrintWriter(o);
p.println(text + "\n");
p.flush();
System.out.print("text sent"+text);
i think the reason it hangs is because readLine() is looking for '\n' and it never recieves it
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}