i am trying to cancel an async task after a period of time. i have searched and found a lot of questions about this and all having the same answer like what i am doing below.
problem: after calling cancel, the webservice does not seem to cancel because it never reaches the onPostExecute.
please any help will be appreciated.
what i have tried:
after a certain period of time i call
class TimeOut that takes an asyncTask as its argument and performs the below:
if (task.getStatus() == AsyncTask.Status.RUNNING )
{task.cancel(true);}
if(task.isCancelled()==true)
{
Log.e(TAG,"TASK IS CANCELLED");
}
and in my async class
#Override
protected void onCancelled() {
webServiceError=true; //when timeout change it to true.(default false)
Toast.makeText(context, R.string.webserviceDownloadUserDataError, Toast.LENGTH_LONG).show();
if (pd.isShowing()) {
pd.dismiss();
}
super.onCancelled();
}
#Override
protected String doInBackground(String... params) {
int paramsTracker = 0;
webServiceError = false;
while(webServiceError==false) {
HttpClient httpclient = new DefaultHttpClient();
String url = params[paramsTracker];
paramsTracker = paramsTracker + 1;
HttpPost httppost = new HttpPost(url);
int paramsCount = params.length;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(paramsCount);
for (int i = 0; i < (paramsCount - 1) / 2; i++) {
Log.d(TAG, "parameters: " + params[paramsTracker] + " - " + params[paramsTracker + 1]);
nameValuePairs.add(new BasicNameValuePair(params[paramsTracker], params[paramsTracker + 1]));
paramsTracker = paramsTracker + 2;
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute http post request, call web service
response = httpclient.execute(httppost);
}
catch (Exception e) {
webServiceError = true;
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error in calling web service " + e.toString(), LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
if (webServiceError == false) {
int CNT = 0;
try {
String query = "SELECT COUNT(*) AS CNT FROM TASKS";
Cursor cursor = MainActivity.myDataBase.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
CNT = Integer.parseInt(cursor.getString(cursor.getColumnIndex("CNT")));
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error in Database error getting task count " + e.toString(), LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
if (CNT == 0) {
String webServiceResponse = "";
try {
Log.d(TAG, "Getting web service response");
// get web service response
HttpEntity entity = response.getEntity();
String content;
content = EntityUtils.toString(entity);
// Log.d(TAG, "content: "+ content);
// parse XML response
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(content));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("string");
Element line = (Element) nodes.item(0);
webServiceResponse = getCharacterDataFromElement(line);
String patternForON = "SET IDENTITY_INSERT \\[.*?\\] O?((N)|(FF))\\s*?;";
Pattern rForON = Pattern.compile(patternForON);
Matcher mForON = rForON.matcher(webServiceResponse);
String webServiceResponseWithOutIdentityInsert = mForON.replaceAll("");
String patternForInsert = "\\bINSERT (?!INTO)";
Pattern rForInsert = Pattern.compile(patternForInsert);
Matcher mForInsert = rForInsert.matcher(webServiceResponseWithOutIdentityInsert);
String webServiceResponseWITHOUTINSERTALONE = mForInsert.replaceAll("INSERT INTO ");
String webServiceResponsePURIFIED = webServiceResponseWITHOUTINSERTALONE.replaceAll(";;", ";");
Log.d(TAG, "content: " + webServiceResponsePURIFIED);
///////////END OF for removing queries that are not applicable in SQLITE
//FOR SPLITTING THE QUERIES AND PLACING EACH AT AN INDEX IN contentArray ARRAY
//String contentArray [] = webServiceResponse.split(";");
String contentArray[] = webServiceResponsePURIFIED.split(";");
Log.d(TAG, "contentArray length" + contentArray.length + ""); //GETS THE NUMBER OF QUERIES
pd.setMax(contentArray.length); //SETTING THE PROGRESS DIALOG (MAX PROGRESS)
for (int i = 0; i < contentArray.length; i++) {
// add the downloaded data to the local database
String query = contentArray[i];
try {
AppLogging(TAG, "Queries Downloaded splitted and purified\n query " + i + " :" + contentArray[i], LogFileName.LogFilename);
} catch (Exception l) {
}
Log.d(TAG, "query: " + query);
// if query contains "getdate()" replace with DATETIME('now'), to render the query executable in sqlite
query = query.replace("GETDATE()", "DATETIME('now')");
try {
MainActivity.myDataBase.execSQL(query); //EXECUTE QUERY
} catch (Exception e) {
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error in performing query: " + query + "\nError: " + e, LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
//Log.d("Initialize database, HTTPRequestGetUserData ", query);
publishProgress();
}
} catch (Exception e) {
webServiceError = true;
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error: " + e.toString(), LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
}
}
if (isCancelled()) return "0";
}
return "1";
}
As per Android AsyncTask documents, after calling cancel() on AsyncTask it won't call onPostExecute() instead it will call onCancelled(). So the flow is desired.
Now as per documentation here in, your code
#Override
protected String doInBackground(String... params) {
while(webServiceError=false) {
.....//calling webservice
if (isCancelled()) return "0";
}
return "1";
}
And now your onCancelled() looks like, with String parameters
#Override
protected void onCancelled(String object) { // Here object should be 0
webServiceError=true; //when timeout change it to true.(default false)
Toast.makeText(context, R.string.webserviceDownloadUserDataError, Toast.LENGTH_LONG).show();
if (pd.isShowing()) {
pd.dismiss();
}
super.onCancelled();
}
Now in this method argument object will be 0. And don't worry both methods onPostExecute() and onCancelled() will run on Main UI thread.
Now what I suggest you is, create a private method which you want to execute from onPostExecute() and onCancelled() with String parameters.
When you cancel a AsyncTask it will never hit the OnPostExecute procedure. It is mentioned here in the API Doc:
http://developer.android.com/reference/android/os/AsyncTask.html
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
Related
View Gujarati Character Using Web Service in Android JSON Parsing
I Got Gujarati Word Like the one in the images I've included. If Gujarati Word is presented like અપૂર્વ, then it appears like the 1st rounded circle in the image.
Please help me to find a solution to this question
Image For Getting Gujarati Word Like this can be seen below:
And here is my code :
public class GetProductData extends AsyncTask<String, String, JSONObject> {
//private ProgressDialog p_dialog;
JSONArray jArray;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*p_dialog = new ProgressDialog(con);
p_dialog.setMessage("Please Wait ...");
p_dialog.setIndeterminate(false);
p_dialog.setCancelable(false);
p_dialog.show();*/
}
#Override
protected JSONObject doInBackground(String... params) {
jArray = JSONParser.GetProductData();
Log.d("TAG", "JSON ARRAY FOR DEVICE ID : " + jArray);
String msg = "Nothing Happened...";
try {
if (jArray != null) {
Key = jArray.getJSONObject(0).getString("Key").toString();
if (Key.equals("1")) {
db.deleteAllProductDetails();
for (int i = 1; i < jArray.length(); i++) {
Log.d("ADADADADTAG","CategoryName ::: "+jArray.getJSONObject(i).getString("CategoryName"));
Log.d("ADADADADTAG","SubCategoryName ::: "+jArray.getJSONObject(i).getString("SubCategoryName").trim());
Log.d("ADADADADTAG","ProductName ::: "+jArray.getJSONObject(i).getString("ProductName"));
db.insertProductDetails(
jArray.getJSONObject(i).getString("ProductId").trim(),
jArray.getJSONObject(i).getString("CategoryId").trim(),
jArray.getJSONObject(i).getString("CategoryName").trim(),
jArray.getJSONObject(i).getString("CategoryImageUrl").trim(),
jArray.getJSONObject(i).getString("SubCategoryId").trim(),
jArray.getJSONObject(i).getString("SubCategoryName").trim(),
jArray.getJSONObject(i).getString("SubCategoryImageUrl").trim(),
jArray.getJSONObject(i).getString("ProductName").trim(),
jArray.getJSONObject(i).getString("ProductImageUrl").trim(),
jArray.getJSONObject(i).getString("ProductCode").trim(),
jArray.getJSONObject(i).getString("ProductPrice").trim(),
jArray.getJSONObject(i).getString("ProductUnit").trim(),
jArray.getJSONObject(i).getString("ProductSmallDesc").trim(),
jArray.getJSONObject(i).getString("CategoryStatus").trim(),
jArray.getJSONObject(i).getString("SubCategoryStatus").trim(),
jArray.getJSONObject(i).getString("ProductStatus").trim()
);
}
}
} else {
}
} catch (Exception e) {
// TODO: handle exception
Log.e("TAG", "Warn :" + e.getLocalizedMessage());
Log.e("TAG", "Warn :" + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
super.onPostExecute(json);
// p_dialog.dismiss();
if (jArray != null) {
if (Key.equals("1")) {
Cursor cGetAllProductDetails = db.getAllProductDetails();
//Toast.makeText(con,"Count ::: "+cGetAllProductDetails.getCount(),Toast.LENGTH_LONG).show();
preferences = con.getSharedPreferences(IsLogin,Context.MODE_PRIVATE);
if(preferences.getBoolean(IsLogin,false))
{
Intent i = new Intent(con, DashboardActivityEnglishWithLogin.class);
startActivity(i);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finish();
}
else
{
Intent i = new Intent(con, DashboardActivityEnglishWithoutLogin.class);
startActivity(i);
overridePendingTransition(R.anim.left_in, R.anim.left_out);
finish();
}
} else if (Key.equals("0")) {
} else {
}
}
}
}
public static JSONArray GetProductData() {
// TODO Auto-generated method stub
try
{
init();
url = SITE_URL + "GetProductData";
Log.d("TAG", url);
httpPost = new HttpPost(url.toString());
Log.d("TAG", "HTTP POST"+httpPost);
pairs = new ArrayList<NameValuePair>();
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
Log.d("TAG", "HTTP POST"+httpPost);
httpResponse = httpClient.execute(httpPost);
Log.d("TAG", "HTTP RESPONSE"+httpResponse);
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
/* Convert response to string */
result = getResult(inputStream);
Log.d("TAG","RESULT : "+ result);
jsonArray = new JSONArray(result);
Log.d("TAG", "JSON ARRAY : "+ jsonArray);
} catch (ClientProtocolException e) {
Log.e("TAG", "Error in Client Protocol : " + e.toString());
} catch (JSONException e) {
Log.e("TAG", "Error Parsing data " + e.toString());
} catch (Exception e) {
Log.e("TAG", "Error in HTTP Connection : " + e.toString());
}
return jsonArray;
}
Parse Json data using URLDecoder,
URLDecoder.decode(jArray.getJSONObject(i).getString("CategoryName"), "utf-8");
Try this
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://floming.com/shayri/guj_romanse.json", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();
I have a running async task in my android application which runs perfectly. However I would like to know if it possible to return a string value from the asynctask in android as well as update a UI item. I want to update to a rating stars in the UI update and return a list of information from my server (which is working now).
Is it possible to return a value and update a UI from one asynctask in android??
Code for my Asynctask is below:
public class ConnectToServer extends AsyncTask< String, String, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... params)
{
Socket client;
DataInputStream input;
DataOutputStream output;
String results = "";
XMLCreator x = new XMLCreator();
ArrayList<String> lists = new ArrayList<String>();
try
{
Log.i("CLIENT", "Client started");
// Step 1: Create a Socket to make connection.
// client = new Socket(InetAddress.getLocalHost(), 500);
client = new Socket("*****", 5001);
Log.i("CLIENT", "Connected to: "
+ client.getInetAddress().getHostName());
publishProgress("Connected...");
// Step 2: Get the input and output streams.
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
Log.i("CLIENT", "Got I/O Streams");
publishProgress("Obtained Streams...");
// Step 3: Process connection.
//Read in the value that the user selected from the bundle
String Day = params[0].toString();
//put into XML document as a query
//create a string
Document doc;
try
{
//Create an XML document with tutor's student number
doc = x.createDoc();
Element tutor = doc.createElement("Query");
tutor.appendChild(x.createDayforSession(doc, "GetSessionByDay", Day));
doc.appendChild(tutor);
//Create a string
String s = x.getStringFromDocument(doc);
output.writeUTF(s);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
publishProgress("Processing");
//Get all the session information for that day in XML string
//Create a document
//Break it up and add it to the view
results = input.readUTF();
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(results)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Result"))
{
//Any methods which need to be called that will be used to query the database
//Always sending the String XML through as a parameter
//Look at the child node
NodeList nList = document.getElementsByTagName("Query");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
String Semester = eElement.getElementsByTagName("Semester").item(0).getTextContent();
String StartTime = eElement.getElementsByTagName("StartTime").item(0).getTextContent();
String Days = eElement.getElementsByTagName("Day").item(0).getTextContent();
String Lab = eElement.getElementsByTagName("Lab").item(0).getTextContent();
String session = "Semester: " + Semester + "\n" + "StartTime: " + StartTime + "\n" + "Days: " + Days + "\n" + "Lab: " + Lab + "\n";
lists.add(session);
}
}
}
}
catch (Exception e)
{
e.getMessage();
}
// Step 4: Close connection.
Log.i("CLIENT", "Transmission complete. "
+ "Closing connection.");
output.writeUTF("TERMINATE");
client.close();
publishProgress("Closed connection...");
} catch (IOException e) {
e.printStackTrace();
}
return lists;
}
#Override
protected void onPostExecute(ArrayList<String> lists)
{
super.onPostExecute(lists);
//UPDATE A STAR RATING HERE
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
}
}
You cannot return a value. But you can update the UI in onPostExecute(). Remove all super calls in your asynctask.
you should override onPostExecute!! you can access your UI from this function and the inputs of this function is the result of doInBackground!!
This issue I am having is that my program can only send my string over TCP once through a AsyncTask. I have read that the AsyncTask can only run once and that after it runs it is supposed to be disposed and that if I need to send another command I should create another instance of the thread and use the new instance to send the new command. However for whatever reason when I attempt to create a second instance of my AsyncTask nothing happens. Something of note. I added a log command in the onPostExecute routine but I never see the log message.
I have the following in my Android-Manifest file:
<uses-permission android:name="android.permission.INTERNET/>
This is the code in the main activity thread that calls the async task.
public void SendCommand(int DeviceID, String DeviceName, String CommandName)
{
//Get the IP address and the port in order to communicate with the device
DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String dbQuery = "SELECT * FROM " + dbHelper.System_Table + ", " + dbHelper.Devices_Table + ", " +
dbHelper.Device_Commands_Table + " WHERE " + dbHelper.System_Table + "." + dbHelper.Attribute_Device_ID +
" = " + String.valueOf(DeviceID) + " AND " + dbHelper.Devices_Table + "." + dbHelper.Attribute_Device_ID +
" = " + String.valueOf(DeviceID) + " AND " + dbHelper.Device_Commands_Table + "." + dbHelper.Attribute_Device_ID +
" = " + String.valueOf(DeviceID) + ";";
Cursor c = db.rawQuery(dbQuery, null);
String IPAddress = "";
int Port = 0;
String DeviceCommand = "";
if (c.getCount() > 0)
{
int Finished = 0;
while (c.moveToNext() && Finished == 0)
{
int iColumnDeviceName = c.getColumnIndex(dbHelper.Attribute_Device_Name);
int iColumnDeviceCommandName = c.getColumnIndex(dbHelper.Attribute_Command_Name);
final String CheckDeviceName = c.getString(iColumnDeviceName);
final String CheckCommandName = c.getString(iColumnDeviceCommandName);
if (DeviceName.equals(CheckDeviceName) && CheckCommandName.equals(CommandName))
{
Finished = 1;
int iColumnIPAddress = c.getColumnIndex(dbHelper.Attribute_Device_IP);
int iColumnPort = c.getColumnIndex(dbHelper.Attribute_Device_Port);
int iColumnDeviceCommandString = c.getColumnIndex(dbHelper.Attribute_Command_String);
IPAddress = c.getString(iColumnIPAddress);
Port = c.getInt(iColumnPort);
DeviceCommand = c.getString(iColumnDeviceCommandString);
DeviceCommand = DeviceCommand.replace("<CR>", "\r");
Log.d("Device Command To Send", DeviceCommand);
}
}
c.close();
dbHelper.close();
ArrayList<String> passing = new ArrayList<String>();
ArrayList<String> result = new ArrayList<String>();
passing.add(IPAddress);
passing.add(String.valueOf(Port));
passing.add(DeviceCommand);
SendCommand SC = new SendCommand();
SC.execute(passing, result);
}
}
This is the seperate class file that the above routine creates a instance of and executes.
public class SendCommand extends AsyncTask<ArrayList<String>, Void, ArrayList<String>>
{
#Override
protected void onPreExecute()
{
//progress bar
}
#Override
protected ArrayList<String> doInBackground(ArrayList<String>... passing)
{
Log.d("Async Task", "Started to send command.");
//Get the connection info and command to send from the caller
String Data = passing[0].toString();
int StopAt = Data.indexOf(",");
String IPAddress = Data.toString().substring(1, StopAt);
Data = Data.replace("[" + IPAddress + ", ", "");
StopAt = Data.indexOf(",");
int Port = Integer.parseInt(Data.toString().substring(0, StopAt));
Data = Data.replace(Port + ", ", "");
StopAt = Data.indexOf("]");
String DeviceCommand = Data.toString().substring(0, StopAt);
Send_Command(IPAddress, Port, DeviceCommand);
return null;
}
protected void onPostExecute(Long result)
{
Log.d("Async Task", "Command Sent");
}
private void Send_Command(String IPAddress, int Port, String DeviceCommand)
{
//Setup the connection parameters
SocketAddress SA = new InetSocketAddress(IPAddress, Port);
int Timeout = 2000;
Socket socket = new Socket();
try
{
//Attempt to connect to the device
socket.connect(SA, Timeout);
int Count = 0;
int Kill = 0;
while (socket.isConnected() == false && Kill == 1)
{
//Waiting for the connection
Count = Count + 1;
if (Count == Timeout)
{
Kill = 1;
Log.d("Connection Status", "Timed out");
}
}
if (socket.isConnected() == true)
{
//send the command
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(DeviceCommand);
wr.flush();
Log.d("Sent Device Command", DeviceCommand);
//listen for the response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String Response;
while ((Response = rd.readLine()) != null)
{
Log.d("Received Device Response", Response);
}
rd.close();
}
//close the socket once the response is received
socket.close();
}
catch (UnknownHostException e)
{
Log.d("UnknownHostException", "Something bad happened");
}
catch (IOException e)
{
Log.d("IOException", "Something bad happened");
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Finally here is my log after attempting to send two commands over tcp.
01-14 23:53:29.773: D/Device Command To Send(31643): PN
01-14 23:53:29.773: D/Async Task(31643): Started to send command.
01-14 23:53:30.108: D/Sent Device Command(31643): PN
01-14 23:53:30.273: D/Received Device Response(31643): R
01-14 23:53:31.918: D/Device Command To Send(31643): PF
I can see that the first time the AsyncTask is started and it sends the command as well as receives the response from the target device. However I don't see "Async Task", "Command Sent" in the log so the onPostExecute is not executing.
Any thoughts on what I am doing wrong?
Your onPostExecute signature is wrong.
protected void onPostExecute(Long result)
It should be
protected void onPostExecute(ArrayList<String> result)
It might be also good to use #Override annotation.
Put some extra debug messages in your Send_Command, AsyncTask is probably hanging there.
Currently you are not Overriding onPostExecute from AsyncTask so change your onPostExecute signature as :
#Override
protected void onPostExecute(ArrayList<String> result)//<Change Long
// to ArrayList<String>
{
Log.d("Async Task", "Command Sent");
}
I create simple Activity with dynamic table from file CSV.
I'd like to simply show progress bar before file is read and UI build.
I stuck on AsyncTask..
If i execute mytask.get() then the UI building is blocked and my desired progressDialog won't shown.
But if i call mytask.get() then app crashes bacause all my UI depends on that CSV.
I found this:
ProgressDialog not shown when AsyncTask.get() called
with related:
Common class for AsyncTask in Android?
but i can't even imagine how to use that concept in my case..
public void onCreate(Bundle savedInstanceState) {
...
Log.i(TAG, "before csv:");
ReadFromCSV mytask = new ReadFromCSV(this);
mytask.execute(char_name);
// try {
// mytask.get();
// } catch (InterruptedException e1) {
// // TODO Auto-generated catch block
// Log.i(TAG, "1 exception");
// e1.printStackTrace();
// } catch (ExecutionException e1) {
// Log.i(TAG, "2 exception");
// e1.printStackTrace();
// }
Log.i(TAG, "after csv");
// create table from var headers
set_title_with_charname(flipper.get_moves_group(0)); //set activity title
Log.i(TAG, "headers values:" + headers);
heading.create_header(this, headers, 0);
lay.addView(heading);
lay.addView(flipper);
lay.setOrientation(1);
setContentView(lay);
}
here is mytask:
private class ReadFromCSV extends AsyncTask<String, Void, String> {
public Activity activity;
private ProgressDialog Dialog = new ProgressDialog(MovesList.this);
public ReadFromCSV(Activity a) {
activity = a;
}
protected void onPreExecute() {
Log.i(TAG, "start onPreExecute");
Dialog.setMessage("Please wait...");
Dialog.show();
Log.i(TAG, "END onPreExecute");
}
protected String doInBackground(String... urls) {
Log.i(TAG, "doInBackground");
// return loadImageFromNetwork(urls[0]);
String new_val = urls[0] + "doInBack";
Log.i(TAG, "new_val: " + new_val);
try {
readfromcsv(flipper, char_name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(TAG, "END doInBackground");
return new_val;
}
protected void onPostExecute(String result) {
Log.i(TAG, "onpostexecute");
Log.i(TAG, "result: " + result);
try {
if(Dialog.isShowing()) {
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e) {
Log.i(TAG, "exception: ");
}
Log.i(TAG, "END onPostExecute");
}
}
here is a code of readfromcsv:
public void readfromcsv(MyFlipper flipper, String char_name)
throws IOException {
String filename = char_name + ".csv";
InputStream is = getAssets().open(filename);
BufferedReader in = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String reader = "";
int line_nb = 0;
MyTable table = null;
while ((reader = in.readLine()) != null) {
line_nb += 1;
Log.d(TAG, "file line: " + reader);
String[] row_data = reader.split("ą");
Log.d(TAG, "splitted: " + row_data[0] + ',' + row_data[1] + "..");
if (line_nb == 1) {
Log.i(TAG, "first row - memorized headers..");
headers = row_data;
Log.i(TAG, "headers memorized: " + row_data[0] + ","
+ row_data[1] + "..");
continue;
}
if (row_data[0].equals("")) {
// new table
// Log.i(TAG, "new moves_group..");
if (table != null) {
add_table(table);
}
Log.d(TAG, "creating new table");
table = new MyTable(this, true, row_data[1]);
Log.d(TAG, "new table created");
continue;
}
Log.d(TAG, "regular row..");
table.row_from_template(this, row_data, line_nb % 2);
if (line_nb == 60) {
break;
}
;
}
add_table(table);
in.close();
}
I am not sure in you case why you are using get as get
Waits if necessary for the computation to complete, and then retrieves its result.
you can simply do you UI work Asynchronously using onPostExecute.
And Avoid UI related wokr in doInBackground and function called from doInBackground ...
Most likely either your add_table your some code that you are calling from doInBackground is executing some UI functions. Since doInBackground does not happen on the UI thread you can't touch the UI in that function. Instead what you could do is call publishProgress with whatever data you need to display. You can alter the Type that is used by publishProgress through the generic type declaration. The middle one is what is used by publishProgress.
Hi I pass the Data base values into webservices. but it passing only resent entry valules only. I need to pass all rows one by one into JSON.
Can any one help me with sample code.
SQLite in DB
Cursor cursor;
cursor = myDataBase.rawQuery(" SELECT " + VENDORID + " FROM " + VENDORINFO_TABLE
+ " WHERE " + CATEGORYID + " = " + id,null);
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndex(VENDORID));
// your JSON put Code
JSONObject jsMain = new JSONObject();
try {
jsMain.put("email", id);
return jsMain.toString();
} catch (JSONException e) {
e.printStackTrace();
return "";
}
}
cursor.close();
check below code try this way. this is just advice for you.
Cursor cus = db.selectAll_delete();
JSONObject jon1 = new JSONObject();
JSONArray jaa = new JSONArray();
int i = 0;
try {
if (cus.moveToFirst()) {
do {
String a = cus.getString(1);
// Toast.makeText(this, ""+ a,
// Toast.LENGTH_LONG).show();
JSONObject job_get = getData_b(a);
jaa.put(i, job_get);
i++;
} while (cus.moveToNext());
}
jon1.accumulate("details", jaa);
} catch (Exception e) {
// TODO: handle exception
}
if (cus != null && !cus.isClosed()) {
cus.close();
}
String js = jon1.toString();
send_to_server(js);
Log.d("test json", "" + js);
method getData_b();
private JSONObject getData_b(String a) {
// TODO Auto-generated method stub
Cursor cus = db.fetchRow(a);
JSONObject job = new JSONObject();
try {
if (cus.moveToFirst()) {
do {
job.put("B", cus.getInt(1));
job.put("I", cus.getString(2));
job.put("O", cus.getString(3));
job.put("D", cus.getString(4));
job.put("D u", cus.getString(5));
job.put("L", cus.getString(6));
job.put("B", cus.getString(7));
job.put("A", cus.getString(8));
job.put("K", cus.getString(9));
job.put("A", cus.getString(10));
job.put("Time", cus.getString(11));
job.put("Upd", cus.getString(12));
job.put("Deleted", cus.getString(13));
} while (cus.moveToNext());
}
} catch (Exception e) {
// TODO: handle exception
}
return job;
}