0

I'm working on an android app for a project. Part of the project is populating a listview from a localhost database. I've attempted to debug the program and attempted to access the URL directly and using other android project. It runs just fine and does the job. I debugged the code down to the line http.connect and it throws an exception which in lead causes the respond variable to remain -1 and causes the whole program to screw over. I dont understand what is exactly happening and where is the source of the problem. A little nod to what im doing wrong would be appreciated. thank you.

Edit: THIS IS NOT A NULL POINTER ISSUE. I already studied the problem and debugged the code. As well as studied a question that deals with null pointers. This is nothing like it. The null pointer EXISTS but it isn't the main problem the main problem is the connection problem which CASUES the nullpointer

package com.example.databsemananger;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    String[] data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        boolean accepted;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if( ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)!= PackageManager.PERMISSION_GRANTED){

            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET},123);
        }
       DownloadTextTask test = new DownloadTextTask();

test.execute();
       /* String s="";
        String[] mobileArray =s.split(",");
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.activity_main, mobileArray);*/



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId())
        {
            case R.id.optionsItem:
            {
                Intent i = new Intent(getApplicationContext(),input.class);
                startActivity(i);
                setContentView(R.layout.activity_input);
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }







    private InputStream OpenHttp() throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL("http://192.168.1.103/webService/get.php");
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex)
        {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;
    }

    public String loadData(){
        int BufferSize_Size=1000;
        InputStream in=null;
        try{

            in=OpenHttp();
        } catch (IOException e) {
            e.printStackTrace();
        }

        InputStreamReader isr= new InputStreamReader(in);
        int charRead;
        String str="";
        char[] inputBuffer=new char[BufferSize_Size];
        try{
            while((charRead=isr.read(inputBuffer))>0){
                String readString= String.copyValueOf(inputBuffer,0,charRead);

            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return str;

    }

    private class DownloadTextTask extends AsyncTask<String,Void,String> {


        @Override
        protected String doInBackground(String... strings) {
            return loadData();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            int duration = Toast.LENGTH_SHORT;
            Context context = getApplicationContext();

            Toast toast = Toast.makeText(context, s, duration);
            toast.show();
           // ListView listView = (ListView) findViewById(R.id.items);
            //listView.setAdapter(adapter);
        }
    }
}

The stack and the error:

2020-05-07 02:46:45.758 14133-14133/? I/databsemanange: Not late-enabling -Xcheck:jni (already on)
2020-05-07 02:46:45.782 14133-14133/? I/databsemanange: Unquickening 12 vdex files!
2020-05-07 02:46:45.783 14133-14133/? W/databsemanange: Unexpected CPU variant for X86 using defaults: x86
2020-05-07 02:46:46.066 14133-14133/com.example.databsemananger I/databsemanange: The ClassLoaderContext is a special shared library.
2020-05-07 02:46:46.228 14133-14133/com.example.databsemananger D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-05-07 02:46:46.229 14133-14133/com.example.databsemananger D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-05-07 02:46:46.263 14133-14173/com.example.databsemananger D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2020-05-07 02:46:46.314 14133-14173/com.example.databsemananger D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2020-05-07 02:46:46.330 14133-14173/com.example.databsemananger D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2020-05-07 02:46:46.801 14133-14133/com.example.databsemananger W/databsemanange: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-05-07 02:46:46.801 14133-14133/com.example.databsemananger W/databsemanange: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-05-07 02:46:46.882 14133-14190/com.example.databsemananger D/Networking: Cleartext HTTP traffic to 192.168.1.103 not permitted
2020-05-07 02:46:46.882 14133-14190/com.example.databsemananger W/System.err: java.io.IOException: Error connecting
2020-05-07 02:46:46.882 14133-14190/com.example.databsemananger W/System.err:     at com.example.databsemananger.MainActivity.OpenHttp(MainActivity.java:102)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at com.example.databsemananger.MainActivity.loadData(MainActivity.java:112)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at com.example.databsemananger.MainActivity$DownloadTextTask.doInBackground(MainActivity.java:140)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at com.example.databsemananger.MainActivity$DownloadTextTask.doInBackground(MainActivity.java:135)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at android.os.AsyncTask$3.call(AsyncTask.java:394)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-05-07 02:46:46.883 14133-14190/com.example.databsemananger W/System.err:     at java.lang.Thread.run(Thread.java:923)
2020-05-07 02:46:46.904 14133-14190/com.example.databsemananger E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.databsemananger, PID: 14133
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$4.done(AsyncTask.java:415)
        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 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
        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:923)
     Caused by: java.lang.NullPointerException
        at java.io.Reader.<init>(Reader.java:78)
        at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
        at com.example.databsemananger.MainActivity.loadData(MainActivity.java:117)
        at com.example.databsemananger.MainActivity$DownloadTextTask.doInBackground(MainActivity.java:140)
        at com.example.databsemananger.MainActivity$DownloadTextTask.doInBackground(MainActivity.java:135)
        at android.os.AsyncTask$3.call(AsyncTask.java:394)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305) 
        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:923) 
Khaled A
  • 11
  • 3
  • Plz provide the logcat error – Zain May 07 '20 at 00:33
  • 1
    It's hard to help with an error without seeing the original error message. Please edit your post to include the exact wording of any error messages, including the full stack trace of any exceptions, if applicable, as well as which line of code the stack trace points to. – denvercoder9 May 07 '20 at 00:33
  • @sonnet yes sir. Give me a moment – Khaled A May 07 '20 at 00:43
  • try to change 'http' to 'https' of your url – Zain May 07 '20 at 00:50
  • Attempted the change. Same issue. – Khaled A May 07 '20 at 00:53
  • try to add `android:usesCleartextTraffic="true"` within of your manifest – Zain May 07 '20 at 00:55
  • Added. No change to the stack errors – Khaled A May 07 '20 at 00:59
  • Use the debugger and step through the code. You have a nullpointerexception in `loadData()` function. – denvercoder9 May 07 '20 at 01:14
  • 2
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – denvercoder9 May 07 '20 at 01:14
  • As i specified in the question's description. I already used the debugger and went through the code step by step..... the debugger indicated that the code crashes at the line http.connect. Please read the question more carefully – Khaled A May 07 '20 at 01:23
  • Create file res/xml/network_security_config.xml - ``` api.example.com(to be adjusted) ``` And use it in manifest under using `android:networkSecurityConfig="@xml/network_security_config"` – Zain May 07 '20 at 01:31
  • The part that i should adjust, the api.example.com is supposed to be in reverse. Correct? for example : com.example.databasemanager – Khaled A May 07 '20 at 02:21
  • just add 192.168.1.103 so that .. 192.168.1.103 – Zain May 07 '20 at 02:50
  • just did that, sadly no change. – Khaled A May 07 '20 at 03:36
  • 1
    @KhaledA Your stack trace clearly indicates that the crash is happening in `MainActivity.loadData`, specifically on line 117. It looks to me like sonnet did read your question carefully, because that's why you're getting that error. – Ryan M May 07 '20 at 10:10
  • Im aware that there is a null pointer exception but that has nothing to do with the real reason why the problem is occuring.... when the connection is not permitted the value at line 117 does not get updated because it gets its value from http.connect. This is not a null pointer problem this is a connection problem which was solved via adding extra configurations in the manifiest. My issue was not a null pointer exception even if that's the error given. And i specified why and how that happened, please remove the assocation and read the comment history carefully – Khaled A May 07 '20 at 12:59

1 Answers1

-1

i added the following line

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

and modified what zain suggested with

<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">api.example.com(to be adjusted)</domain> </domain-config> </network-security-config> And use it in manifest under <application>.

Finally i removed the s from https contrary to a previous suggestion.

Khaled A
  • 11
  • 3