very rare do i come here because most of my problems are solved with examples and samples ect. which im not to bad with. now my problem is i cant figure out what the hell is going on. So i bought this printer, i got the SDK,
In the sdk once i load it, i have to press connect, and it pairs and i punch in the pin (0000), once that done, i get the test button to show up and prints the string ect ect.
what i want it to do is, Connect to the printer (automatically or with a pin, whatever)
Then press "next activity" and be able to print in the next activity whatever i want to with the Bluetooth printer. but when the next activity loads, the connection is closed and i cannot use the printer UNLESS i create the connection method into that activity all together where i would need to pair the device over and over and over again. so here is my SDK that i got. i really hope someone can help me because im going freakin go nuts, i tried using getbondeddevices but i dont think im clever enough... so here goes. maybe someone can see how the printer connects and how i can share it throughout the activities??
maybe even a tutorial on how to pair a device and then use it in the next activity... any help would be great
public class PrintTestAcitvity extends Activity {
// btOperation bo = new btOperation();
//// ¶ÔÆ뷽ʽ
/**
* printing text align left
*/
public static final int AT_LEFT = 0;
/**
* printing text align center
*/
public static final int AT_CENTER = 1;
/**
* printing text align right
*/
public static final int AT_RIGHT = 2;
private static final String GetBondedDevice = null;
// public String curentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
public static String curentDateTimeString() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
private Button btConnect = null;
private Button btCancel = null;
private Button asciiSend = null;
private Button graphicSend = null;
private regoPrinter mobileprint = null;
private boolean bConnect = true;
private TextView textTitle = null;
// private EditText portName;
private int iObjectCode;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btConnect = (Button)findViewById(R.id.connect);
btCancel = (Button)findViewById(R.id.cancel);
asciiSend = (Button)findViewById(R.id.asc_send);
graphicSend = (Button)findViewById(R.id.gra_send);
textTitle = (TextView)findViewById(R.id.title);
// portName = (EditText)findViewById(R.id.portName);
iObjectCode = 0;
mobileprint = new regoPrinter();
asciiSend.setEnabled(false);
graphicSend.setEnabled(false);
btConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String strName = "MPT-II"; // portName.getText().toString();
if(strName.length() == 0)
{
Toast.makeText(PrintTestAcitvity.this, "Error:port name empty", Toast.LENGTH_SHORT).show();
return;
}
if(bConnect)
{
try
{
mobileprint.CON_LnitPrintLib();
iObjectCode = mobileprint.CON_ConnectDevice(strName);
}
catch(printLibException e)
{
Toast.makeText(PrintTestAcitvity.this, e.GetMessage(),
Toast.LENGTH_LONG).show();
}
finally
{
if(iObjectCode != 0)
{
// connect succeed
textTitle.setText(strName + PrintTestAcitvity.this.getString(R.string.consucceed));
btConnect.setText(R.string.disconnect);
bConnect = false;
asciiSend.setEnabled(true);
graphicSend.setEnabled(true);
}
}
}
else
{
textTitle.setText(strName + PrintTestAcitvity.this.getString(R.string.disconnect));
asciiSend.setEnabled(false);
graphicSend.setEnabled(false);
try {
mobileprint.CON_CloseConnect(iObjectCode);
} catch (printLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bConnect = true;
btConnect.setText(R.string.connect);
}
}
});
btCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!bConnect)
{
try {
mobileprint.CON_CloseConnect(iObjectCode);
} catch (printLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mobileprint.CON_FreePrintLib();
finish();
return;
}
});
asciiSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
// mobileprint.CON_PageStart(iObjectCode, 576, 0) &&
if(mobileprint.ASCII_QueryPrinterStatus(iObjectCode))
{
//Çå³ý´òÓ¡»ú»º³å
mobileprint.ASCII_Reset(iObjectCode);
//´òÓ¡LogoͼƬ£¬ÏȽ«Í¼Æ¬ÏÂÔØÖÁ´òÓ¡»úÖÐÔÙÖ´Ðд˺¯Êý
//mobileprint.PrintFlashPic(1, 0);
//´òÓ¡title
mobileprint.ASCII_AlignType(iObjectCode, 1);
mobileprint.ASCII_FormatString(iObjectCode,false,false,true,false,false);
mobileprint.ASCII_SendString(iObjectCode, "Plate:" +" " + "ABCD123", "gb2312");
// mobileprint.ASCII_PrintCRLF(iObjectCode, 2);
mobileprint.ASCII_FeedLines(iObjectCode, 1);
mobileprint.ASCII_Reset(iObjectCode);
mobileprint.ASCII_PrintCRLF(iObjectCode, 2);
mobileprint.CON_PageEnd(iObjectCode);
}
else
{
Toast.makeText(PrintTestAcitvity.this, "Printer status error",
Toast.LENGTH_LONG).show();
}
} catch (printLibException e) {
// TODO Auto-generated catch block
Toast.makeText(PrintTestAcitvity.this, e.GetMessage(),
Toast.LENGTH_LONG).show();
}
}
});
graphicSend.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if(mobileprint.CON_PageStart(iObjectCode, 576, 450) && mobileprint.ASCII_QueryPrinterStatus(iObjectCode))
{
//Çå³ý´òÓ¡»ú»º³å
mobileprint.ASCII_Reset(iObjectCode);
mobileprint.DRAW_Line(iObjectCode,0, 1, 575, 1,3);
mobileprint.DRAW_Line(iObjectCode,0, 1, 0, 450,3);
mobileprint.DRAW_Line(iObjectCode,575, 1, 575, 450,3);
mobileprint.DRAW_Line(iObjectCode,0, 450, 575, 450,3);
mobileprint.DRAW_Line(iObjectCode,465, 1, 465, 450,1);
mobileprint.DRAW_Rectangle(iObjectCode, 0, 0, 80, 50, 1, true);
/* mobileprint.DRAW_Text(iObjectCode, 30, 80, "ÉϺ£¿ì½Ý¿ìÔËÓÐÏÞ¹«Ë¾ ", 40);
mobileprint.DRAW_Text(iObjectCode,90, 185, "ÉϺ£ -> ±±¾©", 35);
mobileprint.DRAW_Text(iObjectCode,80, 245, "(ÉϺ£±±Ç๫·°ì)", 20);
mobileprint.DRAW_Text(iObjectCode,310, 245, "(»ðʮ·վ)", 20);
mobileprint.DRAW_Text(iObjectCode,20, 305, "20112-02100100-0101-2112-10", 30);
mobileprint.DRAW_Code128(iObjectCode, 60, 350, 1, 60, "754432112-2");
mobileprint.DRAW_CreateRotalBlock(iObjectCode,476, 0, 450,100, 2);//(0.0) Ϊ×óÉϽǵľØÐÎ
mobileprint.DRAW_Code128(iObjectCode, 40, 5, 1, 60, "754432112-2");
*/
mobileprint.CON_PageEnd(iObjectCode);
}
else
{
Toast.makeText(PrintTestAcitvity.this, "Printer status error",
Toast.LENGTH_LONG).show();
}
} catch (printLibException e) {
// TODO Auto-generated catch block
Toast.makeText(PrintTestAcitvity.this, e.GetMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
Related
I have just started exploring google-play-services-turnbased APIs. Till now I have been successful in creating a match. But from the documentation I haven't been able to figure out how to player's score after he completes his turn.
This is my onClickStartMatch method.
public void onStartMatchClicked() {
Intent intent =
Games.TurnBasedMultiplayer.getSelectOpponentsIntent(mHelper.getApiClient(), 1, 7, true);
startActivityForResult(intent, RC_SELECT_PLAYERS);
}
This is my onActivityResult method in my main activity class.
if (request == RC_SELECT_PLAYERS) {
if (response != RESULT_OK) {
// user canceled
return;
}
// Get the invitee list.
final ArrayList<String> invitees =
data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
// Get auto-match criteria.
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
} else {
autoMatchCriteria = null;
}
TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setAutoMatchCriteria(autoMatchCriteria)
.build();
// Create and start the match.
Games.TurnBasedMultiplayer
.createMatch(mHelper.getApiClient(), tbmc)
.setResultCallback(new MatchInitiatedCallback());
}
This is my MatchInitiatedCallback class
public class MatchInitiatedCallback implements
ResultCallback<TurnBasedMultiplayer.InitiateMatchResult>,OnTurnBasedMatchUpdateReceivedListener {
#Override
public void onResult(TurnBasedMultiplayer.InitiateMatchResult result) {
// Check if the status code is not success.
Status status = result.getStatus();
if (status.isSuccess()) {
Log.d("turnbased","Turn Based Match Initiated successfully with result: "+status.getStatusMessage());
return;
}
TurnBasedMatch match = result.getMatch();
// If this player is not the first player in this match, continue.
if (match.getData() != null) {
showTurnUI(match);
return;
}
// Otherwise, this is the first player. Initialize the game state.
initGame(match);
// Let the player take the first turn
showTurnUI(match);
}
public void showTurnUI(TurnBasedMatch match){
if(match.getStatus() == TurnBasedMatch.MATCH_STATUS_ACTIVE){
if(match.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN){
turnBasedMatchData = match.getData();
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(), "score:400".getBytes(Charset.forName("UTF-16")),null).setResultCallback(updateMatchResult());
}
}
}
public void initGame(TurnBasedMatch match){
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(),"score:605".getBytes(Charset.forName("UTF-16")),match.getParticipantId(Games.Players.getCurrentPlayerId(mHelper.getApiClient()))).setResultCallback(updateMatchResult());
}
public ResultCallback<TurnBasedMultiplayer.UpdateMatchResult> updateMatchResult(){
return null;
}
#Override
public void onTurnBasedMatchReceived(TurnBasedMatch turnBasedMatch) {
Log.d("turn-based","Player played his turn");
}
#Override
public void onTurnBasedMatchRemoved(String s) {
}
}
}
Also it would helpful if some can properly explain how to continue a game a game from start and when to submit score and how.
Figured it out. This is how you can do it.
public byte[] persist() {
JSONObject retVal = new JSONObject();
try {
retVal.put("turnCounter", 2);
retVal.put("score1",100);
retVal.put("score2",200);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String st = retVal.toString();
Log.d(TAG, "==== PERSISTING\n" + st);
return st.getBytes(Charset.forName("UTF-8"));
}
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(),persist(),null).setResultCallback(updateMatchResult());
Currently, I'm trying to figure out how to stay connected with a device via Bluetooth throughout Activities. I have a few variables that I initialize to get the connection going.
My previous activity flow is Main Page > User input Text page > Bluetooth Connection(SENDING INFO).
So in this way, every time I go back to the User Input Text Page, the Bluetooth connection will be reset because when I go the next page, it'll rerun all the receivers and stuffs.
Now I'm moving the Bluetooth Connection forward. Meaning now it is Main Page > Bluetooth Connection > User Input Text Page(SEND).
But after I connect on my Bluetooth Connection page, I'm not sure what variables I should bring over/save inside SharedPreferences, so that the Bluetooth connection stays and I can send right away.
//This method runs when I click a device on my ListView.
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetoothAdapter.cancelDiscovery();
System.out.println("Bluetooth Adapter2 = "
+ bluetoothAdapter.cancelDiscovery());
SiriListItem item = delist.get(arg2);
mAdapter.notifyDataSetChanged();
// When device being clicked
count++;
click = 1;
// Get the device MAC address, which is the last 17 chars in the
// View
String info = item.message;
String address = info.substring(info.length() - 17);
BlueToothAddress = address;
if (click == 1) {
clientThread ct = new clientThread();
ct.start();
}
};
};
//This is the clientThread if click == 1, it'll start this.
private class clientThread extends Thread {
public void run() {
try {
//
bdDevice = bluetoothAdapter.getRemoteDevice(BlueToothAddress);
socket = bdDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Message msg2 = new Message();
msg2.obj = "Please wait, connecting to server: "
+ BlueToothAddress;
msg2.what = 0;
LinkDetectedHandler.sendMessage(msg2);
socket.connect();
Log.i("tag", "This is the pairing section");
Message msg = new Message();
msg.obj = "Device connected. Sending message is allowed.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
readThread = new readThread();
readThread.start();
click++;
} catch (IOException e) {
Message msg = new Message();
msg.obj = "Error! Can't connect to device. Please try again.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
click--;
}
}
};
public class readThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
String tmp = null;
try {
mmInStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
// read the data from the inputStream
if ((bytes = mmInStream.read(buffer)) > 0) {
for (int i = 0; i < bytes; i++) {
tmp = "" + buffer[i];
String st = new String(tmp);
tmp = null;
Message msg = new Message();
msg.obj = st;
msg.what = 1;
}
}
} catch (IOException e) {
try {
mmInStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
}
//On Click it'll send the message stored in the editText.
buttonConnect.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View arg0) {
if (count == 0) {
Toast.makeText(bluetoothtest.this,
"Please connect to a device first.",
Toast.LENGTH_LONG).show();
}
// Need API=14
else if (!socket.isConnected()) {
Toast.makeText(bluetoothtest.this,
"Connecting! Please wait.", Toast.LENGTH_LONG)
.show();
} else {
try {
sendMessageHandle(contentRow1.getText().toString(),
contentRow2.getText().toString(), contentRow3
.getText().toString(), contentRow4
.getText().toString());
// sendMessageHandle(contentRow2.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
So the main thing is. What method should I have in my User Input Text Page? Must I have all this method in my User Input Text Page or can I just bring over variables via SharedPreferences?
Thanks.
It is probably bad practice to be handling bluetooth connections on the main thread. You should really handle the bluetooth connection/maintenance through a Service/background thread. Your activities can then talk to the service via a BroadcastReceiver and Handles.
This code is able to make the android device as a USB host for the hardware model. It also can read data from the hardware correctly in Main Activity. However, as soon as I moved it to another activity, everything still works but the data reading is incorrect.
For instance, I'm trying to write the data read into file. First activity is to input filename and just a button to send to another activity. The code below is in the second activity
public class Temp extends Activity {
private FileOutputStream outputStream;
public static D2xxManager ftD2xx= null;
Handler mHandler = new Handler();
FT_Device ftDev = null;
int devCount = 0;
UsbDevice device = null;
TextView Text =null;
String temp = null;
_4DPoint P = null;
int rd = 0;
byte[] byt = null;
byte[] Fdata = null;
String outp = "";
String From_Serial = "";
int Min = -1;
String fileName;
Context c;
final Runnable updateResults = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Text.setText("" + Min + '\n' + temp);
}
};
public void getData(){
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byt = new byte[256];//{(byte)'a','b','c','d',};
Toast.makeText(getBaseContext(), "start " + fileName , Toast.LENGTH_LONG).show();
Text = (TextView)findViewById(R.id.test2);
device = (UsbDevice) getIntent().getParcelableExtra("USB");
ftD2xx = D2xxManager.getInstance(c);
ftD2xx.addUsbDevice(device);
devCount = ftD2xx.createDeviceInfoList(c);
if (devCount > 0) {
ftDev = ftD2xx.openByUsbDevice(c, device);
}
if( ftDev.isOpen() == true ) {
ftDev.setBitMode((byte)0 , D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(38400);
ftDev.setDataCharacteristics(D2xxManager.FT_DATA_BITS_8, D2xxManager.FT_STOP_BITS_1, D2xxManager.FT_PARITY_NONE);
ftDev.setFlowControl(D2xxManager.FT_FLOW_NONE, (byte) 0x0b, (byte) 0x0d);
Thread t = new Thread() {
public void run() {
int i;
while(true){
rd=0;
while (rd==0){
rd = ftDev.read(byt, 14);
}
for(i=0; i<rd; i++)
outp += (char)byt[i];
From_Serial = new String(outp);
P = new _4DPoint(From_Serial);
temp = String.format("%s: %f %f %f %f %d\n", From_Serial, P.R, P.G, P.B, P.L, P.camera);
try {
outputStream.write(temp.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outp = "";
mHandler.post(updateResults);
}
}
};
t.start();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (D2xxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
// Show the Up button in the action bar.
setupActionBar();
Intent intent = getIntent();
fileName = intent.getStringExtra("File Name");
c = this;
getData();
}
The set up should be fine since it's reading data from hardware, but the data read is incorrect.
Also, I'm wondering why we need to create new thread while reading data. I tried not creating new thread and it didn't work well, but still have no idea why? I tried to contact the person who wrote the code to read data but no reply.
Any help would be really appreciated :)
You state that you receive data, therefor I think you should look at your ftDev settings. Try for example to set ftDev.setBaudRate(115200) (this worked for me) or try playing with your other ftDev Settings a little bit.
The settings I use in my programm are:
int baudRate = 115200;
byte stopBit = 1; /*1:1stop bits, 2:2 stop bits*/
byte dataBit = 8; /*8:8bit, 7: 7bit*/
byte parity = 0; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl = 1; /*0:none, 1: flow control(CTS,RTS)*/
If this won't work, it is wise to first check this data communication with a computer program e.g. or to analyse the incomming 'wrong' data.
I have two objects, a establishment object that belongs to a deal object that can be voted upon. If I up/down vote the same deal multiple times, the seventh time I vote the query just sits and does not do anything. The app does not crash, but it also does not save. If I go into another activity that requires a parse.com query that query also will not work. Here is my up vote logic (down voting is identical).
Assume all vars used are initialized before onCreate().
Are my queries getting backed up in a pipe somewhere?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upVoteButton = (Button) findViewById(R.id.deal_up_vote_button);
upVoteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new UpVoteTask().execute();
}
});
}
// visually changes buttons if they are selected
private void setButtons(Boolean queryDb) {
if (queryDb == true) {
queryParse();
}
// if deal found correctly
if (deal != null) {
// if user found correctly
if (dealVoteUser != null) {
if (dealVoteUser.get("vote").toString().equals("0")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(true);
} else if (dealVoteUser.get("vote").toString().equals("1")) {
upVoteButton.setPressed(true);
downVoteButton.setPressed(false);
} else if (dealVoteUser.get("vote").toString().equals("2")) {
upVoteButton.setPressed(false);
downVoteButton.setPressed(false);
}
}
}
}
// queries parse and populates vars
private void queryParse(){
ParseQuery<ParseObject> queryDeal = ParseQuery.getQuery("Deal");
queryDeal.whereEqualTo("objectId", deal_id);
try {
deal = queryDeal.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseQuery<ParseObject> queryDealVoteUser = ParseQuery
.getQuery("deal_vote_users");
queryDealVoteUser.whereEqualTo("deal", deal).whereEqualTo("user",
ParseUser.getCurrentUser());
try {
dealVoteUser = queryDealVoteUser.getFirst();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// UpVoteTask AsyncTask
private class UpVoteTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
upVoteProgressDialog = new ProgressDialog(DealsDetailsActivity.this);
// Set progressdialog message
upVoteProgressDialog.setMessage("Saving...");
upVoteProgressDialog.setIndeterminate(false);
// Show progressdialog
upVoteProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
queryParse();
// if deal found correctly
if (deal != null) {
// if user has not voted yet
if (dealVoteUser == null) {
// create new and assign vote to 1
dealVoteUser = new ParseObject("deal_vote_users");
dealVoteUser.put("deal", deal);
dealVoteUser.put("user", ParseUser.getCurrentUser());
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
// if user already down voted
} else if (dealVoteUser.get("vote").toString().equals("0")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes") - 1;
// if user already up voted
} else if (dealVoteUser.get("vote").toString().equals("1")) {
// already voted up, remove vote
dealVoteUser.put("vote", 2);
up_votes = deal.getInt("up_votes") - 1;
down_votes = deal.getInt("down_votes");
// if user already voted but cleared vote
} else if (dealVoteUser.get("vote").toString().equals("2")) {
// change vote to 1
dealVoteUser.put("vote", 1);
up_votes = deal.getInt("up_votes") + 1;
down_votes = deal.getInt("down_votes");
}
// calculate overall rating percentage
if ((up_votes + down_votes) != 0) {
rating = (up_votes / (up_votes + down_votes)) * 100;
} else if ((up_votes == 0) && (down_votes == 0)) {
rating = 0;
} else {
rating = 50;
}
deal.put("rating", rating);
deal.put("up_votes", up_votes);
try {
deal.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dealVoteUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// deal not found problem
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// visually change buttons without querying db
setButtons(false);
//remove progress dialogue
if(upVoteProgressDialog != null){
upVoteProgressDialog.dismiss();
upVoteProgressDialog = null;
}
}
}
Use the saveInBackground method - it will do the same as save, but also save it to your application's cache so that you won't get different values while the data is being saved, so it won't have any apparent effect on your application. It's the best method to save or find (it has a 'sister' method named findInBackground). It acts like an Async task and does not clog your main thread.
I switched all parse calls over to ._____InBackground() and I moved the save logic to onPause(). This way I am not making multiple save calls to parse if the user decides to change their vote multiple times.
I want to cancel a downloading file using async task, i tried below code, here isCancelled() method is not working, can any one suggest how can i stop download.
vid1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
down d1=new down();
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
d1.execute(url1,"one");
}else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(d1!=null && d1.getStatus()!=AsyncTask.Status.FINISHED){
d1.cancel(true);
}
}
}
});
vid2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Vid 2", "Vid 2");
// TODO Auto-generated method stub
down d2=new down();
if(vid2.getText().toString().equals("Start")){
vid2.setText("Pause");
d2.execute(url2,"two");
}else if(vid2.getText().toString().equals("Pause")){
vid2.setText("Start");
Log.v("Vid 2 Else", "Vid 2 Else ");
d2.cancel(true);
}
}
});
}
private class down extends AsyncTask<String, Void, String>{
RandomAccessFile output ;
boolean cancel=false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Log.v("Pre Execute", "Pre Execute");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
File outputFileCache=new File(Environment.getExternalStorageDirectory()+"/pau/"+params[1]+".mp4");
try {
Long download_ok = null ;
int fileLength;
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
if (outputFileCache.exists())
{
Log.v(">>>>>>", "Exists");
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
}
connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();
if (connection.getResponseCode() / 100 != 2)
throw new Exception("Invalid response code!");
else
{
String connectionField = connection.getHeaderField("content-range");
if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
download_ok = Long.valueOf(connectionRanges[0]);
Log.v("download ok", ""+download_ok);
}
if (connectionField == null && outputFileCache.exists())
outputFileCache.delete();
if(download_ok==null){
download_ok=(long) 0;
}
fileLength = (int) (connection.getContentLength() + download_ok);
Log.v("file length", ""+fileLength);
input = new BufferedInputStream(connection.getInputStream());
output = new RandomAccessFile(outputFileCache, "rw");
output.seek(download_ok);
byte data[] = new byte[1024];
int count = 0;
int __progress = 0;
while ((count = input.read(data, 0, 1024)) != -1 && __progress!=100)
{
Log.v(">>>>>>>>>>>progress cancelled", "<<<<<<<<<"+isCancelled());
if(isCancelled()){
Log.v(">>>>>>>>>>>>>>>>>>>>>>>>>>>", "<<<<<<<<<"+isCancelled());
break;
}else{
download_ok += count;
output.write(data, 0, count);
__progress = (int) ((download_ok * 100) / fileLength);
}
}
output.close();
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
Found your problem: You are creating a new instance of the Asynctask with every click, e.g.
down d2=new down();
This means that you are calling cancel on a different AsyncTask object. You need to move this line into your check for the start click and also use a field and not a local variable i.e.
if(vid2.getText().toString().equals("Start")) {
d2 = new down();
vid2.setText("Pause");
d2.execute(url2,"two");
}
where d2 is set in your class. Also note that class names should always start with capital letters, i.e. class Down instead of class down.
EDIT
You can store the Asynctask in a global class array that is equal in length to the number of videos.
Down downTasks[] = new Down[TOTAL VIDEOS];
Then you initialise the Views, similar to what you already did, here shown for one View
vid1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
downTasks[0] = new down();
downTasks[0].execute(url1,"one");
}
else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(downTasks[0]!=null && downTasks[0].getStatus()!=AsyncTask.Status.FINISHED){
downTasks[0].cancel(true);
}
}
}
});
Note that this code is quite redundant because you rewrite almost exactly the same code for every View, this can be nicely refactored with a for loop, but I leave that as an exercise for you if you feel like it.