getToken() -> BAD_AUTHENTICATION. Account - android

Hi in the below code getting an issues Bad Authentication. trying to configuring device but not getting any response.and loader also just dismiss.
Am try to configuring a device using Bluetooth but save data into locally not getting any response .
08-23 11:58:33.185 2112-2459/? E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:743227095>, App: com.android.vending, Service: androidmarket
gai: Long live credential not available.
at gaj.b(:com.google.android.gms#12685008#12.6.85 (020306-197041431):20)
at gaj.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):50)
at fyt.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):38)
at hpk.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):8)
at hpk.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):189)
at hok.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):2)
at hoh.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):17)
at hoh.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):6)
at cyz.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):25)
at cyz.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):82)
at fvp.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):6)
at fvo.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):2)
at fvo.e(:com.google.android.gms#12685008#12.6.85 (020306-197041431):6)
at fvn.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):1)
at fxk.getAuthToken(:com.google.android.gms#12685008#12.6.85 (020306-197041431):7)
at android.accounts.AbstractAccountAuthenticator$Transport.getAuthToken(AbstractAccountAuthenticator.java:196)
at android.accounts.IAccountAuthenticator$Stub.onTransact(IAccountAuthenticator.java:113)
at android.os.Binder.transact(Binder.java:380)
at dbf.onTransact(:com.google.android.gms#12685008#12.6.85 (020306-197041431):3)
at android.os.Binder.execTransact(Binder.java:446)
can any one please help me
#OnClick(R.id.saveConfig)
public void onClick() {
sendCommandToBleService();
}
private void sendCommandToBleService() {
String pollNumber = mPollNumber.getText().toString();
String geoLocation = mGeoLocation.getText().toString();
String luminairePower = mLuminourPower.getText().toString();
String projectName = mProjectName.getText().toString();
String battAh = mBatteryAh.getText().toString();
String pannelWatt = mPannelWatt.getText().toString();
if (TextUtils.isEmpty(pollNumber)) {
Toast.makeText(LightConfigurationActivity.this, R.string.poll_number_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(geoLocation) || geoLocation.equalsIgnoreCase("SET")) {
Toast.makeText(LightConfigurationActivity.this, R.string.geoLocation_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(luminairePower) || luminairePower.equalsIgnoreCase("SET")) {
Toast.makeText(LightConfigurationActivity.this, R.string.luminour_power_empty, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(projectName)) {
Toast.makeText(LightConfigurationActivity.this, R.string.project_name_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(battAh)) {
Toast.makeText(LightConfigurationActivity.this, R.string.battery_ah_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(pannelWatt)) {
Toast.makeText(LightConfigurationActivity.this, R.string.pannel_watt_blank, Toast.LENGTH_SHORT).show();
return;
}
makeDefaultValues(pollNumber, geoLocation, luminairePower, projectName, battAh, pannelWatt);
if (battAh.length() == 1) {
battAh = "00" + battAh;
} else if (battAh.length() == 2) {
battAh = "0" + battAh;
}
if (pannelWatt.length() == 1) {
pannelWatt = "00" + pannelWatt;
} else if (pannelWatt.length() == 2) {
pannelWatt = "0" + pannelWatt;
}
sendCommandsToBleService(battAh, pannelWatt);
}
private void resendconfig() {
sendCommandToBleService();
}
private void sendCommandsToBleService(String batAhValue, String pannellwattValue) {
showProgressDialog();
String command = mSolarController.generatePacket("pol " + mPollNumber.getText().toString(), "00");
String longCmd = mPref.getString(Constants.LAT_COMMAND, "");
String latCmd = mPref.getString(Constants.LONG_COMMAND, "");
String firstTimerCmd = mPref.getString(Constants.TIMER_ONE_CMD, "");
String secondTimerCmd = mPref.getString(Constants.TIMER_TWO_CMD, "");
String projectCmd = mSolarController.generatePacket("pro " + mProjectName.getText().toString(), "00");
String batAh = mSolarController.generatePacket("battah " + batAhValue, "00");
String pannelWatt = mSolarController.generatePacket("panelw " + pannellwattValue, "00");
String wattCommand = mPref.getString(Constants.BRIGHTNESS_CMD, "");
String luminaryWatt = mPref.getString(Constants.LUMINOURE_WATT_COMMAND, "");
mBleService.addCommandToQue(command);
mBleService.addCommandToQue(longCmd);
mBleService.addCommandToQue(latCmd);
mBleService.addCommandToQue(firstTimerCmd);
mBleService.addCommandToQue(secondTimerCmd);
mBleService.addCommandToQue(projectCmd);
mBleService.addCommandToQue(batAh);
mBleService.addCommandToQue(pannelWatt);
mBleService.addCommandToQue(wattCommand);
mBleService.addCommandToQue(luminaryWatt);
mBleService.sendCommandToBle();
}

Related

How to pass (space) as value to api in case the value is empty

I have an update profile API, where first name, last name are one of the parameters. I have separated the name into two strings with space as delimiter. But in case if the user doesn't give last name and update, the page crashes saying "ArrayIndex Out of Bounds Exception". I tried putting an if condition to pass last name value as "space" incase last name is empty. But it doesn't work. Please help to validate this condition and pass value accordingly. Attached the specific piece of code below:
Code
private void updateprofile() {
firstname = edtName.getText().toString();
lastname = edtName.getText().toString();
splitstring = txtName.split(" ");
firstname = splitstring[0].trim();
lastname = splitstring[1].trim();
if(TextUtils.isEmpty(lastname))
{
lastname=" ";
}
else
{
lastname = splitstring[1].trim();
}
Call<UpdateProfile> call = apiService.updateprofile(userId, firstname, lastname, profileurl, location, email, mobilenumber);
Log.e("DATA PASSED", userId + " " + firstname + " " + lastname + " " + profileurl + " " + location + email + mobilenumber);
call.enqueue(new Callback<UpdateProfile>() {
#Override
public void onResponse(Call<UpdateProfile> call, Response<UpdateProfile> response) {
if (response.isSuccessful()) {
String status = response.body().getStatus();
if (status.equalsIgnoreCase("1")) {
//Toast.makeText(getContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
mainActivity.imgHomeMenu.setImageResource(R.drawable.edit_icon);
flagoption = true;
imgEditPhoto.setVisibility(View.GONE);
mainActivity.txvTitle.setText("PROFILE");
edtName.setEnabled(false);
edtLocation.setEnabled(false);
edtEmail.setEnabled(false);
edtPhone.setEnabled(false);
linearEmail.setBackground(getContext().getResources().getDrawable(R.drawable.button_background_profile_changes_two));
} else {
Toast.makeText(getContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<UpdateProfile> call, Throwable t) {
}
});
}
Profile View:
private void callProfileApi(Context context) {
vehicleList = new ArrayList<>();
Call<ProfileDetails> call = apiService.callProfile(userId);
Log.e("USER ID INSIDE API", userId);
call.enqueue(new Callback<ProfileDetails>() {
#Override
public void onResponse(Call<ProfileDetails> call, Response<ProfileDetails> response) {
if (response.isSuccessful()) {
ProfileDetails resp = response.body();
if (resp != null) {
String status = resp.getStatus();
if (status.equalsIgnoreCase("1")) {
profileurl = resp.getUserDetail().getImage();
txtName = resp.getUserDetail().getName();
String joineddate = resp.getUserDetail().getJoined();
String[] join = joineddate.split(" ");
Log.e("join", join[0]);
splitstring = txtName.split(" ");
firstname = splitstring[0].trim();
lastname = splitstring[1].trim();
/*
if(edtName.getText().toString().trim().contains(" ")){
splitstring = txtName.split(" ");
firstname = splitstring[0].trim();
lastname = splitstring[1].trim();
}else{
lastname=" ";
Log.e("Name Error","Enter Name");
}*/
//txtjoinedDate = GlobalMethods.Date(join[0]);
txtjoinedDate = resp.getUserDetail().getJoined();
rating = resp.getUserDetail().getRating();
location = resp.getUserDetail().getLocation();
email = resp.getUserDetail().getEmail();
mobilenumber = resp.getUserDetail().getMobile();
ratingbar.setRating(Float.parseFloat(rating));
emailverification = resp.getUserDetail().getEmailVerification();
if (emailverification.equalsIgnoreCase("0")) {
txtEmail.setText("Verify");
txtEmail.setBackground(getResources().getDrawable(R.drawable.button_background_profile_changes_three));
} else {
txtEmail.setText("Verified");
txtEmail.setBackground(getResources().getDrawable(R.drawable.button_background_profile_changes_two));
}
mobileverfication = resp.getUserDetail().getMobileVerification();
if (mobileverfication.equalsIgnoreCase("0")) {
txtPhone.setText("Verify");
txtPhone.setBackground(getResources().getDrawable(R.drawable.button_background_profile_changes_three));
} else {
txtPhone.setText("Verified");
txtPhone.setBackground(getResources().getDrawable(R.drawable.button_background_profile_changes_two));
}
vehicleList = resp.getVehicles();
if (vehicleList.size() > 0) {
myVehicleAdapter = new MyVehicleProfileAdapter(getActivity(), vehicleList, "3");
recycleVehicleRegister.setAdapter(myVehicleAdapter);
recycleVehicleRegister.setLayoutManager(new GridLayoutManager(getActivity(), 1, LinearLayoutManager.HORIZONTAL, false));
} else {
recycleVehicleRegister.setVisibility(View.GONE);
txtNovehicles.setVisibility(View.VISIBLE);
vehiclelayout.setVisibility(View.GONE);
}
reviewList = resp.getReviews();
if (reviewList.size() > 0) {
profileReviewsAdapter = new ProfileReviewsAdapter(getContext(), reviewList);
recycleViewfeedback.setAdapter(profileReviewsAdapter);
recycleViewfeedback.setLayoutManager(new LinearLayoutManager(getContext()));
} else {
recycleViewfeedback.setVisibility(View.GONE);
txtNoreviews.setVisibility(View.VISIBLE);
morereviewslayout.setVisibility(View.GONE);
/*morereviewslayout.setVisibility(View.GONE);
recycleViewfeedback.setVisibility(View.GONE);
notfoundlayout.setVisibility(View.GONE);*/
}
if (TextUtils.isEmpty(profileurl)) {
userProfiPlaceholder.setImageDrawable(getContext().getResources().getDrawable(R.drawable.profile_placeholder));
Glide.with(getContext()).load(profileurl).into(userProfiPlaceholder);
edtName.setText(txtName);
Log.e("PROFILE NAME", txtName);
ratingbar.setRating(Float.parseFloat(rating));
txtRateText.setText(rating);
txtBalance.setText("$"+resp.getUserDetail().getReferralBalance());
edtLocation.setText(location);
edtEmail.setText(email);
edtPhone.setText(mobilenumber);
edtId.setText(idproof);
} else {
Glide.with(getContext()).load(profileurl).into(userProfiPlaceholder);
edtName.setText(txtName);
Log.e("PROFILE NAME", txtName);
txtJoinedDate.setText("Joined" + " " + txtjoinedDate);
ratingbar.setRating(Float.parseFloat(rating));
txtRateText.setText(rating);
txtBalance.setText("$"+resp.getUserDetail().getReferralBalance());
edtLocation.setText(location);
edtEmail.setText(email);
edtPhone.setText(mobilenumber);
edtId.setText(idproof);
}
if (TextUtils.isEmpty(mobilenumber)) {
edtPhone.setHint("Phone Number");
}
if (TextUtils.isEmpty(location)) {
edtLocation.setHint("Location");
}
if (TextUtils.isEmpty(idimage)) {
edtId.setHint("ID Verified (passport)");
}
}
}
}
}
#Override
public void onFailure(Call<ProfileDetails> call, Throwable t) {
}
});
}
In case your string won't be having lastname then this statement will cause error even before you can check for null.
lastname = splitstring[1].trim();
Try directly checking if size() of your array is larger than index you are accessing. If the size is larger then do your initializing for lastname.
Simply Use
if(textName.getText().toString().trim().contains(" ")){
splitstring = txtName.split(" ");
if (splitstring.length>1) {
firstname = splitstring[0].trim();
lastname = splitstring[1].trim();
}
}else{
Log.e("Name Error","Enter first and last Name")
}

How to wait first for the retrofit response before returning the boolean

always returning the wrong value, before the request has been finish. The validation will already return the value without waiting for the response. I'am using retrofit for request then i put it on listener.
Thankyou for the help, suggestion is much accepted!.
this is my code, i have validation for the screen when it's true it will goes to another screen.
#Override
public boolean isValid() {
if (NetworkUtils.isConnected(getActivity())) {
final AtomicBoolean pass = new AtomicBoolean(false);
Thread simpleThread = new Thread() {
public void run() {
new ReprintOnlineHelper(rType, receiptNoEditText.getText().toString(), issuedDate, etTotalAmtPaid.getText().toString(), new ReprintOnlineHelper.ReceiptNoSearchListener() {
#Override
public boolean onServiceResponse(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.get(0).getTPAYRECEIPTNO());
if (receiptNumbers.isEmpty()) {
returnValue = "eReceipt Number not found!";
val = true;
} else {
String pdates = null, ddates;
try {
if (!receiptNumbers.get(0).getTPAYISSUEDDATE().isEmpty()) {
Date periodFormat = df.parse(receiptNumbers.get(0).getTPAYISSUEDDATE());
pdates = sdf.format(periodFormat);
}
} catch (ParseException e) {
e.printStackTrace();
Log.e("ddd", "" + e.getMessage());
}
String tinNo = receiptNumbers.get(0).getTPTIN();
if (tinNo.contains("-")) {
tinNo = receiptNumbers.get(0).getTPTIN().replace("-", "");
}
Log.e("JAC", "" + receiptNumbers.get(0).getTPAYRECEIPTNO() + "---" + AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)) + "---" + MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) + "--" + AlfonzoUtils.formatDate(issuedDate) + "--" + receiptNoEditText.getText().toString() + "--" + tinNo + "--"+revenueCollection.getTpTin().replace("-", ""));
if (receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString()) &&
AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))
&& MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) == MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) && tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
pass.set(true);
returnValue = "success";
val = true;
showMessagePrompt(rType,returnValue);
return true;
} else if (!tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
returnValue = "eReceipt Number was not issued to this TIN " + revenueCollection.getTpTin();
val = false;
} else if (!AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))) {
returnValue = "Issued date is not valid";
val = false;
} else if (MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) != MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString())) {
returnValue = "Total amount paid is not valid";
val = false;
} else if (!receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString())) {
returnValue = "ReceiptNo is not valid";
val = false;
}
}
return false;
}
#Override
public void onErrorResponse(int err) {
}
}).reprintReceiptNo();
}
};
if (!receiptNoEditText.getText().toString().isEmpty() && issuedDate != 0 /*&& MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) > 0*/) {
try {
simpleThread.start();
simpleThread.join();
pass.get();
Log.e("pass", "" + pass + "-" + pass.get() + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
return pass.get();
}
}
return false;
}
this is my request in retrofit:
public void reprintReceiptNo() {
JSONObject jO = new JSONObject();
JSONObject result = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jO.put("xReceipt", receiptTypeNo);
jO.put("xType", receipttype);
jsonArray.put(jO);
result.put("dataArray", jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("dataArray", "----- " + result.toString());
ServiceInterface si = BaseRestClient.getClient();
Observable<List<ReceiptNumber>> call = si.getreprintReceiptNumber(result.toString());
call.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ReceiptNumber>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.toString());
onReceiptNoSearchListener.onServiceResponse(receiptNumbers);
}
});
}
Its not possible for the isValid() method to wait for the service reponse if you have code outside the Thread you've created.
The method will execute the Thread, but while that Thread is executing, the rest of the code will be read, meaning the return pass.get(); or the return false; statments will be read, causing the the method to return before the server response.
The solution its to change the way this was done. You should check if you can call the server and then created your logic in the methods onServiceResponse() and onErrorResponse() based on how you want to proceed.

how to get instance chat message without press back button in quickblox

I want to get message in my chat activity without press back button in Quickblox instance chat
userData = new QBUser();
userData.setEmail(uNameStr);
userData.setPassword(uPwdStr);
userData.setId(user.getId());
You have to set listeners after the privateChat.sendMessage(chatMessage); so when you get success in listeners call notifydatasetchange method of the adapter.
private void sendMessage() {
// privateChatManager = chatService.getPrivateChatManager();
Log.d("PRIVATE", ">>>>> " + privateChatManager);
Log.d("INST", ">>>>> " + QBChatService.getInstance());
Log.d("CHAT ", "" + chatService);
Log.d("PRI", ">>>>> " + QBChatService.getInstance().getPrivateChatManager());
//login to chat firstly
if (messageEdt.length() > 0) {
privateChatMessageListener = new QBMessageListener<QBPrivateChat>() {
#Override
public void processMessage(QBPrivateChat privateChat, final QBChatMessage chatMessage) {
Log.e("privateChat ", " " + privateChat);
Log.e("chatMessage", "" + chatMessage);
chatListAdapter.notifyDataSetChanged();
}
#Override
public void processError(QBPrivateChat privateChat, QBChatException error, QBChatMessage originMessage) {
Log.e("privateChat ", " " + privateChat);
Log.e("QBChatMessage", "" + originMessage);
Log.e("error", "" + error);
}
};
privateChatManagerListener = new QBPrivateChatManagerListener() {
#Override
public void chatCreated(final QBPrivateChat privateChat, final boolean createdLocally) {
if (!createdLocally) {
privateChat.addMessageListener(privateChatMessageListener);
}
}
};
ChattingFragment.chatService.getPrivateChatManager().addPrivateChatManagerListener(privateChatManagerListener);
try {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(messageEdt.getText().toString());
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
chatMessage.setProperty("notification_type", "1");
chatMessage.setSenderId(Integer.parseInt(Util.ReadSharePrefrence(getApplicationContext(), Constant.SHRED_PR.KEY_QB_USERID)));
chatMessage.setRecipientId(opponentId);
chatMessage.setMarkable(true);
privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBPrivateChat privateChat = privateChatManager.getChat(opponentId);
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentId, privateChatMessageListener);
}
// send message
privateChat.sendMessage(chatMessage);
privateChat.addMessageSentListener(privateChatMessageSentListener);
privateChat.addMessageListener(privateChatMessageListener);
} catch (SmackException.NotConnectedException e) {
Toast.makeText(PrivateChat.this, "Exception " + e, Toast.LENGTH_SHORT).show();
}
}
}
private QBMessageSentListener<QBPrivateChat> privateChatMessageSentListener = new QBMessageSentListener<QBPrivateChat>() {
#Override
public void processMessageSent(QBPrivateChat qbChat, QBChatMessage qbChatMessage) {
Log.d("MEHUL", "M " + qbChat);
Log.d("MSG", "MSG " + qbChatMessage);
hashmap = new HashMap<String, String>();
hashmap.put("id", "" + qbChatMessage.getId());
if (qbChatMessage.getBody() != null) {
hashmap.put("msg", "" + qbChatMessage.getBody());
} else {
hashmap.put("msg", "");
}
hashmap.put("recipient_id", "" + opponentId);
hashmap.put("sender_id", "" + user_id);
Collection<QBAttachment> collection = qbChatMessage.getAttachments();
if (collection != null && collection.size() > 0) {
for (QBAttachment attachment : collection) {
String imageid = attachment.getId();
String RecivedUrl = attachment.getUrl();
hashmap.put("url", "" + RecivedUrl);
}
//Here is the AsyncTask where I am trying to download image
//
}
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
hashmap.put("updated_at", "" + currentDateTimeString);
chatArraylist.add(hashmap);
Toast.makeText(getApplicationContext(), "Message Sent Successfully", Toast.LENGTH_SHORT).show();
messageEdt.setText("");
chatListAdapter = new PrivateChatMsgListAdapter(getApplicationContext(), chatArraylist);
lvChatDetails.setAdapter(chatListAdapter);
lvChatDetails.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lvChatDetails.setStackFromBottom(true);
chatListAdapter.notifyDataSetChanged();
scrollMyListViewToBottom();
}
#Override
public void processMessageFailed(QBPrivateChat qbChat, QBChatMessage qbChatMessage) {
Log.d("MEHUL", "M " + qbChat);
Log.d("MSG", "ERR " + qbChatMessage);
}
};

Call an AsyncTask subclass of activity from another class?

I know this kind of questions are maybe too old, but I got stock with this silly thing.
I have an AsyncTask class which is a subclass of an activity class, and right now I want to call it from another class: following codes shows what I mean:
public class STA extends Activity {
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
private static final String TAG = "ListSpdFiles: ";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private String initiator;
private String path;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(String initiator, String path) {
this.initiator = initiator;
this.path = path;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(getApplicationContext(), pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
// tv.setText("task concluded with a null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
//tv.setText("List of files received is:\n" + Arrays.toString(listOfFiles));
}
term();
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
final Global globalVariable = (Global) getApplicationContext();
if (globalVariable.getPasswordButt() == false) {
// Calling Application class (see application tag in AndroidManifest.xml)
// Get name and email from global/application context
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
String username = "/" + getLastAccessedBrowserPage() + ".username" + ".txt";
//String password = "/" + CurrentURL + "password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, username, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setUsername(name);
// getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsUsername(false);
} else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
// globalVariable.setUsernameButt(false);
} else if (globalVariable.getPasswordButt() == true) {
// Calling Application class (see application tag in AndroidManifest.xml)
// final Global globalVariable = (Global) getApplicationContext();
// Get name and email from global/application context
final boolean ispassword = globalVariable.getIsPassword();
if (ispassword == true) {
// String username = "/" + CurrentURL + "username" + ".txt";
String password = "/" + getLastAccessedBrowserPage() + ".password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, password, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setPassword(name);
//getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsPassword(false);
} else if (ispassword == false)
Log.i(TAG, "Wrong Input Type For Password.");
globalVariable.setPasswordButt(false);
// boolpassword=false;
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
Would you please tell me what should I do to fix this code?
Looking over the code I did not see anywhere you referenced anything from the Activity itself besides the application context so you can move the ListSpdFiles class to its own java file and pass it a context into the constructor when you make a new instance of it.
Put this class in a ListSpdFiles.java file so it is no longer an inner class.
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
Context applicationContext;
public ListSpdFiles(Context context, String initiator, String path) {
this.initiator = initiator;
this.path = path;
applicationContext = context.getApplicationContext();
}
// The rest of your code still goes here. Replace other calls to
// getApplicationContext() with the new applicationContext field
}
You can now use this class anywhere a Context is available. You create a new instance by doing:
ListSpdFiles listSpdFilesTask = new ListSpdFiles(context, "someInitiator", "somePath");
listSpdFilesTask.execute();

Android Pusher Invalid Signature - Client Side

Working with Pusher, issues with invalid signature following error:
Invalid signature: Expected HMAC SHA256 hex digest of socketID:channel, but got hash.
Here is my code:
public static PusherOptions pusherChannelAuthorise(){
Log.v(TAG, "pusherChannelAuthorise");
mMobileToken = Handler_Login.fetchmobile();
PUSHER_MOBILETOKEN_MAP.put(PUSHER_MOBILETOKEN_LABEL, mMobileToken);
HttpAuthorizer authoriser = new HttpAuthorizer(url);
authoriser.setHeaders(PUSHER_MOBILETOKEN_MAP);
options = new PusherOptions().setAuthorizer(authoriser);
return options;
}
public static void connect(){
Log.v(TAG, "connect" + "::CONNECTED::");
PusherOptions presenceChannelOptions = pusherChannelAuthorise();
presenceChannelConnected = true;
pusher = new Pusher(pusherHash, presenceChannelOptions);
pusher.connect(new ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange change) {
socketId = pusher.getConnection().getSocketId();
Log.v(TAG, "The socketId is: " + socketId);
}
#Override
public void onError(String message, String code, Exception e) {
Log.v(TAG, "There was a problem connecting!");
}
}, ConnectionState.CONNECTED);
presencechannel = pusher.subscribePresence(PUSHER_PUBLIC_CHANNEL_NAME, listener);
String myUuid = Handler_Login.getMyUuid();
privatechannel = pusher.subscribePrivate(DOCSYNC_CHANNEL + myUuid, docSyncListener);
privatechannel.bind("client-init", docSyncListener = new PrivateChannelEventListener() {
#Override
public void onEvent(String channelName, String eventName, String data) {
Log.v(TAG, "Private Test onEvent: " + channelName + " " + eventName + " " + data);
}
#Override
public void onSubscriptionSucceeded(String channelName) {
Log.v(TAG, "Private Channel onSubscriptionSucceeded: " + channelName);
}
#Override
public void onAuthenticationFailure(String message, Exception e) {
Log.v(TAG, "Private Channel onAuthenticationFailure: " + message + ":::" + e);
}
});
}
What am I doing wrong? Do I have to set additional parameters in the headers for the authoriser? #leggetter
Authentication to the presence channel works fine, but the private one fails.
EDIT:
Server Code (PHP, Laravel):
public function postMobilePusher(Request $request)
{
if (null !== $request->header('mobileToken')) {
$currentUser = User::where('mobileToken', '=', $request->header('mobileToken'))->first();
if (null !== $currentUser) {
define('APP_ID', ID);
define('APP_KEY', KEY);
define('APP_SECRET', SECRET);
$pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID);
$socket_id = $request->get('socket_id');
$channel_name = $request->get('channel_name');
$user_id = $currentUser->id;
$user_info = [
'firstName' => $currentUser->firstName
];
return $auth = $pusher->presence_auth( $channel_name, $socket_id, $user_id, $user_info );
}
}
return abort(403, 'Unauthorized action.');
}
Update the server-side code to use socket_auth for private channels and presence_auth for presence channels:
public function postMobilePusher(Request $request)
{
if (null !== $request->header('mobileToken')) {
$currentUser = User::where('mobileToken', '=', $request->header('mobileToken'))->first();
if (null !== $currentUser) {
define('APP_ID', ID);
define('APP_KEY', KEY);
define('APP_SECRET', SECRET);
$pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID);
$socket_id = $request->get('socket_id');
$channel_name = $request->get('channel_name');
$auth = null;
if(starts_with($channel_name, 'private-')) {
// TODO: check user has permission to access channel
$auth = $pusher->socket_auth($channel_name, $socket_id);
}
else {
// presence
// TODO: check user has permission to access channel
$user_id = $currentUser->id;
$user_info = [
'firstName' => $currentUser->firstName
];
$auth = $pusher->presence_auth( $channel_name, $socket_id, $user_id, $user_info );
}
}
}
return abort(403, 'Unauthorized action.');
}

Categories

Resources