Android Studio, thread in a java public class - java

I created a class Students, that invokes a thread which needs to fill a linked list with students.
class Students{
private LinkedList<Student> students = new LinkedList<Student>();
android.os.Handler handler = new android.os.Handler();
public String Fill() throws MalformedURLException {
String msg = "++";
new Thread(){
public void run(){
HttpURLConnection htcon=null;
try {
URL my_url = new URL("http://www.whatever.net/fill.php");
htcon = (HttpURLConnection) my_url.openConnection();
htcon.setDoOutput(true);
htcon.setUseCaches(false);
htcon.connect();
int responseCode = htcon.getResponseCode();
if(responseCode ==HttpURLConnection.HTTP_OK){
InputStream stream = htcon.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
String line = "";
StringBuilder strbld = new StringBuilder();
while ((line = bfr.readLine()) != null) {
strbld.append(line);
}
if (bfr!=null)
{
bfr.close();
}
String[] ary = strbld.toString().split("\n");
for (int i = 0; i < ary.length; i++) {
final Student temp = new Student(ary[i].toString().split(":")[0], "1210",Integer.parseInt(ary[i].toString().split(":")[1]), 0);
handler.post(new Runnable() {
#Override
public void run() {
students.push(new Student("jjj","k",9,9));
}
});
}//for
if (htcon!=null)
htcon.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
}.start();
return toBinaryString(students.size());
}
problem is, when handler runs, it doesn't change the list. size is still 0
here is how my UI class looks like(main activity)
TextView txtv = (TextView) findViewById(R.id.textv);
Students students1 = new Students();
try {
msg = students1.Fill();
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
}

Your thread is running asynchronously. So, it will immediately execute:
return toBinaryString(students.size());
while the thread is still on the progress. AsyncTask is really enough for your problem. Hope it helps.

Related

Device Dicovery file of ONVIF library in android studio

I find out a library of JavaWsDiscovery-0.2.jar. It is find out the ONVIF camera on same network, when I simply run the jar file in android studio, it runs successfully.
But when I want to use it in our project, it does not run just because of Private method.
In this library two methods are private those are not accessible to another class.
When i editing in jar file. so, it shows the compilation Error.
So, I need help in this regard, thank you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
ListView values;
List<String> value;
String[] args;
public static int WS_DISCOVERY_TIMEOUT = 4000;
public static int WS_DISCOVERY_PORT = 3702;
public static String WS_DISCOVERY_ADDRESS_IPv4 = "239.255.255.250";
public static String WS_DISCOVERY_ADDRESS_IPv6 = "[FF02::C]";
public static String WS_DISCOVERY_PROBE_MESSAGE = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:tns=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\"><soap:Header><wsa:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsa:Action><wsa:MessageID>urn:uuid:c032cfdd-c3ca-49dc-820e-ee6696ad63e2</wsa:MessageID><wsa:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To></soap:Header><soap:Body><tns:Probe/></soap:Body></soap:Envelope>";
private static final Random random = new SecureRandom();
String filepath = "/mnt/sdcard/Android/data/com.onvif.camera/com.onvif.javaWsDiscovery-0.2.jar";
static DeviceDiscovery deviceDiscovery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceDiscovery = new DeviceDiscovery();
btn = (Button) findViewById(R.id.button);
values = (ListView) findViewById(R.id.values);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
main(args);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws InterruptedException {
Iterator i$ = discoverWsDevicesAsUrls().iterator();
while(i$.hasNext()) {
URL url = (URL)i$.next();
System.out.println("Device discovered: " + url.toString());
}
}
public static Collection<URL> discoverWsDevicesAsUrls() {
return discoverWsDevicesAsUrls("", "");
}
public static Collection<URL> discoverWsDevicesAsUrls(String regexpProtocol, String regexpPath) {
TreeSet urls = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
});
Iterator i$ = discoverWsDevices().iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
try {
URL e = new URL(key);
boolean ok = true;
if(regexpProtocol.length() > 0 && !e.getProtocol().matches(regexpProtocol)) {
ok = false;
}
if(regexpPath.length() > 0 && !e.getPath().matches(regexpPath)) {
ok = false;
}
if(ok) {
urls.add(e);
}
} catch (MalformedURLException var7) {
var7.printStackTrace();
}
}
return urls;
}
public static Collection<String> discoverWsDevices() {
final ConcurrentSkipListSet addresses = new ConcurrentSkipListSet();
final CountDownLatch serverStarted = new CountDownLatch(1);
final CountDownLatch serverFinished = new CountDownLatch(1);
ArrayList addressList = new ArrayList();
try {
Enumeration executorService = NetworkInterface.getNetworkInterfaces();
if(executorService != null) {
label45:
while(true) {
NetworkInterface ignored;
do {
if(!executorService.hasMoreElements()) {
break label45;
}
ignored = (NetworkInterface)executorService.nextElement();
} while(ignored.isLoopback());
List address = ignored.getInterfaceAddresses();
Iterator runnable = address.iterator();
while(runnable.hasNext()) {
InterfaceAddress address1 = (InterfaceAddress)runnable.next();
addressList.add(address1.getAddress());
}
}
}
} catch (SocketException var10) {
var10.printStackTrace();
}
ExecutorService executorService1 = Executors.newCachedThreadPool();
Iterator ignored1 = addressList.iterator();
while(ignored1.hasNext()) {
final InetAddress address2 = (InetAddress)ignored1.next();
Runnable runnable1 = new Runnable() {
public void run() {
try {
String e = UUID.randomUUID().toString();
String probe = WS_DISCOVERY_PROBE_MESSAGE.replaceAll("<wsa:MessageID>urn:uuid:.*</wsa:MessageID>", "<wsa:MessageID>urn:uuid:" + e + "</wsa:MessageID>");
int port = random.nextInt(20000) + '鱀';
final DatagramSocket server = new DatagramSocket(port, address2);
(new Thread() {
public void run() {
try {
DatagramPacket e = new DatagramPacket(new byte[4096], 4096);
server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
long timerStarted = System.currentTimeMillis();
while(System.currentTimeMillis() - timerStarted < (long)WS_DISCOVERY_TIMEOUT) {
serverStarted.countDown();
server.receive(e);
Collection collection = deviceDiscovery.parseSoapResponseForUrls(Arrays.copyOf(e.getData(), e.getLength()));
Iterator i$ = collection.iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
addresses.add(key);
}
}
} catch (SocketTimeoutException var11) {
;
} catch (Exception var12) {
var12.printStackTrace();
} finally {
serverFinished.countDown();
server.close();
}
}
}).start();
try {
serverStarted.await(1000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException var7) {
var7.printStackTrace();
}
if(address2 instanceof Inet4Address) {
server.send(new DatagramPacket(probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4), WS_DISCOVERY_PORT));
} else {
server.send(new DatagramPacket(probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6), WS_DISCOVERY_PORT));
}
} catch (Exception var8) {
var8.printStackTrace();
}
try {
serverFinished.await((long)WS_DISCOVERY_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException var6) {
var6.printStackTrace();
}
}
};
executorService1.submit(runnable1);
}
try {
executorService1.shutdown();
executorService1.awaitTermination((long)(WS_DISCOVERY_TIMEOUT + 2000), TimeUnit.MILLISECONDS);
} catch (InterruptedException var9) {
;
}
return addresses;
}
}
DeviceDiscovery.class
private static Collection<Node> getNodeMatching(Node body, String regexp) {
ArrayList nodes = new ArrayList();
if(body.getNodeName().matches(regexp)) {
nodes.add(body);
}
if(body.getChildNodes().getLength() == 0) {
return nodes;
} else {
NodeList returnList = body.getChildNodes();
for(int k = 0; k < returnList.getLength(); ++k) {
Node node = returnList.item(k);
nodes.addAll(getNodeMatching(node, regexp));
}
return nodes;
}
}
private static Collection<String> parseSoapResponseForUrls(byte[] data) throws SOAPException, IOException {
ArrayList urls = new ArrayList();
MessageFactory factory = MessageFactory.newInstance(WS_DISCOVERY_SOAP_VERSION);
MimeHeaders headers = new MimeHeaders();
headers.addHeader("Content-type", WS_DISCOVERY_CONTENT_TYPE);
SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(data));
SOAPBody body = message.getSOAPBody();
Iterator i$ = getNodeMatching(body, ".*:XAddrs").iterator();
while(i$.hasNext()) {
Node node = (Node)i$.next();
if(node.getTextContent().length() > 0) {
urls.addAll(Arrays.asList(node.getTextContent().split(" ")));
}
}
return urls;
}
I want to use both method of DeviceDiscovery.class. But it's not accessible because it's a private method.
I am not able to editing in DeviceDiscovery.class because it's a part of jar file and it's only readable form.
This is the error I have:
(216, 80) error: parseSoapResponseForUrls(byte[]) has private access in DeviceDiscovery

Java Socket Data received unordered

I am collecting data from Android App(Accelerometer and Gyro) and send it to Desktop app via Java Socket but in high rates
(SENSOR_DELAY_FASTEST,SENSOR_DELAY_GAME)
Notes :
readingsList : contains all reading from sensors
I remove from list the data being sent to server
Only data sent once and i made sure it's ordered from client side
but i got them unordered in server side ( I received all data but not ordered)
processData(String reading) function may takes time but not too much
Client Code :
class SocketClientThread implements Runnable {
public SocketClientThread(){
}
public void run() {
while (!Thread.currentThread().isInterrupted() && breathingStarted) {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
socket.setSendBufferSize(Integer.MAX_VALUE);
socket.setReceiveBufferSize(Integer.MAX_VALUE);
int lastCount = readingsList.size();
out.println(readingsList);
out.flush();
out.close();
int toberemoved = lastCount;
if(readingsList.size() > 0){
for (int i = 0; i < toberemoved; i++) {
readingsList.remove(0);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Server Code :
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(minutes*60*1000);
Thread thread = new Thread() {
public void run() {
while(!isStopped)
{
try
{
Socket connection = serverSocket.accept();
connection.setReceiveBufferSize(Integer.MAX_VALUE);
connection.setSendBufferSize(Integer.MAX_VALUE);
BufferedReader input =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out =
new PrintWriter(connection.getOutputStream(), true);
String inputLine;
while ((inputLine = input.readLine()) != null) {
recentReading = inputLine;
String oldReading = recentReading;
String modifiedReading = oldReading.replace("[", "");
modifiedReading = modifiedReading.replace("]", "");
String [] readings = modifiedReading.split(",");
for (int i = 0; i < readings.length; i++) {
String currentReading = readings[i].trim();
String [] tokens = currentReading.split("_");
processData(currentReading);
}
}
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
display.syncExec(new Runnable() {
public void run() {
statusVal.setText("Socket timed out!");
}
});
break;
}catch(SocketException s)
{
if(serverSocket.isClosed()){
display.syncExec(new Runnable() {
public void run() {
statusVal.setText("Disconnected");
}
});
}
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
};
thread.setDaemon(true);
thread.start();
I am getting data after it's time (not ordered)

indexoutofboundsexception by sending pictures over Socket

I want to make a little programm that makes a live-stream for Desktop.
It should be so that you send pictures to an echo-server and he response it to the clients.
There you get be draw the Images. Side by Side. And so it is like a movie(or something like that).
But I always get an indexoutofboundsexception. Where is the error or how can I improve my program.
The ImageIO.write lines thows the Error
//Client Main
public class Main {
public static void main(String[] args) {
Frame frm = new Frame();
Frame.Client client;
frm.setLayout(null);
frm.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.setSize(1600,900);
frm.setVisible(true);
}
}
// get and send the Desktopimage
public class desktopCapture {
Robot robo;
BufferedImage screenImage;
Rectangle bounding;
public desktopCapture() {
try {
bounding = new Rectangle(0,0,1600,900);
robo = new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
public void sendScreenCapture(Socket client) {
screenImage = robo.createScreenCapture(bounding);
try {
ImageIO.write(screenImage, "png", client.getOutputStream());
} catch (IOException e) {e.printStackTrace();}
}
}
// in Frame two function for actionListener Objects, so I can say who streams his Desktop and which get only the Images to.
public void readImage() {
while(true) {
try {
while((screenImage = ImageIO.read(in)) != null){
repaintScreen();
}
} catch (IOException e) {e.printStackTrace();}
}
}
public void sendImage() {
try {
while(true){
dC.sendScreenCapture(client);
System.out.println("read1");
while((screenImage = ImageIO.read(in)) != null){
System.out.println("read2");
ImageIO.write(screenImage, "png", new File("image1.png"));
Thread.sleep(250);
}
repaintScreen();
screenImage = null;
}
} catch (IOException | InterruptedException e) {e.printStackTrace();}
}
}
}
//Thread for a Client
public class handler implements Runnable {
Socket client;
OutputStream out;
InputStream in;
PrintWriter writer;
BufferedImage image;
public handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while(true) {
System.out.println("write1");
while((image = ImageIO.read(in)) != null){
System.out.println("write2");
for(int i = 1;i <= Server.connectionArray.size();i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(i-1);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}
image = null;
}
}
} catch (IOException e) {e.printStackTrace();}
}
}
I would change your for loop to:
int count = Server.connectionArray.size()
int index = count - 1;
for(int i = 0;i < count; i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(index);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}

program to show a progress bar while transferring all files from one server to another in java

i have written a java code to transfer files from one server to another using the concept of socket programming. now in the same code i also want to check for the network connection availability before each file is transferred. i also want that the files transferred should be transferred according to their numerical sequence. And while the files are being transferred the transfer progress of each file i.e the progress percentage bar should also be visible on the screen.
i will really appreciate if someone can help me with the code. i am posting the code i have written for file transfer.
ClientMain.java
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ClientMain {
private DirectoryTxr transmitter = null;
Socket clientSocket = null;
private boolean connectedStatus = false;
private String ipAddress;
String srcPath = null;
String dstPath = "";
public ClientMain() {
}
public void setIpAddress(String ip) {
this.ipAddress = ip;
}
public void setSrcPath(String path) {
this.srcPath = path;
}
public void setDstPath(String path) {
this.dstPath = path;
}
private void createConnection() {
Runnable connectRunnable = new Runnable() {
public void run() {
while (!connectedStatus) {
try {
clientSocket = new Socket(ipAddress, 3339);
connectedStatus = true;
transmitter = new DirectoryTxr(clientSocket, srcPath, dstPath);
} catch (IOException io) {
io.printStackTrace();
}
}
}
};
Thread connectionThread = new Thread(connectRunnable);
connectionThread.start();
}
public static void main(String[] args) {
ClientMain main = new ClientMain();
main.setIpAddress("10.6.3.92");
main.setSrcPath("E:/temp/movies/");
main.setDstPath("D:/tcp/movies");
main.createConnection();
}
}
(DirectoryTxr.java)
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectoryTxr {
Socket clientSocket = null;
String srcDir = null;
String dstDir = null;
byte[] readBuffer = new byte[1024];
private InputStream inStream = null;
private OutputStream outStream = null;
int state = 0;
final int permissionReqState = 1;
final int initialState = 0;
final int dirHeaderSendState = 2;
final int fileHeaderSendState = 3;
final int fileSendState = 4;
final int fileFinishedState = 5;
private boolean isLive = false;
private int numFiles = 0;
private int filePointer = 0;
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
String dirFailedResponse = "Failed";
File[] opFileList = null;
public DirectoryTxr(Socket clientSocket, String srcDir, String dstDir) {
try {
this.clientSocket = clientSocket;
inStream = clientSocket.getInputStream();
outStream = clientSocket.getOutputStream();
isLive = true;
this.srcDir = srcDir;
this.dstDir = dstDir;
state = initialState;
readResponse(); //starting read thread
sendMessage(request);
state = permissionReqState;
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendMessage(String message) {
try {
sendBytes(request.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Thread to read response from server
*/
private void readResponse() {
Runnable readRunnable = new Runnable() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
} catch (SocketException se) {
System.exit(0);
} catch (IOException io) {
io.printStackTrace();
isLive = false;
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void sendDirectoryHeader() {
File file = new File(srcDir);
if (file.isDirectory()) {
try {
String[] childFiles = file.list();
numFiles = childFiles.length;
String dirHeader = "$" + dstDir + "#" + numFiles + "&";
sendBytes(dirHeader.getBytes("UTF-8"));
} catch (UnsupportedEncodingException en) {
en.printStackTrace();
}
} else {
System.out.println(srcDir + " is not a valid directory");
}
}
private void sendFile(String dirName) {
File file = new File(dirName);
if (!file.isDirectory()) {
try {
int len = (int) file.length();
int buffSize = len / 8;
//to avoid the heap limitation
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
int numRead = 0;
while (numRead >= 0) {
ByteBuffer buf = ByteBuffer.allocate(1024 * 100000);
numRead = channel.read(buf);
if (numRead > 0) {
byte[] array = new byte[numRead];
System.arraycopy(buf.array(), 0, array, 0, numRead);
sendBytes(array);
}
}
System.out.println("Finished");
} catch (IOException io) {
io.printStackTrace();
}
}
}
private void sendHeader(String fileName) {
try {
File file = new File(fileName);
if (file.isDirectory())
return;//avoiding child directories to avoid confusion
//if want we can sent them recursively
//with proper state transitions
String header = "&" + fileName + "#" + file.length() + "*";
sendHeader(header);
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (clientSocket) {
if (outStream != null) {
try {
outStream.write(dataBytes);
outStream.flush();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
private void processBytes(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(respServer) && state == permissionReqState) {
state = dirHeaderSendState;
sendDirectoryHeader();
} else if (message.trim().equalsIgnoreCase(dirResponse) && state == dirHeaderSendState) {
state = fileHeaderSendState;
if (LocateDirectory()) {
createAndSendHeader();
} else {
System.out.println("Vacant or invalid directory");
}
} else if (message.trim().equalsIgnoreCase(fileHeaderRecvd) && state == fileHeaderSendState) {
state = fileSendState;
sendFile(opFileList[filePointer].toString());
state = fileFinishedState;
filePointer++;
} else if (message.trim().equalsIgnoreCase(fileReceived) && state == fileFinishedState) {
if (filePointer < numFiles) {
createAndSendHeader();
}
System.out.println("Successfully sent");
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Going to exit....Error ");
// System.exit(0);
} else if (message.trim().equalsIgnoreCase("Thanks")) {
System.out.println("All files were copied");
}
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean LocateDirectory() {
boolean status = false;
File file = new File(srcDir);
if (file.isDirectory()) {
opFileList = file.listFiles();
numFiles = opFileList.length;
if (numFiles <= 0) {
System.out.println("No files found");
} else {
status = true;
}
}
return status;
}
private void createAndSendHeader() {
File opFile = opFileList[filePointer];
String header = "&" + opFile.getName() + "#" + opFile.length() + "*";
try {
state = fileHeaderSendState;
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
private void sendListFiles() {
createAndSendHeader();
}
}
(ServerMain.java)
public class ServerMain {
public ServerMain() {
}
public static void main(String[] args) {
DirectoryRcr dirRcr = new DirectoryRcr();
}
}
(DirectoryRcr.java)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class DirectoryRcr {
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String dirFailedResponse = "Failed";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
Socket socket = null;
OutputStream ioStream = null;
InputStream inStream = null;
boolean isLive = false;
int state = 0;
final int initialState = 0;
final int dirHeaderWait = 1;
final int dirWaitState = 2;
final int fileHeaderWaitState = 3;
final int fileContentWaitState = 4;
final int fileReceiveState = 5;
final int fileReceivedState = 6;
final int finalState = 7;
byte[] readBuffer = new byte[1024 * 100000];
long fileSize = 0;
String dir = "";
FileOutputStream foStream = null;
int fileCount = 0;
File dstFile = null;
public DirectoryRcr() {
acceptConnection();
}
private void acceptConnection() {
try {
ServerSocket server = new ServerSocket(3339);
socket = server.accept();
isLive = true;
ioStream = socket.getOutputStream();
inStream = socket.getInputStream();
state = initialState;
startReadThread();
} catch (IOException io) {
io.printStackTrace();
}
}
private void startReadThread() {
Thread readRunnable = new Thread() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
sleep(100);
} catch (SocketException s) {
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException i) {
i.printStackTrace();
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void processBytes(byte[] buff) throws InterruptedException {
if (state == fileReceiveState || state == fileContentWaitState) {
//write to file
if (state == fileContentWaitState)
state = fileReceiveState;
fileSize = fileSize - buff.length;
writeToFile(buff);
if (fileSize == 0) {
state = fileReceivedState;
try {
foStream.close();
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Received " + dstFile.getName());
sendResponse(fileReceived);
fileCount--;
if (fileCount != 0) {
state = fileHeaderWaitState;
} else {
System.out.println("Finished");
state = finalState;
sendResponse("Thanks");
Thread.sleep(2000);
System.exit(0);
}
System.out.println("Received");
}
} else {
parseToUTF(buff);
}
}
private void parseToUTF(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(request) && state == initialState) {
sendResponse(respServer);
state = dirHeaderWait;
} else if (state == dirHeaderWait) {
if (createDirectory(message)) {
sendResponse(dirResponse);
state = fileHeaderWaitState;
} else {
sendResponse(dirFailedResponse);
System.out.println("Error occurred...Going to exit");
System.exit(0);
}
} else if (state == fileHeaderWaitState) {
createFile(message);
state = fileContentWaitState;
sendResponse(fileHeaderRecvd);
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Error occurred ....");
System.exit(0);
}
}
private void sendResponse(String resp) {
try {
sendBytes(resp.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean createDirectory(String dirName) {
boolean status = false;
dir = dirName.substring(dirName.indexOf("$") + 1, dirName.indexOf("#"));
fileCount = Integer.parseInt(dirName.substring(dirName.indexOf("#") + 1, dirName.indexOf("&")));
if (new File(dir).mkdir()) {
status = true;
System.out.println("Successfully created directory " + dirName);
} else if (new File(dir).mkdirs()) {
status = true;
System.out.println("Directories were created " + dirName);
} else if (new File(dir).exists()) {
status = true;
System.out.println("Directory exists" + dirName);
} else {
System.out.println("Could not create directory " + dirName);
status = false;
}
return status;
}
private void createFile(String fileName) {
String file = fileName.substring(fileName.indexOf("&") + 1, fileName.indexOf("#"));
String lengthFile = fileName.substring(fileName.indexOf("#") + 1, fileName.indexOf("*"));
fileSize = Integer.parseInt(lengthFile);
dstFile = new File(dir + "/" + file);
try {
foStream = new FileOutputStream(dstFile);
System.out.println("Starting to receive " + dstFile.getName());
} catch (FileNotFoundException fn) {
fn.printStackTrace();
}
}
private void writeToFile(byte[] buff) {
try {
foStream.write(buff);
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (socket) {
if (ioStream != null) {
try {
ioStream.write(dataBytes);
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
ClientMain.java and DirectoryTxr.java are the two classes under client application. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
run the ClientMain.java and ServerMain.java
You can sort an array using Arrays.sort(...)
ie
String[] childFiles = file.list();
Arrays.sort(childFiles);
As I understand it, this will sort the files in natural order, based on the file name.
You can modify this by passing a custom Comparator...
Arrays.sort(childFiles, new Comparator<File>() {...}); // Fill out with your requirements...
Progress monitoring will come down to your requirements. Do you want to see only the overall progress of the number of files, the individual files, a combination of both?
What I've done in the past is pre-iterated the file list, calculated the total number of bytes to be copied and used a ProgressMonitor to display the overall bytes been copied...
Otherwise you will need to supply your own dialog. In either case, you will need use SwingUtilities.invokeLater to update them correctly.
Check out Concurrency in Swing for more details.
Network connectivity is subjective. You could simply send a special "message" to there server and wait for a response, but this only suggests that the message was sent and a recipt was received. It could just as easily fail when you start transfering the file again...

how to limit the display of questions using json array in android

hey guys im developing a quiz where i have 50 questions randomly stored using json array, now my problem is all those 50 questions are displayed everytime the user will play.is it possible to limit them if iwant only 10 questions to display?...i have 50 questions stored because it is randomly selected but i want only 10 to display..please help me guys..thanks so much!
public class Question1<JsonObject> extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
static int index = 50;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
List<JSONObject> question = new ArrayList<JSONObject>();
int n = Math.min(10, quesList.length());
for(int i = 0; i < n; i++) {
JSONObject questions1 = quesList.getJSONObject(i);
question.add(questions1);
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
}
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList()throws JSONException{
Random rnd = new Random();
for (int i = quesList.length() - 1; i >= 0; i--)
{
int j = rnd.nextInt(i + 1);
// Simple swap
Object object = quesList.get(j);
quesList.put(j, quesList.get(i));
quesList.put(i, object);
}
return quesList;
}
Try to put it this way:
List<JSONObject> question = null;
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
}
question = new ArrayList<JSONObject>();
int n = Math.min(10, quesList.length());
for(int i = 0; i < n; i++) {
JSONObject questions1 = quesList.getJSONObject(i);
question.add(questions1);
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
Looks like naming in Your program is messed up. There's no specific code, but I assume that You need to use List<JSONObject> question instead of quesList.

Categories