Getting error while calling library jar file in j2me - java-me

I have created a login page with webservice in j2me. But while running I am getting error. Can anyone please help? My code is:
public class Login extends MIDlet implements CommandListener {
//the main form
Form mainForm = null;
//the text-boxes for the input
TextField txtBoxA = null;
TextField txtBoxB = null;
//the result label
//the Exit command
Command cmdExit = null;
Command cmdAdd = null;
//the Display reference
Display display = null;
public Login() {
{
//construct the main form
mainForm = new Form("kSOAP Example");
//construct the controls
txtBoxA = new TextField("UserName:", null, 50, TextField.ANY);
txtBoxB = new TextField("Password:", null, 50, TextField.ANY);
// result = new StringItem("Result:", null);
//add controls to the form
mainForm.append(txtBoxA);
mainForm.append(txtBoxB);
// mainForm.append(result);
//construct commands
cmdExit = new Command("Exit", Command.EXIT, 1);
cmdAdd = new Command("Add", Command.SCREEN, 1);
//add commands
mainForm.addCommand(cmdAdd);
mainForm.addCommand(cmdExit);
}
}
public void startApp() {
if (display == null) {
display = Display.getDisplay(this);
}
//display the main form
display.setCurrent(mainForm);
//register the command listener
mainForm.setCommandListener(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.destroyApp(false);
this.notifyDestroyed();
} else if (c == cmdAdd) {
//callWebServiceMethod();
Library lib=new Library();
lib.init();
}
}
my jar file coding is library.jar
public class Library {
String METHOD_NAME = "ValidateLogin_M";
String SOAP_ACTION ="http://64.244.69.235:81/MobileApp/ValidateLogin_M";
String NAMESPACE ="http://64.244.69.235:81/MobileApp/";
String URL ="http://64.244.69.235:81/MobileApp/service1.asmx";
public Library() {
// TODO Auto-generated constructor stub
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Library lib=new Library();
lib.init();
}
public void init()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String user= "gsrtestnew#gmail.com";
String password= "123456";
request.addProperty("UserID",user);
request.addProperty("Password",password);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransport j2meHttpTransport = new HttpTransport(URL);
try {
j2meHttpTransport.call(SOAP_ACTION, envelope);
SoapObject content = (SoapObject) envelope.bodyIn;
String sum = content.getProperty(0).toString();
// result.setText(sum);
System.out.println("##########"+sum);
JSONArray jsonobj = new JSONArray(sum.toString());
System.out.println("Json obj length:: " + jsonobj.length());
if(jsonobj.length() == 0)
{
}
for(int i=0; i<jsonobj.length(); i++)
{
JSONObject jobj = jsonobj.getJSONObject(i);
String CustID = jobj.getString("CustID");
System.out.println("CustID is :: "+CustID);
String Email = jobj.getString("Email");
System.out.println("Email is :: "+Email);
String FirstName = jobj.getString("FirstName");
System.out.println("FirstName is :: "+FirstName);
String LastName = jobj.getString("LastName");
System.out.println("LastName is :: "+LastName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have imported the jar file and called as Library class. But still I am getting error.
My error is
Starting emulator in execution mode
Installing suite from: http://127.0.0.1:49412/WebApplication.jad
TRACE: <at java.lang.Error: ClassFormatError: 56>, Exception caught in Display class
java.lang.Error: ClassFormatError: 56
at com.web.application.Login.commandAction(Login.java:95)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.commandSelected(), bci=11
at com.sun.midp.chameleon.layers.MenuLayer.pointerInput(), bci=170
at com.sun.midp.chameleon.CWindow.pointerInput(), bci=76
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handlePointerEvent(), bci=19
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=296
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)

This has already been answered - jvm cannot load a class due to difference in version - cf - ClassFormatError: 56 while using hessian in j2me
Recompile with
javac -target 1.4 ...

Related

Download File using download manager and save file based on click

I have my download manager, and it work perfect if I try to download a file. But I have a problem.
I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.
Here is the code to call the download function
cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R1Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
and here is the download function
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pDialogDL.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialogDL.setIndeterminate(false);
pDialogDL.setMax(100);
pDialogDL.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
pDialogDL.dismiss();
if (result != null)
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
The code work in my app, but the problem is, when I try to add second CardView which is like this
cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R2Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
Yes it will download the second file, but it will overwrite the first file. I think the problem is right here
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
Anyone can help me with this code?
I need your help, Thanks
Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again
thanks

J2ME http post error - Nokia Asha SDK 1.0

I am making a http-post request from my J2ME app for Nokia Asha 501(s40). I'm using the Nokia Asha SDK 1.0 for development.
Once the app tries to make http connection it goes directly into the finally clause of try-catch statement without throwing any exceptions.
In the emulator, the following message is displayed - "Something went wrong with running this app" - Screenshot-link
I then tried the sample http-post source code given in the Nokia developer forum and got the same result.
The code is given below.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpPOST extends MIDlet implements CommandListener {
private static String defaultURL = "http://localhost/api/signin";
private Display myDisplay = null;
private Form mainScreen;
private TextField requestField;
private Form resultScreen;
private StringItem resultField;
Command sendCommand = new Command("SEND", Command.OK, 1);
Command backCommand = new Command("BACK", Command.OK, 1);
public HttpPOST()
{
myDisplay = Display.getDisplay(this);
mainScreen = new Form("Type in a URL:");
requestField = new TextField(null, defaultURL, 100, TextField.URL);
mainScreen.append(requestField);
mainScreen.addCommand(sendCommand);
mainScreen.setCommandListener(this);
}
public void startApp() {myDisplay.setCurrent(mainScreen);}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s)
{
if (c == sendCommand)
{
String urlstring = requestField.getString();
String resultstring = sendPostRequest(urlstring);
resultScreen = new Form("POST Result:");
resultField = new StringItem(null, resultstring);
resultScreen.append(resultField);
resultScreen.addCommand(backCommand);
resultScreen.setCommandListener(this);
myDisplay.setCurrent(resultScreen);
}
else if (c == backCommand)
{
requestField.setString(defaultURL);
myDisplay.setCurrent(mainScreen);
}
}
public String sendPostRequest(String urlstring)
{
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
String message = "";
String requeststring = "email=test#gmail.com&password=1234";
try
{
hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
dos = hc.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// flush outdos.flush();
dis = new DataInputStream(hc.openInputStream());
int ch;
while ((ch = dis.read()) != -1)
{
message = message + (char) ch;
}
}
catch (IOException ioe)
{
message = "ERROR";
}
finally
{
try
{
if (hc != null)
hc.close();
}
catch (IOException ignored)
{
}
try
{
if (dis != null)
dis.close();
}
catch (IOException ignored)
{
}
try
{
if (dos != null)
dos.close();
}
catch (IOException ignored)
{
}
}
return message;
}
}
Somebody please help me out in solving this issue.
Thanks in advance.
Please find below an example. It will helpful to somebody. It is tested in Nokia Asha 501, It is perfectly working.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class GetNpost extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // The main form
private Alert alError; // Alert to error message
private Command cmGET; // Request method GET
private Command cmPOST; // Request method Post
private Command cmExit; // Command to exit the MIDlet
private TextField tfAcct; // Get account number
private TextField tfPwd; // Get password
private StringItem siBalance;// Show account balance
private String errorMsg = null;
GetNetworkConnection getObject = null;
PostNetworkConnection postObject = null;
GetNpost mainObject = null;
public GetNpost()
{
display = Display.getDisplay(this);
mainObject = this;
// Create commands
cmGET = new Command("GET", Command.SCREEN, 2);
cmPOST = new Command("POST", Command.SCREEN, 3);
cmExit = new Command("Exit", Command.EXIT, 1);
// Textfields
tfAcct = new TextField("Account:", "", 5, TextField.NUMERIC);
tfPwd = new TextField("Password:", "", 10, TextField.ANY | TextField.PASSWORD);
// Balance string item
siBalance = new StringItem("Balance: $", "");
// Create Form, add commands & componenets, listen for events
fmMain = new Form("Account Information");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmGET);
fmMain.addCommand(cmPOST);
fmMain.append(tfAcct);
fmMain.append(tfPwd);
fmMain.append(siBalance);
fmMain.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmGET || c == cmPOST)
{
try
{
if (c == cmGET){
getObject = new GetNetworkConnection();
getObject.start();
}
else{
postObject = new PostNetworkConnection();
postObject.start();
}
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
/*--------------------------------------------------
* Access servlet using GET
*-------------------------------------------------*/
private void lookupBalance_withGET() throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed at the end of url for GET
// don't use localhost as a ip
String url = "http://(ip address):(port)/ServerSide/hello" + "?" +
"account=" + tfAcct.getString() + "&" +
"password=" + tfPwd.getString();
try
{
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// 2) Send header information - none
// 3) Send body/data - data is at the end of URL
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}
/*--------------------------------------------------
* Access servlet using POST
*-------------------------------------------------*/
private void lookupBalance_withPOST() throws IOException
{
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed as a separate stream for POST (below)
// don't use localhost as a ip
String url = "http://(ip address):(port)/ServerSide/hello";
try
{
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request type
http.setRequestMethod(HttpConnection.POST);
// 2) Send header information. Required for POST to work!
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
oStrm = http.openOutputStream();
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");
// 3) Send data/body
// Write account number
byte data[] = ("account=" + tfAcct.getString()).getBytes();
oStrm.write(data);
// Write password
data = ("&password=" + tfPwd.getString()).getBytes();
oStrm.write(data);
// For 1.0.3 remove flush command
// See the note at the bottom of this file
// oStrm.flush();
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
catch(Exception e){
System.out.println("Error in Post: "+e.getMessage());
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}
/*--------------------------------------------------
* Process a response from a server
*-------------------------------------------------*/
private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException
{
//Reset error message
errorMsg = null;
// 1) Get status Line
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
// 2) Get header information - none
// 3) Get body (data)
int length = (int) http.getLength();
String str;
if (length != -1)
{
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
// Update the string item on the display
siBalance.setText(str);
return true;
}
else
// Use message from the servlet
errorMsg = new String( http.getResponseMessage());
return false;
}
/*--------------------------------------------------
* Show an Alert
*-------------------------------------------------*/
private void showAlert(String msg)
{
// Create Alert, use message returned from servlet
alError = new Alert("Error", msg, null, AlertType.ERROR);
// Set Alert to type Modal
alError.setTimeout(Alert.FOREVER);
// Display the Alert. Once dismissed, display the form
display.setCurrent(alError, fmMain);
}
public class GetNetworkConnection extends Thread{
public void run(){
try {
mainObject.lookupBalance_withGET();
}
catch(Exception e){
System.out.println("Error in Get Connection: "+e.getMessage());
}
}
}
public class PostNetworkConnection extends Thread{
public void run(){
try {
mainObject.lookupBalance_withPOST();
}
catch(Exception e){
System.out.println("Error in Post Connection: "+e.getMessage());
}
}
}
}
The server side code is, (It is a servlet. Name is hello.java)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author thirumalvalavan
*/
#WebServlet(name = "hello", urlPatterns = {"/hello"})
public class hello extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// /*TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet hello</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet hello at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
// */
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String acct = request.getParameter("account"),
pwd = request.getParameter("password");
System.out.println("Hello Get Method::: " + acct + " " + pwd);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet hello</title>");
out.println("</head>");
out.println("<body>");
out.print("<h1>Hi Get Method: </h1> <br> <h2> Your Account is: " + acct + "<br> Your pwd is: " + pwd + "</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String acct = request.getParameter("account"),
pwd = request.getParameter("password");
System.out.println("Hello Post Method::: " + acct + " " + pwd);
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet hello</title>");
out.println("</head>");
out.println("<body>");
out.print("<h1>Hi Post Method: </h1> <br> <h2> Your Account is: " + acct + "<br> Your pwd is: " + pwd + "</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

the specified child already has a parent .you must call removeView()

For some reason, I keep receiving the following error:
java.lang.IllegalStateException: the specified child already has a parent. You must call removeView() on the child's parent view
I am using the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listitem);
//url is fetched from another class
readWebpage(imdbUrl);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
}
#Override
protected void onPostExecute(String result) {
//textView.setText(result);
displayMoviesList(result);
}
}
public void readWebpage(String imdbUrl) {
}
public void displayMoviesList(String result) {
JSONObject responseObj = null;
try {
responseObj = new JSONObject(result);
JSONObject Obj = responseObj.getJSONObject("results");
JSONArray moviesListObj = Obj.getJSONArray("result");
for(int i=0 ;i<moviesListObj.length();i++) {
JSONObject e = moviesListObj.getJSONObject(i);
cover[i] = e.getString("cover");
title[i] = e.getString("title");
year[i] = e.getString("year");
director[i] = e.getString("director");
rating[i] = e.getString("rating");
details[i] = e.getString("details");
}
tl = (TableLayout) findViewById(R.id.main_table);
imgView = (ImageView)findViewById(R.id.imageID);
progressbar = (ProgressBar) findViewById(R.id.loadingBar);
//new loadImageTask().execute(cover[i].toString());
new loadImageTask().execute( URL);// it calls another function..
TextView title = (TextView)findViewById(R.id.titleID);
title.setText("TEXT");
TableRow tr = new TableRow(this);
tr.addView(imgView);
tr.addView(title);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
} catch(JSONException e) {
//Log.e("log_tag", "Error parsing data " + e.toString());
}
I am not sure why I'm receiving the error, but it appears to be being generated while I am adding it to the view.
Solution is that we either we define the rows in .xml file or in our .java file. I was adding the rows dynamically in my java file and using addView. So in .xml file we cannot add another view (we should not add rows for the same).

Multithreading and file I/O , ThreadLocal issues

I have this base class structure:
Base:
public abstract class BackgroundTask
{
protected readonly Logger Logger = LogManager.GetCurrentClassLogger();
protected virtual void Initialize()
{
// initialize database access
}
public void Run()
{
Initialize();
try
{
Execute();
// insert to database or whatever
}
catch (Exception ex)
{
Logger.ErrorException(string.Format("Error proccesing task: {0}\r\n", ToString()), ex);
Exceptions.Add(ex);
}
finally
{
TaskExecuter.Discard();
}
}
protected abstract void Execute();
public abstract override string ToString();
public IList<Exception> Exceptions = new List<Exception>();
}
Task executor:
public static class TaskExecuter
{
private static readonly ThreadLocal<IList<BackgroundTask>> TasksToExecute
= new ThreadLocal<IList<BackgroundTask>>(() => new List<BackgroundTask>());
public static void ExecuteLater(BackgroundTask task)
{
TasksToExecute.Value.Add(task);
}
public static void StartExecuting()
{
foreach (var backgroundTask in TasksToExecute.Value)
{
Task.Factory.StartNew(backgroundTask.Run);
}
}
public static void Discard()
{
TasksToExecute.Value.Clear();
TasksToExecute.Dispose();
}
}
FileTask:
public class FileTask : BackgroundTask
{
protected static string BaseFolder = #"C:\ASCII\";
private static readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();
private readonly string _folder;
private IHistoryRepository _historyRepository;
public string Folder
{
get { return _folder; }
}
public FileTask(string folder)
{
_folder = string.Format("{0}{1}", BaseFolder, folder);
}
protected override void Initialize()
{
_historyRepository = new HistoryRepository();
}
protected override void Execute()
{
// todo: Get institute that are active,
var institute = MockInstitute(); // todo: uncomment _historyRepository.FindInstituteByFolderName(Folder);
// todo: Update institute, lastupdate - [date] | [files amount] | [phonenumbers amount]
if (institute == null)
{
Logger.Warn("Not found data", Folder);
return;
}
// todo: read file get encoding | type and parse it
Task.Factory.StartNew(ReadFile);
}
private void ReadFile()
{
var list = GetFilesByFolder();
StreamReader sr = null;
try
{
Lock.EnterReadLock();
foreach (var fi in list)
{
var fileName = fi.FullName;
Logger.Info("Line: {0}:=> Content: {1}", fileName, Thread.CurrentThread.ManagedThreadId);
sr = new StreamReader(fileName, DetectEncoding(fileName));
string currentLine;
while ((currentLine = sr.ReadLine()).ReturnSuccess())
{
if (string.IsNullOrEmpty(currentLine)) continue;
Logger.Info("Line: {0}:=> Content: {1}", fileName, currentLine);
}
}
Lock.ExitReadLock();
}
finally
{
if (sr != null) sr.Dispose();
Logger.Info("Finished working" + Folder);
}
}
protected IEnumerable<FileInfo> GetFilesByFolder()
{
return Directory.GetFiles(Folder).Select(fileName => new FileInfo(fileName));
}
protected Encoding DetectEncoding(string file)
{
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
var cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
return cdet.With(x => x.Charset)
.Return(x => Encoding.GetEncoding(cdet.Charset),
Encoding.GetEncoding("windows-1255"));
}
}
private Institute MockInstitute()
{
return new Institute
{
FromFolderLocation = string.Format("{0}{1}", BaseFolder, Folder)
};
}
public override string ToString()
{
return string.Format("Folder: {0}", Folder);
}
}
When don't read the file every thing ok, the Log is populated and every thing runs smooth,
but when i attach the Task.Factory.StartNew(ReadFile); method i have an exception.
Exception:
Cannot access a disposed object.
Object name: 'The ThreadLocal object has been disposed.'.
How do i solve that issue? might i need to change the LocalThread logic, or what - i have been trying to handle that issue, for almost a day.
BTW: It's an MVC4 project, and C# 5.0 and i'm trying to TDD it all.
You shouldn't be calling TasksToExecute.Dispose();
there.

How to use the return value of call method of Task class in Javafx

I am using Task class to run background task in javafx application to fetch the data from the database.
public class CustomTask extends Task<ObservableList<ObservableList>> {
TableView tableview;
ObservableList<ObservableList> data;
public CustomTask(TableView tableview) {
this.tableview = tableview;
}
#Override
protected ObservableList<ObservableList> call() throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String SQL = "SELECT * from sell where Date='" + dateFormat.format(date) + "'";
ResultSet rs = DBConnect.getResultSet(SQL);
data = DBConnect.generateListDateFromTable(rs, true);
return data;
}
}
How to use the data object.
Example 1 addEventHandler
MyResultObjectType result;
CustomTask task = new CustomTask();
task.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED,
new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
result = task.getValue();
}
});
Example 2 setOnSucceeded
MyResultObjectType result;
CustomTask task = new CustomTask();
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
result = task.getValue();
}
});
Example 3 addListener
task.valueProperty().addListener(new ChangeListener<Task>() {
#Override
public void changed(ObservableValue<? extends mytype> obs,
mytype oldValue, mytype newValue) {
if (newValue != null) {
System.out.println("Result = " + newValue);
}
}
});
Bind to the Task's value property OR provide a task.setOnSucceeded() event handler and call task.getValue() in the provided event handler.

Resources