I want to upload files one by one like queue in android - android

I want to upload files one by one just like queue. In brief suppose there are 10 files and I want to upload all files and it should be checking for network connectivity is available or not, if not then those file should be into the queue and will try to upload later. It will keep on trying till any single file in left queue. Please help me out, How can I achieve this in android.
This is the sample code that I have tried so far
final Thread thread = new Thread(){
public void run() {
try {
while(true){
ThisCaching ic = new ThisCaching(getApplicationContext());
fileToUpload = ic.getDataFromCache("audiofiles", "SELECT * FROM audiofiles WHERE STATUS = '2' OR STATUS = '3' ORDER BY rowid DESC");
if(fileToUpload != null)
{
for (int i=0; i<fileToUpload.size(); i++) {
try {
System.out.println("Current position while uploading ::> " + i);
Thread.sleep(1000);
ConstantData.selectedFile = fileToUpload.get(i).toString();
ConstantData.position = i;
if(checkConnectivity()){
new Uploading().execute();
myApplication.getHttpClient().getConnectionManager().closeExpiredConnections();
}else{
String[] status = {"STATUS"};
String[] val = {"2"};
try {
SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e) {
return;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
};
String line = null;
HttpClient httpClient = null;
HttpContext localContext = null;
HttpPost httpPost = null;
MultipartEntity entity = null;
HttpResponse response = null;
HttpEntity httpEntity =null;
SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
try {
String strArray[]={"http://myurl.com","filename",ConstantData.selectedFile,"activityType",ConstantData.activityType,"patientId",ConstantData.patientId,"caseId",ConstantData.caseId,"doctorId",ConstantData.doctorId,"clinicCode",ConstantData.clinicCode,"documentType",ConstantData.documentType,"templateId",ConstantData.templateId};
httpClient = new DefaultHttpClient();
//httpClient.getConnectionManager().r
localContext = new BasicHttpContext();
httpPost = new HttpPost(strArray[0]);
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(ConstantData.selectedFile);
String type = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")+1);
if(strArray.length>1)
{
for(int i=1;i<strArray.length;i=i+2)
{
if(strArray[i]!=null){
if(!strArray[i].equalsIgnoreCase("")){
// System.out.println("i) : "+i +" i+1) : "+(i+1));
Log.i(strArray[i], "::" + strArray[i+1]);
if(strArray[i].equalsIgnoreCase("filename")){
entity.addPart("filename", new FileBody(file,"audio/"+type));
}else{
entity.addPart(strArray[i], new StringBody(strArray[i+1]));
}
}
}
}
}
httpPost.setEntity(entity);
response = httpClient.execute(httpPost,localContext);// i m getting error at this line
System.out.println("Response code is ::> " +response.getStatusLine().getStatusCode());
code = response.getStatusLine().getStatusCode();
httpEntity = response.getEntity();
line = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (IOException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (Exception e) {
code=100;
e.printStackTrace();
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
}finally{
//
try {
// System.out.println("&&&& while realeasing connection");
//// if(httpClient != null){
//// httpClient.getConnectionManager().releaseConnection((ManagedClientConnection) httpClient.getConnectionManager(), -1, TimeUnit.MINUTES);
//// }
// if(httpPost.getEntity().getContent() != null){
// InputStream content = httpPost.getEntity().getContent();
// content.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
}
return line;
`

From what I see, do you use plain Threads (cant see the edit, yet). Since Java 1.5 there's an package for such things as queues and mutlithreading, that makes live much easier.
For your purpose of a queue, you can create a single threaded executor with Executors.newSingleThreadExecutor(). You get a Threadpool with just one thread that executes each task you submit(Runnable) in the order you submitted them. Java garanties, that the Executor always has one thread working on the queue (Java recreates the Thread automatically if it dies)
Each task you submit implements a Runnable. So, to implement the three retries you described, you just need a class that implements the Runnable interface, that counts the retries and - if the upload was not succesful - it increments the counter and resubmits itself.
Here's the Guide, Tutorial and Reference to Executors and ExecutorService.

Related

How to get a working HttpsUrlConnection with Steam Web API?

im currently trying to implement the Steam Web API using the given code in the following repository -> https://github.com/Overv/SteamWebAPI/blob/master/SteamAPISession.cs into my Android app and im getting different exceptions dependend on using the given wep api ip ( 63.228.223.110 ) or the adress ( https://api.steampowered.com/ ) itself.
my code actually looks like this in the given method when building up a connection to the web api:
private String steamRequest( String get, String post ) {
final int MAX_RETRIES = 3;
int numberOfTries = 0;
HttpsURLConnection request = null;
while(numberOfTries < MAX_RETRIES) {
if (numberOfTries != 0) {
Log.d(TAG, "Retry -> " + numberOfTries);
}
try {
request = (HttpsURLConnection) new URL("https://api.steampowered.com/" + get).openConnection(); //or 63.228.223.110/ ???
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
String host = "api.steampowered.com";
int port = 443;
int header = 0;
socketFactory.createSocket(new Socket(host, port), host, port, false);
request.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
request.setSSLSocketFactory(socketFactory);
request.setDoOutput(false);
// request.setRequestProperty("Host", "api.steampowered.com:443");
// request.setRequestProperty("Protocol-Version", "httpVersion");
request.setRequestProperty("Accept", "*/*");
request.setRequestProperty("Accept-Encoding", "gzip, deflate");
request.setRequestProperty("Accept-Language", "en-us");
request.setRequestProperty("User-Agent", "Steam 1291812 / iPhone");
request.setRequestProperty("Connection", "close");
if (post != null) {
byte[] postBytes;
try {
request.setRequestMethod("POST");
postBytes = post.getBytes("US-ASCII");
// request.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
request.setFixedLengthStreamingMode(postBytes.length);
request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(request.getOutputStream());
out.print(post);
out.close();
// DataOutputStream requestStream = new DataOutputStream(request.getOutputStream());
//// OutputStreamWriter stream = new OutputStreamWriter(request.getOutputStream());
//// stream.write(postBytes, 0, postBytes.length);
// requestStream.write(postBytes, 0, postBytes.length);
// requestStream.close();
message++;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
int statusCode = request.getResponseCode();
InputStream is;
Log.d(TAG, "The response code of the status code is" + statusCode);
if (statusCode != 200) {
is = request.getErrorStream();
Log.d(TAG, String.valueOf(is));
}
// String src = null;
// OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream());
// out.write(src);
// out.close();
Scanner inStream = new Scanner(request.getInputStream());
String response = "";
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
// String src;
// BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
// StringBuilder builder = new StringBuilder();
// while ((src = in.readLine()) != null) {
// builder.append(src);
// }
// String jsonData = builder.toString();
Log.d(TAG, response); //jsonData
// in.close();
return response; //jsonData
} catch (MalformedURLException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_LONG).show();
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (request != null) {
request.disconnect();
}
}
numberOfTries++;
}
Log.d(TAG, "Max retries reached. Giving up on connecting to Steam Web API...");
return null;
}
following exception occurs when using https://api.steampowered.com/ as url:
W/System.err﹕ java.io.FileNotFoundException: https://api.steampowered.com/ISteamOAuth2/GetTokenWithCredentials/v0001
D/OptionsFragment﹕ Failed to log in!
i've really tried and researched on those issues, but i just can't get a solution. If someone got a good hint on helping to solve these exceptions please let me know!
EDIT:
I've researched some more!
Looking up on https://partner.steamgames.com/documentation/webapi#creating the direct ip adress shouldn't be used and therefore only the DNS name itself (for further clarification look on the given link). Hence, looking up on the API interface list itself -> http://api.steampowered.com/ISteamWebAPIUtil/GetSupportedAPIList/v0001/?format=json there doesn't seem to be a given Interface with a method called ISteamOAuth2/GetTokenWithCredentials.(Or not anymore!) Only ISteamUserAuth and ISteamUserOAuth which seem to handle Authentication stuff.
I will update this post again if i should get a working connection and handling with the steam web api.
Cheers!

Extracting data from server takes too much time- android

I have a android application, where i extract data from the multiple urls and save then as arraylist of string. It works fine, but for fetching data from 13 urls, it takes close to 15-20 sec. Where as fetching the data from same set of urls take 3-4 sec in same app built using phonegap. Here is the code below.
#Override
protected String doInBackground(String... params) {
client = new DefaultHttpClient();
for(int i=0;i<url.size();i++)
{
get = new HttpGet(url.get(i));
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
String str = buffer.toString();
param.add(str);
}
return null;
}
Could anyone please suggest how i can speed this execution and reduce the extraction time.
You could try starting a separate thread for each iteration from the for loop.
Smth like this :
for(int i = 0; i < url.size(); i++){
//start thread that gets data from url and adds it to the list
}

How to handle IllegalBlockSizeException: last block incomplete in decryption in android

I am working on encryption decryption using AES and is working fine.But for the security checks i have done some changes in a file. Now again when i am running it is crashing on the line where it throws error of
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
.
I have put log's and flags but it is not reaching the next line.Please suggest me how to handle this exception. I used try catch also but not working. The code snippet is":
DataBaseActivity myDbHelper;
File myFile1 = new File(filing1); //Date.txt
FileInputStream fIn = null;
String dateDec= null;
String[] date = null;
Boolean flag = null;
Calendar cal1 = null;
Calendar cal2 = null;
try {
fIn = new FileInputStream(myFile1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow1 = "";
String aBuffer1 = "";
try {
while ((aDataRow1 = myReader.readLine()) != null) {
aBuffer1 += aDataRow1;
myReader.close();
dateDec = AESencrp.decrypt(aBuffer1);
System.out.println("Datedec"+dateDec);
if(dateDec == ""){
flag = false;
}else {
flag = true;
}
}
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (NullPointerException e) {
e.printStackTrace();
}
if(flag == true) {
try
{
System.out.println("checks1");
//DataBaseActivity openHelperClass = new DataBaseActivity(this);
myDbHelper = new DataBaseActivity(this);
// myDbHelper = new DataBaseActivity(this);
System.out.println("checks2");
try {
System.out.println("checks3");
myDbHelper.createDataBase();
System.out.println("checks4");
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
The Exception is on the line dateDec = AESencrp.decrypt(aBuffer1);

restarting AsyncTask in Service

I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
private class DklabExecute extends AsyncTask<Void, String, Void> {
int count;
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());
HttpGet rplPost = new HttpGet(url);
protected Void doInBackground(Void... args)
{
Log.i("service count", Integer.toString(count));
count ++;
Log.i("md5 func", md5(LoginActivity.passUserId));
String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";
JSONParser parser = new JSONParser();
DefaultHttpClient testClient = new DefaultHttpClient();
DefaultHttpClient rplClient = new DefaultHttpClient();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
HttpGet httpTest = new HttpGet(testData);
httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
try {
httpResponse = rplClient.execute(rplPost);
}
catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Header[] head = httpResponse.getAllHeaders();
Log.i("http Response",httpResponse.toString());
for (Header one:head)
{
Log.i("headers",one.toString());
}
Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);// + "n");
}
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
json = sb.toString();
Log.i("rpl response",json);
if (new JSONArray(json) != null)
jArr = new JSONArray(json);
else
this.cancel(true);
JSONObject toObj = jArr.getJSONObject(0);
JSONObject data = toObj.getJSONObject(KEY_DATA);
if (data.has(KEY_ORDER))
{
for (Order a : ServiceMessages.orderExport)
{
Log.i("service before list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("before dashboard list", a.toString());
}
JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
Gson gson = new Gson();
Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
try
{
for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
{
Order a = itr.next();
Log.i("order count", a.toString());
if(orderObj.getOrderid()==a.getOrderid())
{
Log.i("Service","order was changed");
a = orderObj;
someMethod("Your order "+ orderObj.getTitle() + " was changed");
}
else
{
Log.i("Service","order"+ orderObj.getTitle()+" was added");
// DashboardActivityAlt.forPrint.add(0, orderObj);
ServiceMessages.orderExport.add(0,orderObj);
Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
someMethod("Your order "+ orderObj.getTitle() + " was added");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (Order a : ServiceMessages.orderExport)
{
Log.i("service after list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("after dashboard list", a.toString());
}
// intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
sendBroadcast(intentOrder);
Log.i("after parse order",orderObj.toString());
Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
}
else if (data.has(KEY_MESSAGE))
{
JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
Gson gson = new Gson();
Log.i("messages before parse", jsonMessage.toString());
for (Order a: DashboardActivityAlt.forPrint)
{
Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
}
Log.i("disparse message",jsonMessage.toString());
Message message = gson.fromJson(jsonMessage.toString(),Message.class);
Log.i("incomming message",message.toString());
JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
Threads thread = gson.fromJson(jsonThread.toString(),Threads.class);
Log.i("incomming thread",thread.toString());
Order orderChanged = new Order();
String orderName = null;
for(Order as : DashboardActivityAlt.forPrint)
{
if (as.getOrderid() == thread.getTreadOrder().getOrderid())
{
orderName = as.getTitle();
orderChanged = as;
Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
}
}
Log.i("orderchanged",orderChanged.toString());
someMethod("Your order "+ thread.getTreadOrder().getTitle() + " was changed. Message was added");
orderChanged.getCusThread().addMessage(message);
sendBroadcast(intentMessage);
Log.i("messages service", "before sleep");
Log.i("messages service", "after sleep");
}
else
{
this.cancel(true);
}
}
catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
rplClient.getConnectionManager().shutdown();
testClient.getConnectionManager().shutdown();
someMethod("You've lost internet connection. You should try later.");
e2.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void bitmap) {
this.cancel(true);
new DklabExecute().execute();
}
}
If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...
if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
private ScheduledExecutorService executor;
// call those on startCommand
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);
and have a Runnable doing the work
private Runnable run = new Runnable() {
#Override
public void run() {
// do your network stuff
}
};
and don't forget to cancel everything when your service stops
executor.shutdown();
edit:
or to use a thread in loop you can:
boolean isRunning;
.
// this on your start
Thread t = new Thread(run);
isRunning = true;
t.start();
the runnable
private Runnable run = new Runnable() {
#Override
public void run() {
while(isRunning){
// do your network stuff
}
}
};
and again, don't forget to finish it whenever the service finishes with:
isRunning = false;

Fetch ip address of pc on android emulator through code android

I want to get the ip address of my pc in android emulator through code....or tell me to achive ip address of all devices connected in a lan to identify each one uniquely .......please help me to sort out this problem
Thanks in advance
The above functions are possible only by checking the arp cache where the IP address will be added one by one depending on how each one connect to the device. USe the below code and check. Just put button with proper name and call this method on click
public void getClientList() {
int macCount = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
macCount++;
ClientList.add("Client(" + macCount + ")");
IpAddr.add(splitted[0]);
HWAddr.add(splitted[3]);
Device.add(splitted[5]);
Toast.makeText(
getApplicationContext(),
"Mac_Count " + macCount + " MAC_ADDRESS "
+ mac, Toast.LENGTH_SHORT).show();
for (int i = 0; i < splitted.length; i++)
System.out.println("Addressssssss "
+ splitted[i]);
}
}
}
// ClientList.remove(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
use this code fetch the external ip address
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://api.externalip.net/ip/");
HttpResponse response = null;
try
{
response = httpclient.execute(httpget);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Log.e("",""+response);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 && len < 1024)
{
try
{
str=EntityUtils.toString(entity);
Log.e("",""+str);
}
catch (ParseException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Categories

Resources