hi here is my code i want to call the insert(latitude,longitude) inside the get() but it is not working for me so please help!
public void onStart(Intent intent, int startid){
Toast.makeText(getApplicationContext(),"Service Strated...",Toast.LENGTH_SHORT).show();
device_id = intent.getExtras().getString("device_id");
final int delay = 60000; //milliseconds
h.postDelayed(new Runnable() {
public void run() {
try {
get();
} catch (JSONException e) {
e.printStackTrace();
}
h.postDelayed(this, delay);
}
}, delay);
}
public void get() throws JSONException {
count++;
gps=new GPSTracker(getApplicationContext());
if(gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if (latitude != 0.0 & longitude != 0.0) {
insert(latitude,longitude);
Toast.makeText(getApplicationContext(), "Your Location : \n Lat :" + latitude + "\nLang :" + longitude, Toast.LENGTH_LONG).show();
if(count==5){
send();
count=0;
}
}
}
}
public void insert(double lat,double lon){
System.out.print("hi_entered");
boolean exist = checkIfExist(lat, lon);
System.out.print(exist);
if(!exist) {
System.out.print("INSERT INTO location VALUES(null,'" + lat + "','" + lon + "',null);");
db.execSQL("INSERT INTO location VALUES(null,'" + lat + "','" + lon + "',null);");
}
}
Related
I am quite new to this so please bear with me. I am trying to use a keyword search to pull images from twitter using twitter4j. I want it to show the images positioned randomly on the screen in a loop.
This code I have below is a combination of different ones I have found online. Its currently finding tweets using these keywords and showing them in the console, however, it is not displaying them on the screen and I’m not sure why…
Another thing is that I think it is doing a live stream from twitter so pulling tweets immediately at the time the code is run, so I am not getting lots of results when I put in an obscure keyword, I want it to search for the last 100 tweets with images using the keyword so that I get more results
I’d really appreciate all the help I can get! thank you
///////////////////////////// Config your setup here! ////////////////////////////
// { site, parse token }
String imageService[][] = {
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://twitpic.com",
"<img class=\"photo\" id=\"photo-display\" src=\""
},
{
"http://img.ly",
"<img alt=\"\" id=\"the-image\" src=\""
},
{
"http://lockerz.com/",
"<img id=\"photo\" src=\""
},
{
"http://instagr.am/",
"<meta property=\"og:image\" content=\""
} {
"http://pic.twitter.com",
"<img id
};
// This is where you enter your Oauth info
static String OAuthConsumerKey = KEY_HERE;
static String OAuthConsumerSecret = SECRET_HERE;
static String AccessToken = TOKEN_HERE;
static String AccessTokenSecret = TOKEN_SECRET_HERE;
cb.setIncludeEntitiesEnabled(true);
Twitter twitterInstance = new TwitterFactory(cb.build()).getInstance();
// if you enter keywords here it will filter, otherwise it will sample
String keywords[] = {
"#hashtag" //sample keyword!!!!!!!!
};
///////////////////////////// End Variable Config ////////////////////////////
TwitterStream twitter = new TwitterStreamFactory().getInstance();
PImage img;
boolean imageLoaded;
void setup() {
frameRate(10);
size(800, 600);
noStroke();
imageMode(CENTER);
connectTwitter();
twitter.addListener(listener);
if (keywords.length == 0) twitter.sample();
else twitter.filter(new FilterQuery().track(keywords));
}
void draw() {
background(0);
if (imageLoaded) image(img, width / 5, height / 5);
//image(loadImage((status.getUser().getImage())), (int)random(width*.45), height-(int)random(height*.4));
}
// Initial connection
void connectTwitter() {
twitter.setOAuthConsumer(OAuthConsumerKey, OAuthConsumerSecret);
AccessToken accessToken = loadAccessToken();
twitter.setOAuthAccessToken(accessToken);
}
// Loading up the access token
private static AccessToken loadAccessToken() {
return new AccessToken(AccessToken, AccessTokenSecret);
}
// This listens for new tweet
StatusListener listener = new StatusListener() {
//#Override
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
//#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
//#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
//#Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
//#Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
}
//#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
public void onStatus(Status status) {
String imgUrl = null;
String imgPage = null;
// Checks for images posted using twitter API
if (status.getMediaEntities() != null) {
imgUrl = status.getMediaEntities()[0].getMediaURL().toString();
}
// Checks for images posted using other APIs
else {
if (status.getURLEntities().length > 0) {
if (status.getURLEntities()[0].getExpandedURL() != null) {
imgPage = status.getURLEntities()[0].getExpandedURL().toString();
} else {
if (status.getURLEntities()[0].getDisplayURL() != null) {
imgPage = status.getURLEntities()[0].getDisplayURL().toString();
}
}
}
if (imgPage != null) imgUrl = parseTwitterImg(imgPage);
}
if (imgUrl != null) {
println("found image: " + imgUrl);
// hacks to make image load correctly
if (imgUrl.startsWith("//")) {
println("s3 weirdness");
imgUrl = "http:" + imgUrl;
}
if (!imgUrl.endsWith(".jpg")) {
byte[] imgBytes = loadBytes(imgUrl);
saveBytes("tempImage.jpg", imgBytes);
imgUrl = "tempImage.jpg";
}
println("loading " + imgUrl);
img = loadImage(imgUrl);
imageLoaded = true;
}
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
public void onException(Exception ex) {
ex.printStackTrace();
}
// Twitter doesn't recognize images from other sites as media, so must be parsed manually
// You can add more services at the top if something is missing
String parseTwitterImg(String pageUrl) {
for (int i = 0; i < imageService.length; i++) {
if (pageUrl.startsWith(imageService[i][0])) {
String fullPage = ""; // container for html
String lines[] = loadStrings(pageUrl); // load html into an array, then move to container
for (int j = 0; j < lines.length; j++) {
fullPage += lines[j] + "\n";
}
String[] pieces = split(fullPage, imageService[i][1]);
pieces = split(pieces[1], "\"");
return (pieces[0]);
}
}
return (null);
}
I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}
I'm trying to write down something more sophisticated than simple Fahrenheit to Celsius and vice versa converter. I'm trying to use JoptionPane for better fell but I'm stuck in one place and have no idea how to resolve this (line 32 and 37 - method not applicable for the arguments ()) any help will be appreciated.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class ex74v3 {
public static void main(String[] args) {
temp();
new ex74v3();
}
public ex74v3() {
boolean done=false;
while(!done){
done=true;
String[] ans=new String[11];
String[] choice={
"(°F) to (°C)",
"(°C) to (°F)",
};
int choice_indx=JOptionPane.showOptionDialog(null, "Choose type of conversion", "Choice",
0,JOptionPane.QUESTION_MESSAGE ,
null,choice,0);
ans[0]=choice[choice_indx];
if(choice_indx==1 || choice_indx==2) {
done=false;
}else{
choice_indx=JOptionPane.showMessageDialog(null, "Fahrenheit to Celsius: " + baseFtC() + " (°C)");
}
if(choice_indx==2) {
done=false;
}else{
choice_indx=JOptionPane.showMessageDialog(null, "Celsius to Fahrenheit : " + baseCtF() + " (°F)");
}
}
}
public static int temp() {
String value = JOptionPane.showInputDialog(null, "Enter value ");
#SuppressWarnings("unused")
int log;
return log = Integer.parseInt(value);
}
public int baseCtF(int value) {
int conversion = (int) (temp() * 1.8 + 32);
return conversion;
}
public int baseFtC(int value) {
int conversion = (int) ((temp() - 32) / 1.8);
return conversion;
}
}
Ok, there is an other way, easier, thanks anyway ;]
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ex74v4 {
public static void main(String[] a) {
DecimalFormat digit = new DecimalFormat("0.00");
String value = JOptionPane.showInputDialog(null, "Enter value ");
float log;
log = Float.parseFloat(value);
JFrame frame = new JFrame();
Object stringArray[] = { "Celsius to Fahrenheit", "Fahrenheit to Celsius" };
int reply = JOptionPane.showOptionDialog(frame, "Choose conversion type of value: " + digit.format(log), "MiniConverter",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray,
stringArray[0]);
if (reply == JOptionPane.YES_OPTION) {
DecimalFormat digit2 = new DecimalFormat("0.00");
double conversion = log * 1.8 + 32;
JOptionPane.showMessageDialog(frame, log + " " + "(°C) equals " + digit2.format(conversion) + " (°F)", "MiniConverter", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else {
DecimalFormat digit3 = new DecimalFormat("0.00");
double conversion = (log - 32) / 1.8;
JOptionPane.showMessageDialog(frame, log + " " + "(°F) equals " + digit3.format(conversion) + " (°C)", "MiniConverter", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
I have two applications, sending messages asynchronously in both directions. I am using sockets of type ZMQ.DEALER on both sides. The connection status is additionally controlled by heartbeating.
I have now problems to get the connection reliably recovering after connection problems (line failure or application restart on one side). When I restart the applicaton on the server side (the side doing the bind()), the client side will not always reconnect successfully and then needs to be restarted, especially when the local buffer has reached the HWM limit.
I did not find any other way to make the connection recovery reliable, other than resetting the complete ZMQ.Context in case of heartbeat failures or if send() returned false. I will then call Context.term() and will create Context and Socket again. This seemed to work fine in my tests. But now I observed occasional and hangups inside Context.term(), which are rare and hard to reproduce. I know, that creating the Context should be done just once at application startup, but as said I found no other way to re-establish a broken connection.
I am using JeroMQ 0.3.4. The source of a test application is below, ~200 lines of code.
Any hints to solve this are very much appreciated.
import java.util.Calendar;
import org.zeromq.ZMQ;
public class JeroMQTest {
public interface IMsgListener {
public void newMsg(byte[] message);
}
final static int delay = 100;
final static boolean doResetContext = true;
static JeroMQTest jeroMQTest;
static boolean isServer;
private ZMQ.Context zContext;
private ZMQ.Socket zSocket;
private String address = "tcp://localhost:9889";
private long lastHeartbeatReceived = 0;
private long lastHeartbeatReplyReceived;
private boolean sendStat = true, serverIsActive = false, receiverInterrupted = false;
private Thread receiverThread;
private IMsgListener msgListener;
public static void main(String[] args) {
isServer = args.length > 0 && args[0].equals("true");
if (isServer) {
new JeroMQTest().runServer();
}
else {
new JeroMQTest().runClient();
}
}
public void runServer() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT")) {
String msgSent = "HEARTBEAT_REP " + msgReceived.substring(10);
sendStat = zSocket.send(msgSent.getBytes());
System.out.println("heartbeat rcvd, reply sent, status:" + sendStat);
lastHeartbeatReceived = getNow();
} else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
while (true) {
boolean heartbeatsOk = lastHeartbeatReceived > getNow() - delay * 4;
if (heartbeatsOk) {
serverIsActive = true;
String msg = "SERVER " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
ct++;
}
if (serverIsActive && (!heartbeatsOk || !sendStat)) {
serverIsActive = false;
if (doResetContext) {
resetContext();
}
}
sleep(delay);
}
}
public void runClient() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT_REP")) {
System.out.println("HEARTBEAT_REP received:" + msgReceived);
lastHeartbeatReplyReceived = getNow();
}
else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
boolean reconnectDone = false;
while (true) {
boolean heartbeatsOK = lastHeartbeatReplyReceived > getNow() - delay * 4;
String msg = "HEARTBEAT " + (ct++);
sendStat = zSocket.send(msg.getBytes());
System.out.println("heartbeat sent:" + msg + ", status:" + sendStat);
sleep(delay / 2);
if (sendStat) {
msg = "MSG " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
reconnectDone = false;
}
if ((!heartbeatsOK && lastHeartbeatReplyReceived > 0) || (!sendStat && !reconnectDone)) {
if (doResetContext) {
resetContext();
}
lastHeartbeatReplyReceived = 0;
reconnectDone = true;
}
sleep(delay / 2);
}
}
public void resetContext() {
closeJmq();
sleep(1000);
createJmq();
System.out.println("resetContext done");
}
private void createJmq() {
zContext = ZMQ.context(1);
zSocket = zContext.socket(ZMQ.DEALER);
zSocket.setSendTimeOut(100);
zSocket.setReceiveTimeOut(100);
zSocket.setSndHWM(10);
zSocket.setRcvHWM(10);
zSocket.setLinger(100);
if (isServer) {
zSocket.bind(address);
} else {
zSocket.connect(address);
}
receiverThread = new Thread() {
public void run() {
receiverInterrupted = false;
try {
ZMQ.Poller poller = new ZMQ.Poller(1);
poller.register(zSocket, ZMQ.Poller.POLLIN);
while (!receiverInterrupted) {
if (poller.poll(100) > 0) {
byte byteArr[] = zSocket.recv(0);
msgListener.newMsg(byteArr);
}
}
poller.unregister(zSocket);
} catch (Throwable e) {
System.out.println("Exception in ReceiverThread.run:" + e.getMessage());
}
}
};
receiverThread.start();
}
public void closeJmq() {
receiverInterrupted = true;
sleep(100);
zSocket.close();
zContext.term();
}
long getNow() {
Calendar now = Calendar.getInstance();
return (long) (now.getTime().getTime());
}
private static void sleep(int mSleep) {
try {
Thread.sleep(mSleep);
} catch (InterruptedException e) {
}
}
}
I want to sync data from MSSQL to android sqllite.All syncdata method write in ansync class.But sometime application return java.sql.SQLException: I/O Error: Socket closed error and not finish sync data . Sometime application successfully sync all update data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{
CheckProductGroupInfoHasNew();
CheckProductInfoHasNew();
CheckProductPriceInfoHasNew();
CheckCustomerInfoHasNew();
}
private void CheckProductInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PC");
else
_AsyncSyncData.execute("PC");
}
private void CheckProductPriceInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PPRICE");
else
_AsyncSyncData.execute("PPRICE");
}
private void CheckCustomerInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"CV");
else
_AsyncSyncData.execute("CV");
}
private void CheckProductGroupInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PG");
else
_AsyncSyncData.execute("PG");
}
class AsyncSyncData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
if (params[0].toString().equals("PG")) {
_ListProductGroupInfo = _MSDBConnection
.SelectProductGroupInfo(_Query);}
} else if (params[0].equals("PC")) {
_ListProductInfo = _MSDBConnection
.SelectProductInfo(_Query);
} else if (params[0].equals("CV")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
} else if (params[0].equals("PPRICE")) {
_ListProductPriceInfo = _MSDBConnection
.SelectProductPriceInfo(_Query);
} else if (params[0].equals("VAT")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
}
#Override
protected void onPostExecute(String result) {
try {
if (result.equals("PG")) {
int _result = 0;
if ((_result = SyncProductGroupInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Group Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PC")) {
int _result = 0;
if ((_result = SyncProductInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PPRICE")) {
int _result = 0;
if ((_result = SyncProductPriceInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Price Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("CV")) {
int _result = 0;
if ((_result = SyncCustomerInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Customer Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
HomeFragment.BindProductGroup();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} else if (result.equals("VAT")) {
if (SyncVatInfo()) {
Toast.makeText(_context, "Save Successfully Vat Data",
Toast.LENGTH_SHORT).show();
}
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
}
} catch (Exception ex) {
Log.i("onPostExecute Ex",
" Chan I'm onPostExecute" + ex.getMessage());
ex.printStackTrace();
Toast.makeText(_context, ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} finally {
}
}