i am getting the following error when i try to debug the app, app is running without a crash but unable to load another location on map,
W/System.err: org.json.JSONException: Index 0 out of range [0..0)
W/System.err: at org.json.JSONArray.get(JSONArray.java:295)
at org.json.JSONArray.getJSONObject(JSONArray.java:523)
W/System.err: at praneeth.dev.androidpolorserver.TrackingOrder$1.onResponse(TrackingOrder.java:138)
W/System.err: at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:82)
at retrofit2.-
W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
W/System.err: at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
W/System.err: Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
W/System.err: at java.util.ArrayList.get(ArrayList.java:437)
at org.json.JSONArray.get(JSONArray.java:289)
... 11 more
this is my onResponse code,
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
String lat = ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lat").toString();
String lng = ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lng").toString();
LatLng orderLocation = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.foodagent);
bitmap = Common.scaledBitmap(bitmap,70,70);
MarkerOptions marker = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title("Order of "+Common.currentRequest.getPhone())
.position(orderLocation);
mMap.addMarker(marker);
mService.getDirections(yourLocation.latitude+","+yourLocation.longitude,
orderLocation.latitude+","+orderLocation.longitude,"API_CODE")
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
new ParseTask().execute(response.body().toString());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
call to toString(), is also redundant, can any one help me solve this. i am stuck at this for days
Related
I want to take an user Screenshot, I used this code. I was take 3 permission, READ_EXTERNAL_STORE,WRITE_EXTERNAL_STORE, and READ_EXTERNAL_STORAGE. Problem not fix. It show open failed: EPERM (Operation not permitted)
public void tackeAndSaveScreenShot(Activity mActivity) {
View MainView = mActivity.getWindow().getDecorView();
MainView.setDrawingCacheEnabled(true);
MainView.buildDrawingCache();
Bitmap MainBitmap = MainView.getDrawingCache();
Rect frame = new Rect();
mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//to remove statusBar from the taken sc
int statusBarHeight = frame.top;
//using screen size to create bitmap
int width = mActivity.getWindowManager().getDefaultDisplay().getWidth();
int height = mActivity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap OutBitmap = Bitmap.createBitmap(MainBitmap, 0, statusBarHeight, width, height - statusBarHeight);
MainView.destroyDrawingCache();
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
//you can also using current time to generate name
String name="YourName";
File file = new File(path, name + ".png");
fOut = new FileOutputStream(file);
OutBitmap.compress(Bitmap.CompressFormat.PNG, 1000, fOut);
fOut.flush();
fOut.close();
//this line will add the saved picture to gallery
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I check on my Logcat. they show the problem is in
fOut = new FileOutputStream(file);
I get permission properly.
private void userPermission2(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_CODE1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
userPermission2();
}else {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
}
I tried many why but don'work. Every time is the same problem.
The log is.
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10351; state: ENABLED
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/YourName.png: open failed: EPERM (Operation not permitted)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err: at com.example.myapplication.MainActivity.tackeAndSaveScreenShot(MainActivity.java:93)
W/System.err: at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:64)
W/System.err: at android.view.View.performClick(View.java:7570)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
W/System.err: at android.view.View.performClickInternal(View.java:7525)
W/System.err: at android.view.View.access$3900(View.java:836)
W/System.err: at android.view.View$PerformClick.run(View.java:28680)
W/System.err: at android.os.Handler.handleCallback(Handler.java:938)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:254)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8243)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8125)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
W/System.err: ... 16 more
String path = Environment.getExternalStorageDirectory().toString();
Change to:
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
And for Android 10 devices add android:legacyExternalStorage="true" to application tag in manifest file.
For Android 13+ devices you do not need any permission.
I want to iterate in a Json Objet. My Json file is :
[
{
"id": 2,
"tagw2": "flemme",
"conseil2": "travailler"
},
{
"id": 3,
"tagw": "flemme",
"conseil": "travailler"
}
]
But my android application always send a empty toast when I try to iterate. I do this with for. This is my code :
Button GetData;
GetData = (Button) findViewById(R.id.GetData);
GetData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = " myserverJsonIPs";
JsonArrayRequest request=new JsonArrayRequest(Request.Method.GET,url, null,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String GiveTagw = "";
String GiveConseil= "";
String testo;
try {
//JSONObject Info = response.getJSONObject(0);
for (int i=0;i<4;i++)
{
JSONObject Info = response.getJSONObject(i);
Toast.makeText(getApplicationContext(), GiveTagw, Toast.LENGTH_SHORT).show();
//testo = Info.getString(String.valueOf(id));
//GiveTagw = Arrays.asList(Info.getString("tagw").split("\\s*,\\s*"));
GiveTagw = Info.getString("tagw");
Toast.makeText(getApplicationContext(), GiveTagw , Toast.LENGTH_SHORT).show();
GiveConseil = Info.getString("conseil");
//testMap4.put(Arrays.asList(Info.getString("tagw").split("\\s*,\\s*")), GiveConseil);
//id = id + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
mTextViewResult.setText(GiveTagw);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextViewResult.setText("something wrong");
}
});
queue.add(request);
}
});
When I click in the button I created, I don't have "something wrong" error message but only a empty Textview and an empty Toast... I am so confused
When I click to the button the only thing I have in run is :
W/System.err: at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
W/libEGL: EGLNativeWindowType 0x6ee583fc90 disconnect failed
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x6ee583fc90 disconnect failed
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x6ee583fc90 disconnect failed
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x6ee583fc90 disconnect failed
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x6ee583fc90 disconnect failed
The new log run :
V/AudioManager: querySoundEffectsEnabled...
W/System.err: org.json.JSONException: No value for tagw
at org.json.JSONObject.get(JSONObject.java:399)
at org.json.JSONObject.getString(JSONObject.java:560)
W/System.err: at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:112)
at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:104)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
W/System.err: at android.os.Looper.loop(Looper.java:213)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
LogRun3
V/AudioManager: querySoundEffectsEnabled...
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/AwareBitmapCacher: handleInit switch not opened pid=3109
W/System.err: org.json.JSONException: No value for tagw
at org.json.JSONObject.get(JSONObject.java:399)
W/System.err: at org.json.JSONObject.getString(JSONObject.java:560)
at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:112)
at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:104)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
W/System.err: at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
LOGRUN 3
W/Settings: Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
V/HiTouch_HiTouchSensor: User setup is finished.
V/AudioManager: querySoundEffectsEnabled...
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/System.err: org.json.JSONException: No value for tagw
at org.json.JSONObject.get(JSONObject.java:399)
at org.json.JSONObject.getString(JSONObject.java:560)
at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:113)
at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:105)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
D/AwareBitmapCacher: handleInit switch not opened pid=6482
V/AudioManager: querySoundEffectsEnabled...
I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time
W/System.err: org.json.JSONException: No value for tagw
W/System.err: at org.json.JSONObject.get(JSONObject.java:399)
at org.json.JSONObject.getString(JSONObject.java:560)
at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:113)
W/System.err: at fr.apprentissage.version2.MainActivity$2$1.onResponse(MainActivity.java:105)
W/System.err: at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
W/System.err: at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
You are run toast in background thread, try to move toast in main thread.
// read obj1
JSONObject objResult1 = response.getJSONObject(0);
int id1 = objResult1.optInt("id");
String tagw1 = objResult1.optString("tagw2");
String conseil1 = objResult1.optString("conseil2");
// read obj2
JSONObject objResult2 = response.getJSONObject(1);
int id2 = objResult2.optInt("id");
String tagw2 = objResult2.optString("tagw");
String conseil2 = objResult2.optString("conseil");
new Handler(Looper.getMainLooper()).post(() -> {
Toast.makeText(getApplicationContext(), "id1:" + id1 + " tagw1:" + tagw1 + " conseil1" + conseil1 , Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "id2:" + id2 + " tagw2:" + tagw2 + " conseil2" + conseil2 , Toast.LENGTH_LONG).show();
});
Try with the following code may be it will help you.
public void onResponse(JSONArray response) {
String tagw = "";
String giveConseil = "";
try {
for (int i = 0; i < response.length(); i++) {
JSONObject info = response.getJSONObject(i);
int id = info.getInt("id");
if (info.has("tagw"))
tagw = info.getString("tagw");
if (info.has("tagw2"))
tagw = info.getString("tagw2");
if (info.has("conseil"))
giveConseil = info.getString("conseil");
if (info.has("conseil2"))
giveConseil = info.getString("conseil2");
Toast.makeText(getApplicationContext(), giveConseil, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I use Camera2 API for capturing OCR image in my App (Tablet only). Everything is work but there are one device (let say A Device) did'nt work. Here the log :
2021-05-28 13:46:23.402 28882-28937/com. D/OpenGLRenderer: textureCacheSize 75497472
2021-05-28 13:46:23.416 28882-28882/com. I/CameraManagerGlobal: Connecting to camera service
2021-05-28 13:46:33.303 28882-28975/com. W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'android.media.Image$Plane[] android.media.Image.getPlanes()' on a null object reference
2021-05-28 13:46:33.305 28882-28975/com. W/System.err: at com.Camera2Fragment$6$1.run(Camera2Fragment.java:927)
2021-05-28 13:46:33.307 28882-28975/com. W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
2021-05-28 13:46:33.308 28882-28975/com. W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
2021-05-28 13:46:33.310 28882-28975/com. W/System.err: at android.os.Looper.loop(Looper.java:193)
2021-05-28 13:46:33.311 28882-28975/com. W/System.err: at android.os.HandlerThread.run(HandlerThread.java:65)
Here my CaptureSession.CaptureCallback :
CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Bitmap bitmap = null;
String nik;
try {
System.out.println("Array plane : " + mImageReader.acquireLatestImage().getPlanes().toString());
ByteBuffer buffer = mImageReader.acquireLatestImage().getPlanes()[0].getBuffer(); // Error start from here, in other device, acquireLatestImage is not null, but in A device is become null
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (NullPointerException e) {
// **In one device, its fall to here**
e.printStackTrace();
}
if (bitmap == null) {
Toast.makeText(getActivity(), "Failed to get image, please try again", Toast.LENGTH_SHORT).show();
} else {
// other my code (proccessing image, ocr and other)
}
}
}
}
}
Extra :
The A device have screen specification 10 inch and 800x1280 and 8MP. I dont know its take a effect for the surface but its only happen in this device.
I have read some issues about getting an image from Camera2 API, but actually my code work on many many devices.
If I try requesting something from HTTP OnClick, it takes too long to complete the request and so I get a MainThread error that it’s taking too long. If I try to place it on a back thread, the contents aren’t where i need them to be by the time I need to use them.
My code is capable of parsing a JSON string, but the problem I have is getting the string from the server takes forever and doesn't get there by the time I need to parse.
It only works for me when I use the debugging tool, place a breakpoint before the request and after. Then, the string is there quick enough to parse.
FYI: I tried client.execute() and that resulted in a main thread issue which is why I now used client.enqueue() but then i don't get the data on time for the parsing.
Any help is appreciated, thank you!
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.weather_app, PID: 2774
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
**at com.example.weather_app.MainActivity.button1Pressed(MainActivity.java:91)**
My Button implementation: (error at: "** .... **")
public void button1Pressed(View view) {
Log.i("event", "Button 1 Pressed");
final TextView temperature = (TextView) this.findViewById(R.id.Temperature);
final TextView humidity = (TextView) this.findViewById(R.id.Humidity);
final TextView wind_speed = (TextView) this.findViewById(R.id.Wind_Speed);
final TextView precipitation = (TextView) this.findViewById(R.id.Precipitation);
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
Log.i("location", location.toString());
String url = "https://api.darksky.net/forecast/6e5fd8e33301bec5482dd3656d16cb32/" + location.getLatitude() + "," + location.getLongitude();
getAndParseData(url);
}
}
});
**temperature.setText(String.valueOf(weatherDataList.get(0).getHourly().getSummary()));**
humidity.setText(String.valueOf(weatherDataList.get(0).getCurrently().getHumidity()));
wind_speed.setText(String.valueOf(weatherDataList.get(0).getCurrently().getWindSpeed()));
precipitation.setText(String.valueOf(weatherDataList.get(0).getCurrently().getPrecipIntensity()));
}
Get and Parse Data from HTTP:
void getAndParseData(String url){
Request request = new Request.Builder()
.url(url)
.build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
data = "[" + response.body().string() + "]";
parseData(data);
}
}
});
}
void parseData(String weatherData){
try {
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
weatherDataList = mapper.readValue(weatherData, new TypeReference<List<WeatherData>>(){
});
} catch (IOException | NullPointerException ignore){}
}
A snippet of my Activity_Main.xml if needed:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="#string/button1"
android:textSize="20sp"
android:onClick="button1Pressed" />
I am new to android.I want to use my service for fetching the Json data from server.when I open my app then all works fine but when I exit my app or when my device go to sleep then there is a Json exception.how can I make my service run every-time in background. Please guide for solving this error.
error:-
E/agdghdgdgdrgrdgrdg: dgdgd
W/System.err: java.net.UnknownHostException: Unable to resolve host
"podgier-
woman.000webhostapp.com": No address associated with hostname
W/System.err: at
java.net.InetAddress.lookupHostByName(InetAddress.java:457)
W/System.err: at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
W/System.err: at
java.net.InetAddress.getAllByName(InetAddress.java:215)
W/System.err: at
org.apache.http.conn.DefaultClientConnectionOperator.openConnection
(DefaultClientConnectionOperator.java:137)
W/System.err:at org.apache.http.impl.conn.AbstractPoolEntry.open
(AbstractPoolEntry.java:164)
W/Systemerr:at
org.apache.http.impl.conn.AbstractPooledConnAdapter.open
(AbstractPooledConnAdapter.java:119)
W/System.err: at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:360)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:555)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:487)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:465)
W/System.err: at com.grover.jsonp.JSONParser.makeHttpRequest
(JSONParser.java:62)
W/System.err:at com.grover.jsonp.BackgroundService$gro.doInBackground
(BackgroundService.java:50)
W/System.err: at
com.grover.jsonp.BackgroundService$gro.doInBackground
(BackgroundService.java:41)
W/System.err:at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err:at java.util.concurrent.FutureTask.run
(FutureTask.java:237)
W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1112)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor
$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.GaiException:
android_getaddrinfo
failed: EAI_NODATA (No address associated with hostname)
W/System.err: at libcore.io.Posix.android_getaddrinfo(Native
Method)
W/System.err: at
libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
W/System.err: at
java.net.InetAddress.lookupHostByName(InetAddress.java:438)
W/System.err: ... 18 more
E/Buffer Error: Error converting result java.io.IOException: Attempted
read
on closed stream.
BackgroundService.java
public class BackgroundService extends Service
{
public BackgroundService(){
}
private static String url ="https://podgier-woman.000webhostapp.com/table.php";
JSONParser jParser = new JSONParser();
ArrayList<String> bcv;
class gro extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
java.util.List<NameValuePair> pr = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", pr);
bcv = new ArrayList<String>();
try {
JSONArray code = json.getJSONArray("code");
Log.d("list :",code.toString());
for (int i = 0; i < code.length(); i++) {
JSONObject c = code.getJSONObject(i);
bcv.add(c.getString("name"));
// adding each child node to HashMap key => value
// adding contact to contact list
JSONArray p = null;
}
}catch(JSONException e){
}
return null;
}
protected void onPostExecute(String file_url) {
Log.v("sdg","sgfdg"+record.idName);
if(record.idName < bcv.size()){
int xx= bcv.size() - record.idName;
Intent intent = new Intent(BackgroundService.this, record.class);
PendingIntent pIntent = PendingIntent.getActivity(BackgroundService.this, (int) System.currentTimeMillis(),intent, 0);
Log.d("SGsgzxv","dfgzdvv");
Notification n = new Notification.Builder(getApplicationContext())
.setContentTitle("View "+xx+" updated data")
.setContentText("data pending ")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher, "call", pIntent)
.addAction(R.mipmap.ic_launcher, "More", pIntent)
.addAction(R.mipmap.ic_launcher, "and more", pIntent)
.build();
Uri so = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
n.sound = so;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0,n);
}
record.idName = bcv.size();
bcv.clear();
}
}
private static final String TAG = "BackgroundService";
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");
#Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "in onCreate()");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
int counter = intent.getExtras().getInt("counter");
Log.v(TAG, "in onStartCommand(), counter = " + counter +
", startId = " + startId);
new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
.start();
return START_STICKY;
}
class ServiceWorker implements Runnable
{
private int counter = -1;
public ServiceWorker(int counter) {
this.counter = counter;
}
public void run() {
final String TAG2 = "ServiceWorker:" + Thread.currentThread().getId();
// do background processing here...
try {
Log.e(TAG2, "sleeping for 5 seconds. counter = " + counter);
while(true)
{
Thread.sleep(9000);
Log.e("agdghdgdgdrgrdgrdg","dgdgd");
new gro().execute();
}
} catch (InterruptedException e) {
Log.e(TAG2, "... sleep interrupted");
}
}
}
#Override
public void onDestroy()
{
}
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "in onBind()");
return null;
}
}
I don't recommend using a background service for such purposes. I know from experience that we are never sure that such a service will not be destroyed by the system.
To perform tasks (periodic, single) I recommend using Firebase Job Dispatcher. In my opinion, this is a more reliable mechanism when it comes to doing background work.
Here is an example of use, given by me: https://stackoverflow.com/a/44489327/8119117