Problem with .getToken() java.io.IOException: INVALID_TARGET_VERSION - java

gettoken() throws INVALID_TARGET_VERSION error in Android 10
I used this dependency and this method.
implementation platform('com.google.firebase:firebase-bom:28.4.2')
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-analytics'
FirebaseMessaging.getInstance().subscribeToTopic(topic).addOnCompleteListener((task) -> {
if (!task.isSuccessful()) {
return;
}
});
FirebaseMessaging.getInstance().getToken().addOnCompleteListener((task)-> {
if (!task.isSuccessful()) {
return;
}
// Get new FCM registration token
String token = task.getResult();
});
this is error content
E/FirebaseMessaging: Failed to sync topics. Won't retry sync. INVALID_TARGET_VERSION
D/IMI: =====> Fetching FCM registration token failed java.io.IOException: INVALID_TARGET_VERSION
W/System.err: java.io.IOException: INVALID_TARGET_VERSION
at com.google.firebase.iid.GmsRpc.handleResponse(com.google.firebase:firebase-iid##21.0.1:7)
at com.google.firebase.iid.GmsRpc.lambda$extractResponseWhenComplete$0$GmsRpc(Unknown Source:8)
at com.google.firebase.iid.GmsRpc$$Lambda$0.then(Unknown Source:2)
at com.google.android.gms.tasks.zzc.run(com.google.android.gms:play-services-tasks##17.2.1:3)
at com.google.firebase.iid.FirebaseIidExecutors$$Lambda$0.execute(Unknown Source:0)
at com.google.android.gms.tasks.zzd.zza(com.google.android.gms:play-services-tasks##17.2.1:1)
at com.google.android.gms.tasks.zzr.zzb(com.google.android.gms:play-services-tasks##17.2.1:5)
at com.google.android.gms.tasks.zzw.zza(com.google.android.gms:play-services-tasks##17.2.1:3)
at com.google.android.gms.tasks.zzc.run(com.google.android.gms:play-services-tasks##17.2.1:8)
at com.google.android.gms.cloudmessaging.zzz.execute(Unknown Source:0)
at com.google.android.gms.tasks.zzd.zza(com.google.android.gms:play-services-tasks##17.2.1:1)
at com.google.android.gms.tasks.zzr.zzb(com.google.android.gms:play-services-tasks##17.2.1:5)
at com.google.android.gms.tasks.zzw.zza(com.google.android.gms:play-services-tasks##17.2.1:3)
at com.google.android.gms.tasks.TaskCompletionSource.setResult(com.google.android.gms:play-services-tasks##17.2.1:1)
at com.google.android.gms.cloudmessaging.zzq.zza(com.google.android.gms:play-services-cloud-messaging##16.0.0:9)
at com.google.android.gms.cloudmessaging.zzs.zza(com.google.android.gms:play-services-cloud-messaging##16.0.0:7)
at com.google.android.gms.cloudmessaging.zzf.zza(com.google.android.gms:play-services-cloud-messaging##16.0.0:45)
at com.google.android.gms.cloudmessaging.zzi.handleMessage(Unknown Source:2)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:247)
at android.app.ActivityThread.main(ActivityThread.java:8656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
I followed the example, but I do not understand the content of this error. What problem do I have?

Related

BluetoothDevice.getUuids() returns null

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.

java.io.FileNotFoundException: open failed: EACCES (Permission denied) while trying to record using JobIntentService

I'm trying to set up an android call recorder using a Broadcast Receiver and a JobIntentService. However, whenever I launch the JobIntentService, the Mediarecorder.prepare() method throws an error as follows:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Music/filename.3gp: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
W/System.err: at com.example.callrecorder.Job.recordCall(Job.java:77)
W/System.err: at com.example.callrecorder.Job.onHandleWork(Job.java:38)
W/System.err: at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:392)
W/System.err: at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
W/System.err: at android.os.AsyncTask$3.call(AsyncTask.java:378)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
W/System.err: ... 12 more
I/Try: java.io.FileNotFoundException: /storage/emulated/0/Music/filename.3gp: open failed: EACCES (Permission denied)
E/MediaRecorder: start called in an invalid state: 4
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.callrecorder, PID: 10311
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.example.callrecorder.Job.recordCall(Job.java:82)
at com.example.callrecorder.Job.onHandleWork(Job.java:38)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:392)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:919)
The code for my JobIntentService is as follows:
public class Job extends JobIntentService {
static final int JOB_ID = 1000;
String state;
MediaRecorder mediaRecorder;
static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, Job.class, JOB_ID, intent);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.i("Job", "Triggered");
state = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
switch (state) {
case "OFFHOOK": {
recordCall();
}
break;
case "IDLE": {
stopRecording();
}
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void stopRecording() {
Log.i("Stato", "Stopped");
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
private void recordCall() {
String recordPath = null;
String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC).getAbsolutePath();
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
String myFile = "filename.3gp";
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(dir + "/" + myFile);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
Log.i("Try", String.valueOf(e));
}
mediaRecorder.start();
Log.i("Stato", "Started");
}
}
The intent for this service is passed from a Broadcast Receiver and it all runs fine is I try to check by removing the media recorder part. For some reason, it throws errors whenever I try to start the media recorder saying Permission Denied.
I have given WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, RECORD_AUDIO, READ_PHONE_STATE, PROCESS_OUTGOING_CALLS permissions in the Android Manifest file.
The jobservice and receiver have been registered as well.
From Android 10 onwards, you need legacy permission to access storage the old way or switch to using the new methods.
Add this under applications in Manifest for legacy storage.
android:requestLegacyExternalStorage="true"
Recording calls feature has also been stopped from android 10 so you can no longer record calls on it without accessibility options.

FATAL EXCEPTION: CameraX-audio encoding thread

I am recording videos using the camera X library. When i take video for 5 seconds before that (i,e)two seconds if i close the video its crashing with above error.How to handle this run time exception in android cameraX library
E/AndroidRuntime: FATAL EXCEPTION: CameraX-audio encoding thread
Process: .debug, PID: 4625
java.lang.IllegalStateException
at android.media.MediaCodec.native_dequeueOutputBuffer(Native Method)
at android.media.MediaCodec.dequeueOutputBuffer(MediaCodec.java:2698)
at androidx.camera.core.VideoCapture.audioEncode(VideoCapture.java:705)
at androidx.camera.core.VideoCapture$1.run(VideoCapture.java:340)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.os.HandlerThread.run(HandlerThread.java:65)
sometimes the below issue
FATAL EXCEPTION: CameraX-video encoding thread
Process: <packagename>, PID: 10794
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaCodec.dequeueOutputBuffer(android.media.MediaCodec$BufferInfo, long)' on a null object reference
at androidx.camera.core.VideoCapture.videoEncode(VideoCapture.java:604)
at androidx.camera.core.VideoCapture$2.run(VideoCapture.java:348)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.os.HandlerThread.run(HandlerThread.java:65)
in this samples also not fixed yet
https://github.com/android/camera-samples/issues/2#issuecomment-546812852
By adding a callback to videoCapture.startRecording(videoFile, executor, onVideoSavedCallback); you should be able to handle the exeption in the onError method.
/**
* Define callback that will be triggered after a video has been taken and saved to disk
*/
private VideoCapture.OnVideoSavedCallback onVideoSavedCallback= new VideoCapture.OnVideoSavedCallback() {
#SuppressLint("RestrictedApi")
#Override
public void onVideoSaved(#NonNull File file) {
Log.d("VIDEO_CAPTURE", "Video capture succeeded");
}
#Override
public void onError(int videoCaptureError, #NonNull String message, #Nullable Throwable cause) {
Log.e("VIDEO_CAPTURE", "Video capture failed");
if (cause != null) {
cause.printStackTrace();
Toast.makeText(context,"Video capture failed",Toast.LENGTH_LONG).show();
}
}
};

com.parse.ParseRequest$ParseRequestException: bad json response With Parse error code 100

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.

android OkHttpClient Requesting Error

I am trying to store some data in mysql database using my android app. I am using okhttp3 to send request , but an error appears to me at this line:
client.newCall(request).execute();
I tried it on local machine and online but it gives me the same error here is the code ,
public class MainActivity extends AppCompatActivity {
String token1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("MainActivity is :" + FirebaseInstanceId.getInstance().getToken());
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
token1=FirebaseInstanceId.getInstance().getToken();
}
public void clicking(View view) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and here is the log:
com.example.user.firebasenot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.firebasenot, PID: 3280
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:172)
at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:138)
at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:80)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:178)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:129)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:98)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:124)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:170)
at okhttp3.RealCall.execute(RealCall.java:60)
at com.example.user.firebasenot.MainActivity.clicking(MainActivity.java:54)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
The error message says it all:
Caused by: android.os.NetworkOnMainThreadException
You are not supposed to make network requests on the main (aka UI) thread.
There are many ways in which you can make this request on a different thread, here's one:
final OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
final okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
});
But okhttp makes it easier for us to make asynchronous requests using the enqueue method:
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// you code to handle response
}
);
Here is how you should go about debugging your code:
Your 1st cue in the log that states,
java.lang.IllegalStateException: Could not execute method for
android:onClick
tells you that there is something wrong with you onClick method implementation, which in this case is clicking(View view). You then go on to hunt for your next hint, which is your 2nd cue in the log that states,
Caused by: android.os.NetworkOnMainThreadException
and that certainly is happening in your clicking(View view) method implementation line that you pointed out. It's making a network request from the main thread; and oh!, Android system reckons it a bad thing.
So what is the way out? You can use any of the following alternatives methods:
Alternative 1: View.post(Runnable) or View.postDelayed(Runnable, long)
Alternative 2: Activity.runOnUiThread(Runnable)
Alternative 3: Handler
Alternative 4: AsyncTask
I have demoed each of these alternatives, including the wrong way like the one you showcased in my Github project titled, DemoThreadsAndProcesses. Please feel free to (fork and) download it and play with it to see which implementation alternative suits your interest and go about using it in you own very project.
For quick check, I'll go about implementing your clicking(View view) like below:
public void clicking(View view) {
new MakeNetworkRequestAsyncTask().execute();
}
private void makeNetworkRequest() {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MakeNetworkRequestAsyncTask extends AsyncTask<Void, Void, Void> {
// The system calls this to perform work in a worker thread and
// delivers it the parameters given to AsyncTask.execute()
protected transient Void doInBackground(Void[] params) {
makeNetworkRequest();
}
// The system calls this to perform work in the UI thread and
// delivers the result from doInBackground() method defined above
#Override
protected void onPostExecute(Void result) {}
}
Hope that helps!

Categories