I want to retrieve an user token. This is my code:
AccountManager am = AccountManager.get(mActivity);
AccountManagerFuture<Bundle> bundleAccountManagerFuture = am.getAuthTokenByFeatures(ACCOUNT_TYPE, AUTHORIZATION_TOKEN_TYPE, null, mActivity, null, null, null, null);
try {
Bundle result = bundleAccountManagerFuture.getResult(30, TimeUnit.SECONDS);
if (result!=null) {
OTTCache.getInstance().authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
}
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
}
But the process stop in this line:
Bundle result = bundleAccountManagerFuture.getResult();
Some idea?
Thank you very much
Exception:
android.accounts.OperationCanceledException W/System.err: at
android.accounts.AccountManager$AmsTask.internalGetResult(AccountManager.java:1985)
W/System.err: at
android.accounts.AccountManager$AmsTask.getResult(AccountManager.java:1997)
W/System.err: at
android.accounts.AccountManager$AmsTask.getResult(AccountManager.java:1995)
W/System.err: at
com.fr.apps.cliente.tv.task.LoginTask.doInBackground(LoginTask.java:83)
W/System.err: at
com.fr.apps.cliente.tv.task.LoginTask.doInBackground(LoginTask.java:25)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:304)
W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err:
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err: at java.lang.Thread.run(Thread.java:761)
Using getResult() attempts to call on the variable, and the code continues immediately. I'm assuming you're trying to retrieve it from a server or something, rather than from being stored on the device? In that case you need to wait for .isDone() (android doc here) to become true before you process the result.
From Documentation of AccountManagerFuture for .getResult() method -
This
* call will block until the result is available. In order to check if the result is
* available without blocking, one may call {#link #isDone()} and {#link #isCancelled()}.
EDIT 1: You can use getResult(long timeout, TimeUnit unit) which will timeout after a specified time if the request is blocked. After this, you can check if task was successfully done or not using .isDone() and accordingly, proceed.
I found the problem:
The package name of my application do not match exactly with the package name of my other app (This app have the login). Now, i signed both with the same key.
Related
I am currently working on an app which requires a Bluetooth laser meter. So i tried a few lines of code and went through a loads of failures. The last error I get is an NPE because i try to access the array returned by getUuids().
I also tried to connect the app to my airPods and everything worked well.
I am at minSdk 27 and targetSdk 31
All bluetooth permissions (bluetooth, bluetooth_admin) are granted.
the fact is, the laser thing requires an app to work and i wonder if the constructor could have blocked some functionalities. if so, i'll look to buy another one from another brand, if someone could provide me a link to buy a device working for my app.
Here's my bluetooth connect code (pretty generic I guess)
I also tried the static UUID suggested in this post but i now get this socket error which (i think) mean the uuid's not working either:
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
Const.requestAllAppPermissions(this);
return;
}
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if (bondedDevices.size() > 0) {
Object[] devices = bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0];
System.out.println(device.getName());
if (device.fetchUuidsWithSdp()) {
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = null;
try {
//socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket = device.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805f9b54fb"));
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
//outputStream = socket.getOutputStream();
// inStream = socket.getInputStream();
} else {
}
} else {
System.out.println("bluetooth disabled");
}
} else {
System.out.println("No bluetooth built-in");
}
here's the static UUID stacktrace:
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:920)
W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:934)
W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:494)
W/System.err: at com.adici.activities.PlanActivity.lambda$defButton$13$com-adici-activities-PlanActivity(PlanActivity.java:409)
W/System.err: at com.adici.activities.PlanActivity$$ExternalSyntheticLambda10.onClick(Unknown Source:2)
W/System.err: at android.view.View.performClick(View.java:7346)
W/System.err: at android.view.View.performClickInternal(View.java:7312)
W/System.err: at android.view.View.access$3200(View.java:846)
W/System.err: at android.view.View$PerformClick.run(View.java:27794)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:214)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7100)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
I'm open to any suggestion
Looking at the user manual for the Leica DISTO D2 it states the device uses Bluetooth Smart, also known as Bluetooth Low Energy (BLE). You won't be able to connect to it using Bluetooth Sockets (Bluetooth Classic).
Please follow the Android documentation on BLE to develop your app. To debug the connection beforehand, please install a generic BLE scanner such as nRF Connect and investigate the services and characteristics the device offers.
For my app I need values which are parsed by jSoup from a website and then returned to the user using a notification, these values change ~ every minute, so to be up-todate with the values I set up a task using a handler, this works good when the app is in foreground, but as soon as the user goes to the homescreen the app will return multiple exceptions like e.g. java.net.UnknownHostException or java.net.SocketTimeoutException, in the code this happens when jSoup is connecting to the specified site, I already tried using Services and AsyncTasks instead of threads, but it was always the exact same problem, I also searched for people with similar experiences, but I guess my issue is quite specific.
This is the code for the handler:
private final static int INTERVAL = 1000 * 60;
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable()
{
#Override
public void run() {
try {
wakeLock.release();
} catch (RuntimeException e) {
e.printStackTrace();
}
if (!isUpdating) {
isUpdating = true;
App.shouldUpdate = true;
System.out.println("update");
final TinyDB tinydb = new TinyDB(getApplicationContext());
TextView priceEditText = loadedLayouts.get(1).findViewById(R.id.priceTextView);
TextView increaseEditText = loadedLayouts.get(1).findViewById(R.id.increaseTextView);
updatePricesStock(tinydb.getString("current_isin"), priceEditText, increaseEditText);
}
wakeLock.acquire(2*60*1000L /*10 minutes*/);
}
mHandler.postDelayed(mHandlerTask, INTERVAL);
}
}
};
and this is the code for the updateStockPrices method (I will not include updatePricesWarrant and updatePricesKnockout since they are essentially doing the same things and also throw the same exceptions)
public void updatePricesStock(final String ISIN, TextView priceText, TextView increaseText) {
final TinyDB tinydb = new TinyDB(getApplicationContext());
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
TinyDB tinydb = new TinyDB(getApplicationContext());
try {
Document doc = Jsoup.connect("https://www.ls-tc.de/de/aktie/" + ISIN).get();
System.out.println(ISIN);
increase = doc.selectFirst("#page_content > div > div:nth-child(1) > div > div.mpe_bootstrapgrid.col-md-8 > div > div:nth-child(3) > div > span:nth-child(3)").text().replace(" ", "");
tinydb.putString(ISIN + "notification_price", doc.selectFirst("#page_content > div > div:nth-child(1) > div > div.mpe_bootstrapgrid.col-md-8 > div > div:nth-child(3) > div > span:nth-child(1)").text() + "€");
} catch (IOException e) {
e.printStackTrace();
tinydb.putString(ISIN + "notification_price", "Error Scraping Price");
}
}
});
if(!thread.isAlive()) {
thread.start();
}
try{
thread.join();
}catch (Exception ex){
ex.printStackTrace();
}
if(!thread.isAlive()) {
notificationCompat = NotificationManagerCompat.from(getApplicationContext());
System.out.println("done");
System.out.println(tinydb.getString(ISIN + "notification_price"));
priceText.setText(tinydb.getString(ISIN + "notification_price"));
increaseText.setText(increase);
System.out.println("Text Updated " + priceText.getText().toString());
if(tinydb.getBoolean(ISIN + "_notification_status")) {
Notification notification = new NotificationCompat.Builder(getApplicationContext(), App.notificationChannel)
.setSmallIcon(R.drawable.ic_baseline_attach_money_24).setContentTitle(tinydb.getString(ISIN + "notification_name")).setContentText(tinydb.getString(ISIN + "notification_price")).setPriority(NotificationCompat.PRIORITY_MAX).setCategory(NotificationCompat.CATEGORY_STATUS).setOnlyAlertOnce(true).build();
notificationCompat.notify(tinydb.getInt(ISIN + "_notification_id"), notification);
}
isUpdating = false;
}
}
finnally these are the stacktraces I get:
W/System.err: java.net.SocketTimeoutException: timeout
W/System.err: at com.android.okhttp.okio.Okio$3.newTimeoutException(Okio.java:225)
at com.android.okhttp.okio.AsyncTimeout.exit(AsyncTimeout.java:263)
W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:217)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:317)
at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:311)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:207)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:388)
at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:146)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:900)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:772)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:493)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:429)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:560)
W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:106)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:30)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:734)
W/System.err: at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:706)
W/System.err: at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:299)
W/System.err: at org.jsoup.helper.HttpConnection.get(HttpConnection.java:288)
at de.xliquid.stockwatchultimate.MainActivity$4.run(MainActivity.java:266)
W/System.err: at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: java.net.SocketException: socket is closed
at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:588)
at com.android.okhttp.okio.Okio$2.read(Okio.java:145)
at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
W/System.err: ... 18 more
java.net.UnknownHostException: Unable to resolve host "www.onvista.de": No address associated with hostname
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:156)
W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:192)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:144)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:106)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:400)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:333)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:483)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:429)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:560)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:106)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:30)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:734)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:706)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:299)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:288)
W/System.err: at de.xliquid.stockwatchultimate.MainActivity$6.run(MainActivity.java:371)
at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
W/System.err: at libcore.io.Linux.android_getaddrinfo(Native Method)
W/System.err: at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:200)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)
W/System.err: ... 22 more
Also this app is solely for me so I don't really bother if the solution isn't the cleanest or drains the battery faster.
The problem was energy saving mode, if it is turned on the phone won't do requests in background / idle mode, no matter the wakelock, I solved my problem by adding a permission, so the app can request data even when the phone is in energy saving standby.
I a new to Android programming.While trying to connect to PHP from my Android Client (WAMP) I get the following error
java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms
'I had searched for this type of error and had made all prescribed changes including Changing localhost to ipv address, changing the Timeout interval, configuring the httpd.conf file, still couldn't resolve.Pls find below the code, conf file changes and error log
Error Log:
java.net.SocketTimeoutException: failed to connect to /192.168.1.8 (port 8383) after 10000ms
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:169)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.net.Socket.connect(Socket.java:882)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.Connection.connect(Connection.java:148)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.example.vijayar.phpconnect.MainActivity$AsyncRetrieve.doInBackground(MainActivity.java:80)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at com.example.vijayar.phpconnect.MainActivity$AsyncRetrieve.doInBackground(MainActivity.java:33)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-20 07:42:34.857 3370-3512/com.example.vijayar.phpconnect W/System.err: at java.lang.Thread.run(Thread.java:818)
02-20 07:42:35.007 3370-3510/com.example.vijayar.phpconnect V/RenderScript: 0xb0f4b600 Launching thread(s), CPUs 3
Java Code
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 10000;
TextView textPHP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textPHP = (TextView) findViewById(R.id.textPHP);
//Make call to AsyncRetrieve
new AsyncRetrieve().execute();
}
private class AsyncRetrieve extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
//this method will interact with UI, here display loading message
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
// This method does not interact with UI, You need to pass result to onPostExecute to display
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.1.8:8383/Checking/Checking.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
// this method will interact with UI, display result sent from doInBackground method
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equals("Success! This message is from PHP")) {
textPHP.setText(result.toString());
}else{
// you to understand error returned from doInBackground method
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Manifest File
<uses-permission android:name="android.permission.INTERNET"/>
In Httpd.conf the following changes are made
#Listen 12.34.56.78:8383
Listen 0.0.0.0:8383
Listen [::0]:8383
<Directory />
AllowOverride None
Options None
Allow from All
Require all granted
</Directory>
PHP file -> Checking.Php
<?php
echo "Success! This message is from PHP";
?>
The PHP page works fine when invoked from browser.
The problem looks like your Apache configuration might be listening on the wrong ip address. Android is trying to access the ip address 192.168.1.8:8383 and your Apache server needs to be on the same network with your Android device. I would recommend that you make sure your Android device is on the same network as the Apache server and that your server is setup to listen on the correct ip address that Android is trying to connect too.
Timeout issue is resolved, this is what I did, I had added IPV4 to Listen command in httpd.conf file and disabled temporarily the antivirus gateway (that was preventing request from hitting the server) –
Am using Parse DB for my backend , used method like Login,SaveInBackground,FindInBackGround, most of the function is working except, One function which uses SaveInBackground(){....} other method with same SaveInBackground () is working
This is the method for which the error occurred
private void xxdatat(final ParseObject receiverObject) {
ParseObject obj = new ParseObject(Constants.XXX);
obj.put("SENDER_ID", objdata); //parse object type
obj.put("RECIEIVER_ID", Robjdata); //parse object type
obj.put("REQUEST_TYPE", stingdata); //String type
obj.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e==null) {
DialogUtil.showDialog(mContext, "working");
} else {
DialogUtil.showDialog(mContext,"Not working");
}
}
});
I surfed through the internet and find some solutions to be made in parse configuration file.
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(APP_ID)
.clientKey(CLIENT_KEY)
.addNetworkInterceptor(new ParseLogInterceptor())
.server("https://parse.xxxyyyzzz.com/parse/")
.build());
The link is completed by "/"
As observed there are errors while converting the data from parse to JSONObject and the exception is also JSONException.
How to solve this issue? Thanks in advance.
com.parse.ParseRequest$ParseRequestException: bad json response
at com.parse.ParseRequest.newTemporaryException(ParseRequest.java:290)
at com.parse.ParseRESTCommand.onResponseAsync(ParseRESTCommand.java:308)
at com.parse.ParseRequest$3.then(ParseRequest.java:137)
at com.parse.ParseRequest$3.then(ParseRequest.java:133)
at bolts.Task$15.run(Task.java:917)
at bolts.BoltsExecutors$ImmediateExecutor.execute(BoltsExecutors.java:105)
at bolts.Task.completeAfterTask(Task.java:908)
at bolts.Task.continueWithTask(Task.java:715)
at bolts.Task.continueWithTask(Task.java:726)
at bolts.Task$13.then(Task.java:818)
at bolts.Task$13.then(Task.java:806)
at bolts.Task$15.run(Task.java:917)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:160)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.parse.ParseRESTCommand.onResponseAsync(ParseRESTCommand.java:298)
at com.parse.ParseRequest$3.then(ParseRequest.java:137)
at com.parse.ParseRequest$3.then(ParseRequest.java:133)
at bolts.Task$15.run(Task.java:917)
at bolts.BoltsExecutors$ImmediateExecutor.execute(BoltsExecutors.java:105)
at bolts.Task.completeAfterTask(Task.java:908)
at bolts.Task.continueWithTask(Task.java:715)
at bolts.Task.continueWithTask(Task.java:726)
at bolts.Task$13.then(Task.java:818)
at bolts.Task$13.then(Task.java:806)
at bolts.Task$15.run(Task.java:917)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Finally solved this issues by creating a new table in db with same structure and different name.
Now there is no issues working fine.
UPDATED:
Ok, after a few days of testing and debugging... I GOT IT TO WORK, but not the way I want.
The reason it crashed previously was because of "reorientation" of the camera during lockscreen, apparently, that crashes often.
Once I forced it to use landscape mode, it works. However, I don't want it to use landscape mode; I want it to work in portrait mode.
The code is taken directly from Android Studio's sample (Media -> MediaRecorder). The sample had the code working in landscape mode, and I can't figure how to get it to use portrait mode so I can avoid re-orientation and thus avoid the crashes?
There's nothing in the onPause, onResume code and the stacktrace pointed toward this method being called.
Easy Reproduce:
1) Use Android Studio to get the MediaRecord Sample app
2) In the manifest, change, android:screenOrientation="landscape"> to Portrait.
3) The App won't launch now.
I added mCamera.setDisplayOrientation(90), same issue.
Code:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private boolean prepareVideoRecorder(){
// BEGIN_INCLUDE (configure_preview)
mCamera = CameraHelper.getDefaultCameraInstance();
// We need to make sure that our preview and recording video size are supported by the
// camera. Query camera to find all the sizes and choose the optimal size given the
// dimensions of our preview surface.
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
Camera.Size optimalSize = CameraHelper.getOptimalPreviewSize(mSupportedPreviewSizes,
mPreview.getWidth(), mPreview.getHeight());
// Use the same size for recording profile.
CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
profile.videoFrameWidth = optimalSize.width;
profile.videoFrameHeight = optimalSize.height;
// likewise for the camera object itself.
parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight);
mCamera.setParameters(parameters);
try {
// Requires API level 11+, For backward compatibility use {#link setPreviewDisplay}
// with {#link SurfaceView}
mCamera.setPreviewTexture(mPreview.getSurfaceTexture());
} catch (IOException e) {
Log.e(TAG, "Surface texture is unavailable or unsuitable" + e.getMessage());
return false;
}
// END_INCLUDE (configure_preview)
// BEGIN_INCLUDE (configure_media_recorder)
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(profile);
// Step 4: Set output file
mMediaRecorder.setOutputFile(CameraHelper.getOutputMediaFile(
CameraHelper.MEDIA_TYPE_VIDEO).toString());
mMediaRecorder.setOrientationHint(90);
// END_INCLUDE (configure_media_recorder)
MediaScannerConnection.scanFile(this, new String[] { CameraHelper.getOutputMediaFile(
CameraHelper.MEDIA_TYPE_VIDEO).getPath() }, new String[] { "video/mp4" }, null);
// Step 5: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
Logs:
06-27 02:18:08.244 25734-25752/com.watchdawg.watchdawg E/MediaRecorder﹕ start failed: -22
06-27 02:18:08.253 25734-25752/com.watchdawg.watchdawg E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.watchdawg.watchdawg, PID: 25734
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: start failed.
at android.media.MediaRecorder.start(Native Method)
at com.watchdawg.watchdawg.RecordActivity$MediaPrepareTask.doInBackground(RecordActivity.java:276)
at com.watchdawg.watchdawg.RecordActivity$MediaPrepareTask.doInBackground(RecordActivity.java:267)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Whenever the application is removed from the recent task list, process will not be cleaned up completely, it is just that the UI will be cleaned up. So it is app responsibility to cleanup the resource held by your activity or app. Hence, you need to override onTaskRemoved() method in your service(Android service) component and perform cleanup(releasing mediaplayer instance etc).
try this way:
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoFrameRate(24);
mMediaRecorder.setVideoSize(720,480);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mPreview.setRotation(90);
instead of mMediaRecorder.setProfile(profile);
hope it works!