1

I have been using a ASYNC TASK to send or fetch the data from my app to the database and vice-versa via REST API. The Code i have been using for my few projects(completed) is what i use in other new projects too.I have now created a new project and the working async code is not fetching data anymore, but the same code i paste in any previous projects, it works well. I have a new project starting tomorrow and i want the code i am ease to use works well in new projects too. To be considered that INTERNET PERMISSION ADDED IN MANIFEST.. The code in MainActivity.java that should display the Toast from database on postExecute

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    String name;
    ArrayList<String> NAME=new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new getpostcount().execute();
    }

    public class getpostcount extends AsyncTask<String, String, String> {
        String db_url;


        @Override
        protected void onPreExecute() {
            //   Toast.makeText(newsFeed.this, "Loading........", Toast.LENGTH_SHORT).show();
            db_url = "http://testprasis.000webhostapp.com/getshopname.php";

        }

        @Override
        protected String doInBackground(String... args) {

            try {
                URL url = new URL(db_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                StringBuffer buffer = new StringBuffer();
                StringBuilder stringBuilder = new StringBuilder();
                String line = "";

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);

                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                String data = stringBuilder.toString().trim();

                String json;

                InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
                int size = stream.available();
                byte[] buffer1 = new byte[size];
                stream.read(buffer1);
                stream.close();

                json = new String(buffer1, "UTF-8");
                JSONArray jsonArray = new JSONArray(json);

                for (int i = 0; i <= jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (jsonObject.getString("id") != null) {
                        name = jsonObject.getString("shop_name");

                        NAME.add(name);


                    }
                }


                return null;


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
//
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
              Toast.makeText(MainActivity.this,NAME.get(0), Toast.LENGTH_SHORT).show();
        }
    }
}

LOGCAT:

2019-11-27 17:13:00.044 26790-26790/com.sheershakx.hisab E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sheershakx.hisab, PID: 26790
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.get(ArrayList.java:437)
        at com.sheershakx.hisab.MainActivity$getpostcount.onPostExecute(MainActivity.java:119)
        at com.sheershakx.hisab.MainActivity$getpostcount.onPostExecute(MainActivity.java:38)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.access$600(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6810)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Mike M.
  • 38,532
  • 8
  • 99
  • 95
Sheershak
  • 39
  • 6

2 Answers2

1

Why it didn't work all of the sudden?

Actually it will work but on Android version lower that Android P. Because Android P uses HTTPS by default. What this means is that if you are using unencrypted HTTP requests in your app, the app will work fine in all versions(lower) of Android except Android P.

How to make it work on Android P?

  1. You just need to create a network_security_config file in the xml folder and then include it in the manifest in the following manner.

The network_security_config file looks like this.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">nikit19.github.io</domain>
    </domain-config>
</network-security-config>

Add it in Manifest as

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config"
                    ... >
        ...
    </application>
</manifest>
  1. Simply use this in Manifest inside application

    android:usesCleartextTraffic="true"
    
Arnold Brown
  • 1,330
  • 13
  • 28
0

I think i have been fool around for few days as the problem is solved : I just forgot to add android:usesCleartextTraffic="true" in my manifest file.Now it works well Since it did not show in my logcat error i have been fooling myself. Thanks everyone for your comment.

Sheershak
  • 39
  • 6
  • It did show in your logcat. You're printing the stack trace for the Exception it was throwing: `catch (IOException e) { e.printStackTrace(); }`. That's why I suggested that you look further up in your logcat. – Mike M. Nov 29 '19 at 10:08