I'm having a thread contention issue when my program gets to executing an asynctask whose current purpose is to connect to an ftp server and based on a successful connection then make a get HTTP parsing request in order to access JSON data I need to write into a local SQLite database.
I'm slightly new in understanding thread contention but having read around particulalry this article I suspect it is a deadlock.
Below is my debug window which is called when I run my app. I'm doing so on a device and not an emulator:
Below is the asynctask code:
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(AllProductsActivity.this);
//pDialog.setMessage("Loading products. Please wait...");
Log.i("LoadAllProducts", "LoadAllProducts - Loading products. Please wait...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.i("LoadAllProducts", "URL: " + url_all_products);
ftpConnectLoginAndUpload = new FTPConnectLoginAndUpload();
if(ftpConnectLoginAndUpload.execute()) {
// Check your log cat for JSON response
Log.d("LoadAllProducts ", "About to execute JSONObject json = jParser.makeHttpRequest(url_all_products, \"GET\", params);");
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON response
Log.d("LoadAllProducts ", json.toString());
/*try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS); // products is a variable holding the value from the 2nd key-value pairing.
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String price = c.getString("price");
String created_at = c.getString("created_at");
String updated_at = c.getString("updated_at");
Log.d("LoadAllProducts ", "JSON item var i.e. id:" + id);
Log.d("LoadAllProducts ", "JSON item var i.e. name:" + name);
Log.d("LoadAllProducts ", "JSON item var i.e. price:" + price);
Log.d("LoadAllProducts ", "JSON item var i.e. created_at:" + created_at);
Log.d("LoadAllProducts ", "JSON item var i.e. updated_at:" + updated_at);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}*/
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
Log.i("LoadAllProducts", "LoadAllProducts - dismiss the dialog after getting all products");
// updating UI from Background Thread
/*runOnUiThread(new Runnable() {
public void run() {
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});*/
}
}
Below is the FTP log in code:
//!< FTP Connect, Login And Upload
public class FTPConnectLoginAndUpload {
//!<
private void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("---> showServerReply(FTPClient ftpClient) - SERVER: " + aReply);
}
}
}
//!<
public boolean execute() {
// Boston's FTP login credentials
String server = "XX.XXX.XXX.XX";
int port = 21;
String user = "XXXXXXXX_XXXXXX";
String pass = "XXXXXXXX";
// Time out period after connection attempt
int timeOut = 5000;
boolean ftpResult;
// FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server
// This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface
FTPClient ftpClient = new FTPClient();
// Execute FTP process
try {
// Set connection timeout in milliseconds
ftpClient.setConnectTimeout(timeOut);
// Sets the timeout in milliseconds to use when reading from the data connection.
ftpClient.setDataTimeout(timeOut);
// Connect using provided server and port numb
ftpClient.connect(server, port);
System.out.println("\n---> ftpClient.connect(server, port) has been executed.\n---> Server used was "
+ server + " and port number used was: " + port);
System.out.println("\n---> ftpClient.getReplyString() returns: " + ftpClient.getReplyString());
// Returns server reply
System.out.println("\n---> Server reply is as follows:");
showServerReply(ftpClient);
System.out.println("---> End of server reply");
// Get server reply code
int replyCode = ftpClient.getReplyCode();
System.out.println("\n---> ftpClient replyCode is: " + replyCode);
// Determine if a reply code is a positive completion response. All codes beginning with a 2 are positive completion responses.
// The FTP server will send a positive completion response on the final successful completion of a command.
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("\n---> Operation failed. Server reply code: " + replyCode);
ftpResult = false;
return ftpResult;
} else {
System.out.println("\n---> Operation successful. Server reply code: " + replyCode);
// Attempt login
boolean success = ftpClient.login(user, pass);
System.out.println("\n---> ftpClient.login(user, pass); has been called.");
// Determine log in success
if (!success) {
System.out.println("\n ---> Unable to login to the server");
ftpResult = false;
return ftpResult;
} else {
System.out.println("\n---> Successfully logged into server");
ftpResult = true;
}
//
ftpClient.enterLocalPassiveMode();
// Show server reply after logging in
System.out.println("\n---> Server response after logging in is as follows:");
showServerReply(ftpClient);
System.out.println("---> End of server response after logging");
return ftpResult;
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
ftpResult = false;
return ftpResult;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
ftpResult = false;
return ftpResult;
}
} catch (IOException ex) {
ex.printStackTrace();
ftpResult = false;
return ftpResult;
}
}
}
}
Related
i've got problem getting data from Node server, i've searching many reference from internet, but i haven't found one yet that can solve my problem.
this is my node server
var socket = require('socket.io');
var express = require('express');
var app = express();
/*
var options = {
key: fs.readFileSync('cert/file.key'),
cert: fs.readFileSync('cert/file.crt')
};
var server = require('https').createServer(options, app);
*/
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
//server.listen(port, '103.126.57.4', function () {
server.listen(port, function () {
console.log('Server listening at port %d', port);
//console.log('Server listening at port %d', port, server.address());
});
io.on('connection', function (socket) {
console.log( "New client connected !" );
//console.log(socket.handshake.headers.host);
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'new_chat_kelas', function( data ) {
io.sockets.emit( data.tabelchat, {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'change_chat_status', function( data ) {
io.sockets.emit( 'change_status'+data.tabelchat, {
status: data.status
});
});
/*
socket.on('disconnect', function () {
console.log( "Client disconnected !" );
});
*/});
And this is my Android code
try {
//if you are using a phone device you should connect to same local network as your laptop and disable your pubic firewall as well
socket = IO.socket("http://192.168.100.13:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
refreshChat(url);
getTabelKelas();
getDiskusiChat(sharedDiskusi.getSpdiskusi());
private void getDiskusiChat(String tabelChat) {
socket.on(tabelChat, new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String jsonStr = data.toString();
Log.d("cek", "cek data : "+data);
Toast.makeText(mContext, (CharSequence) data, Toast.LENGTH_LONG).show();
try {
//extract data from fired event
String cek = String.valueOf(data.getJSONArray("idleveluser"));
// String nickname = data.getString("senderNickname");
// String message = data.getString("message");
// make instance of message
//
// Message m = new Message(nickname,message);
// Message m = new Message(nickname,message);
//
//
// //add the message to the messageList
//
// MessageList.add(m);
//
// // add the new updated list to the dapter
// chatBoxAdapter = new ChatBoxAdapter(MessageList);
//
// // notify the adapter to update the recycler view
//
// chatBoxAdapter.notifyDataSetChanged();
//
// //set the adapter for the recycler view
//
// myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
i have try to Toast and log it but did not appear.
Can anyone help me to retrieve data ?I confuse how to get data if the data in the form of an array. I'm helped if someone helps me.
Sry for my bad english brother.
This is my log
Change this code line
String cek = String.valueOf(data.getJSONArray("idleveluser"));
to
String cek = String.valueOf(data.getString("idleveluser"));
as each item in the data object is a string.
I have problem sending a string parameter to a PHP file to download a song inserting the song's name from a edit text. I don't understand the error I'm receiving.
Thanks in advance for the help!
LOGCAT:
Response from url: {"error":false,"message":"Musics fetched successfully.","musics":[]}
i don't know why the array is empty.
The PHP file works if i use a rest client passing the song's name but not in the URL.
This is my code:
ANDROID SIDE:
class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
canzone = editText.getText().toString();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
/* title=jsonObj.getString("title");
link=jsonObj.getString("link");
HashMap<String, String> contact = new HashMap<>();
contact.put("title", title);
contact.put("link", link);
System.out.println("LINK: "+link);
contactList.add(contact);
*/
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
JSONArray jsonArray = jsonObj.getJSONArray("musics");
for (int i = 0; i < jsonArray.length(); i++) {
//Declaring a json object corresponding to every pdf object in our json Array
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Declaring a Pdf object to add it to the ArrayList pdfList
// Pdf pdf = new Pdf();
// String pdfName = jsonObject.getString("name");
//String pdfUrl = jsonObject.getString("url");
//pdf.setName(pdfName);
//pdf.setUrl(pdfUrl);
//pdfList.add(pdf);
canzone_cantante = jsonObject.getString("canzone_cantante");
}
/* pdfAdapter=new PdfAdapter(MainActivity.this,R.layout.list_layout, pdfList);
listView.setAdapter(pdfAdapter);
pdfAdapter.notifyDataSetChanged();*/
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("canzone_cantante", canzone_cantante);
//contact.put("email", email);
// contact.put("mobile", mobile);
/* Toast.makeText(getApplicationContext(),
"LINK: "+link ,
Toast.LENGTH_LONG).show();*/
// adding contact to contact list
System.out.println("LINK: " + canzone_cantante);
contactList.add(contact);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
PHP CODE:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$canzone = $_POST['canzone'];
require_once 'dbDetails.php';
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die("Unable to connect");
$sql = "SELECT * FROM music where canzone = '$canzone'";
$result = mysqli_query($con,$sql);
//response array
$response = array();
$response['error'] = false;
$response['message'] = "Musics fetched successfully.";
$response['musics'] = array();
//traversing through all the rows
while($row =mysqli_fetch_array($result)){
$temp = array();
$temp['id'] = $row['id'];
$temp['canzone'] = $row['canzone'];
$temp['canzone_cantante'] = $row['canzone_cantante'];
$temp['url'] = $row['url'];
array_push($response['musics'],$temp);
}
echo json_encode($response);
}
You are sending your canzone parameter with get request( inAndroid) but trying to get it by POST global variable(in php)
so i suggest changing your php from $canzone= $_POST['canzone']; to $canzone= $_GET['canzone'];
EDIT
also change the if statement here
if($_SERVER['REQUEST_METHOD']=='POST'){
to
if($_SERVER['REQUEST_METHOD']=='GET'){
You send song name as GET not like post.
Also you need to urlencode name of a song, if it has more then one word in name.
Cheers :)
As I understood you post the request like this from Android App
String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
But there is a problem that you send 'canzone' in URL, so this is GET parameter, and in the PHP you grab this variable from $_POST, just change $_POST to $_GET, should work
Try with replacing this line
$canzone = $_POST['canzone'];
with
$canzone = $_REQUEST['canzone'];
I have use alljoyn for wifi share. I want device list connected to wifi network on channel base.
I have follow one demo but it not call implemented method announced
AboutListener is part of alljoyn.
import org.alljoyn.bus.AboutListener;
public class OnboardingApplication extends Application implements AboutListener {
#Override
public void announced(String busName, int version, short port, AboutObjectDescription[] objectDescriptions, Map<String, Variant> aboutMap) {
Map<String, Object> newMap = new HashMap<String, Object>();
try {
newMap = TransportUtil.fromVariantMap(aboutMap);
String deviceId = (newMap.get(AboutKeys.ABOUT_APP_ID).toString());
String deviceFriendlyName = (String) newMap.get(AboutKeys.ABOUT_DEVICE_NAME);
m_logger.debug(TAG, "onAnnouncement received: with parameters: busName:" + busName + ", port:" + port + ", deviceid" + deviceId + ", deviceName:" + deviceFriendlyName);
addDevice(deviceId, busName, port, deviceFriendlyName, objectDescriptions, newMap);
} catch (BusException e) {
e.printStackTrace();
}
}
}
In order to get the announced method called you'll need to register your AboutListener:
org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
//Bus Connection
Status status = mBus.connect();
//Check if connection is established
if (status != Status.OK) {
return;
}
//Setup Bus Attachment
mBus.useOSLogging(true);
mBus.setDebugLevel("ALLJOYN_JAVA", 7);
mBus.registerAboutListener(mListener);
//Start AboutData Listener
status = mBus.whoImplements(null);
if (status != Status.OK) {
Log.e(TAG, "whoImplements Error");
} else {
Log.w(TAG, "whoImplements Success");
}
mListener is your object that implements AboutListener.
When you call whoImplements(null) you are saying you want all announcements from all interfaces.
In addition to what LopesFigueiredo said, try creating your BusAttachment with a remote message policy of Receive. For example:
BusAttachment mBus = new BusAttachment("My Attachment", BusAttachment.RemoteMessage.Receive);
I am new to NFC tags and am interested on how it work. I have bought a NFC tag and am able to write studentid to the tag. Now my problem is how to pass the student id to a php web service and check if this student has paid his/her meals before thy can proceed to the cafeteria when thy scan their student cards through my application.
Kindly anyone assist me on how i can do this. below is what i have done.
//reading the tag
private String readText(NdefRecord record) throws UnsupportedEncodingException {
byte[] payload = record.getPayload();
// Get the Text Encoding
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
// Get the Language Code
int languageCodeLength = payload[0] & 0063;
// Get the Text
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
//show the student id in a textedit
mTextView.setText(result);
//pass variable to the server and get contents. I want to pass the student id to the method
getstudentinfo(result);
}
}
void getstudentinfo(String studID) {
//get connection to the server using http request
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://myip/getStudentBl.php?studID="+ studID);
try{
response = getThreadSafeClient().execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
//checking the response and info the user
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
//if the user is found
if(response.equalsIgnoreCase("Student Found")){
runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(MainActivity.this,"Saved Successfull", Toast.LENGTH_SHORT).show();
stdBalance.setText("Student Balance " + response);
}
});
//show the dashboard screen
startActivity(new Intent(MainActivity.this, MainActivity.class));
}else if(response.equalsIgnoreCase("No Record")){
//show error results
showAlert();
}
//end try catch
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
From my understanding, with android readers at a minimum, if the tag holds an URL, it will automatically load the browser and go to the URL (no asking if you want to open the app nor if you want to go to the URL). You should be able to just put the student_id as a query string and use it in a page.
Looks here to have an exemple of an NDEF implementation : Github repo
In the main activity you will have to modify the
#Override
public void ndefDataRead(String ndefData) {
demoTextView.setText(ndefData);
}
to call your getstudentinfo(String studID) methods and it might work
hello i want to ask some question
i want to make application that connected with a web services that i made
my app has 2 uniqueID called app_id and token, app_id generate only once when the app first start and token generated by web service
every request, i must check whenever the token already expired or not, if the token already expired it will call separate web service and generate new token
the problem is the app must access 2 different web service: to request new token and to get another desired data
i use asynctask, but the response from web service for request token always same every request and i have no idea why
protected Boolean doInBackground(Void... params) {
int status = 0;
int token_expired=0;
String token_val = token.getToken(getBaseContext());
for(int i=0;i<5 && status==0;i++) {
try {
Thread.sleep(1000);
//function to check if token already expired or not and request new token using http post
token_expired = token.checkToken(getBaseContext());
System.out.println("token expired: " +token_expired);
if (token_expired==1 || token_expired==2) {
//function to call another web service and get a data from it
status = rclient.Execute("POST");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (status==0) {
return false;
}else{
return true;
}
}
thanks before!
oh yeah this is a function of check token from class token handler
public Integer checkToken(Context context) {
int status = 0; //0 = failed to request token , 1 = successfully request new token, 2 = token has not expired yet
String token_id = getToken(context);
System.out.println("token_id: " +token_id);
//if (token_id!=null) {
Long time = getTime(context);
Long curr_time = System.currentTimeMillis()/1000;
System.out.println("time before: " +time);
System.out.println("time current: " +curr_time);
Long interval = curr_time - time;
System.out.println("interval: " +interval);
if (interval>10) {
status = TokenGenerator(context);
}else {
status = 2;
}
//}
return status;
}
}
and this is a function to request new token from the same class
public synchronized Integer TokenGenerator(Context context) {
int status = 0;
SharedPreferences sharedPrefs = context.getSharedPreferences(TOKEN_STORAGE, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
try {
rclient.AddJSON("app_id", uniqueID);
rclient.CompileJSON();
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
status = rclient.Execute("POST");
} catch (Exception e) {
e.printStackTrace();
}
if (status==1) {
String response = rclient.getResponse();
String token = null;
System.out.println("uuid_response: " +response);
try {
JSONObject json = new JSONObject(response);
token = json.getString("result");
} catch (JSONException e) {
e.printStackTrace();
}
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
System.out.println("time: " +ts);
Editor editor = sharedPrefs.edit();
editor.putString(TIMESTAMP, ts);
editor.putString(TOKEN_ID, token);
editor.commit();
}
return status;
}
so basically the rest client class called two times, first at class token handler to request a new token, and second from the activity itself
As per the code posted by you, I think rclient.Execute("POST") is used to get the data. But the below piece of code
if (token_expired==1 || token_expired==2) {
//function to call another web service and get a data from it
status = rclient.Execute("POST");
}
says that if the token is still alive you are trying to get the new token again.
I think the line status = rclient.Execute("POST"); should be replaced with the code to fetch the data from the server.
problem solved after i put constructor of rest client class in function