Android Json and AsyncTask Error : <p>i had written an code that sends data from the android application to the database using JSON Form but i am having some errors when it sends.</p>

<p>this is the class for registration:</p>

<pre><code>package com.subhi.tabhost;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;

import AddUser.AllUsersLoadSpinner;
import ConnectionDetector.ConnectionDetector;
import SpinnerFirstLoad.MultiSelectionSpinner;
import SpinnerFirstLoad.PlayersLoadSpinner;
import SpinnerFirstLoad.TeamsLoadSpinner;

public class Registeration extends AppCompatActivity {

    ConnectionDetector connectionDetector;
    private MultiSelectionSpinner multiSelectionSpinner;
    private MultiSelectionSpinner PlayersSelectSpinier;
    Button save;
    TextView name, email, userexists;

    ArrayList&lt;String&gt; TeamsList = new ArrayList&lt;String&gt;();
    ArrayList&lt;String&gt; UsersList = new ArrayList&lt;String&gt;();
    ArrayList&lt;String&gt; PlayersList = new ArrayList&lt;String&gt;();
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String Name = "nameKey";
    public static final String EMAIL = "emailKey";
    SharedPreferences sharedpreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registeration);


        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        String restoredText = sharedpreferences.getString(Name, null);
       /* if (restoredText != null) {
           // Intent intent = new Intent(getApplicationContext(), MainMenu.class);
            //startActivity(intent);
           // finish();

        }*/

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);


       // if (connectionDetector.isConnectingToInternet()) {
            name = (TextView) findViewById(R.id.name);
            email = (TextView) findViewById(R.id.email);
            userexists = (TextView) findViewById(R.id.btnLinkToLoginScreen);


            save = (Button) findViewById(R.id.btnRegister);
            multiSelectionSpinner = (MultiSelectionSpinner) findViewById(R.id.mySpinner);
            PlayersSelectSpinier = (MultiSelectionSpinner) findViewById(R.id.mySpinner2);

            TeamsLoadSpinner x1 = new TeamsLoadSpinner(this);
            x1.execute("http://192.168.1.106/add/index.php");

            AllUsersLoadSpinner allUsersLoadSpinner = new AllUsersLoadSpinner(this);
            allUsersLoadSpinner.execute("http://192.168.1.106/add/allusers.php");

            PlayersLoadSpinner x2 = new PlayersLoadSpinner(this);
            x2.execute("http://192.168.1.106/add/print.php");


            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    InsertData adduser = new InsertData();

                    String txtname = name.getText().toString();
                    String txtemail = email.getText().toString();
                    if (txtname.equals(""))
                        Toast.makeText(getApplicationContext(), "UserName Cannot Be Empty", Toast.LENGTH_LONG).show();
                    else {
                        if (txtemail.equals(""))
                            Toast.makeText(getApplicationContext(), "Email Cannot Be Empty ", Toast.LENGTH_LONG).show();
                        else {
                            if (isValidEmail(txtemail)) {
                                boolean x = false;

                                for (int i = 0; i &lt; UsersList.size(); i++) {
                                    if (UsersList.get(i).equals(txtname)) {
                                        x = true;
                                    }

                                }
                                if (x == false) {




                                    SharedPreferences.Editor editor = sharedpreferences.edit();

                                    editor.putString(Name, txtname);
                                    editor.putString(EMAIL, txtemail);
                                    editor.commit();




                                    adduser.execute("192.168.1.106/add/add.php", txtname, txtemail, multiSelectionSpinner.getSelectedItemsAsString(), PlayersSelectSpinier.getSelectedItemsAsString());






                                } else {

                                    //Toast.makeText(getApplicationContext(),"USER EXISTS",Toast.LENGTH_LONG).show();

                                    userexists.setText("User Alerady Exists, Please Choose Differnent User name ");
                                }

                            } else
                                Toast.makeText(getApplicationContext(), "Please Enter A valid Email", Toast.LENGTH_LONG).show();

                        }

                    }

                }
            });

       // }else {

            // Internet connection is not present
            // Ask user to connect to Internet
          //  showAlertDialog(Registeration.this, "No Internet Connection",
             //       "You don't have internet connection.", false);
       // }
    }


    public void showAlertDialog(final Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }



    private boolean isValidEmail(String email) {
        Pattern pattern = Patterns.EMAIL_ADDRESS;
        return pattern.matcher(email).matches();
    }


    public void SetTeams(ArrayList&lt;String&gt; list) {

        TeamsList = list;
        String[] stockArr = new String[TeamsList.size()];
        stockArr = TeamsList.toArray(stockArr);
        multiSelectionSpinner.setItems(stockArr);
    }

    public void SetUsers(ArrayList&lt;String&gt; list) {

        UsersList = list;

    }

    public void SetPlayers(ArrayList&lt;String&gt; players) {
        PlayersList = players;


        String[] stockArr = new String[PlayersList.size()];
        stockArr = PlayersList.toArray(stockArr);
        PlayersSelectSpinier.setItems(stockArr);
    }





    private class InsertData extends AsyncTask&lt;String,Void,Boolean&gt;
    {



        @Override
        protected Boolean doInBackground(String... urls) {

            OutputStream os=null;
            InputStream is=null;
            HttpURLConnection conn=null;



            try {



                URL url =new URL(urls[0]);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("UserName", urls[1]);
                jsonObject.put("Email", urls[2]);
                jsonObject.put("Teams", urls[3]);
                jsonObject.put("Players", urls[4]);
                String message=jsonObject.toString();
                Log.d(message, "Test");
                conn=(HttpURLConnection)url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setFixedLengthStreamingMode(message.getBytes().length);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                conn.connect();

                os=new BufferedOutputStream(conn.getOutputStream());
                os.write(message.getBytes());

                os.flush();

                is=conn.getInputStream();






            } catch (MalformedURLException e) {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();;
                e.printStackTrace();
                return  false;
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();;
                e.printStackTrace();
                return false;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finally {

                try {
                    assert os != null;
                    os.close();
                    assert is != null;
                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();
                }

                conn.disconnect();
            }


            return true;
        }



        @Override
        protected void onPostExecute(Boolean result) {
            if(result)
            {

                Toast.makeText(getApplicationContext(),"Insert Success",Toast.LENGTH_LONG).show();;
            }
            else {
                Toast.makeText(getApplicationContext(),"Insert Fail",Toast.LENGTH_LONG).show();;
            }

        }
    }
}
</code></pre>

<p>and this is the php code script:</p>

<pre><code>&lt;?php 


require ('config.php');
$con=mysqli_connect($servername,$username,$password,$db);


    $json = file_get_contents('php://input');
$obj = json_decode($json,true);




$txtname=$obj['UserName'];//$_POST['txtname'];
$txtemail=$obj['Email'];//$_POST['txtemail'];
$txtteam=$obj['Teams'];//$_POST['txtemail'];

$txtplayer=$obj['Players'];//$_POST['txtemail'];

mysqli_query($con,"insert into user (UserName,Email,TeamsInterested,PlayersIterested) values('$txtname','$txtemail','$txtteam','$txtplayer') ");
    echo "Inserted";





?&gt;
</code></pre>

<p>and this is the log cat :</p>

<pre><code>02-11 12:06:15.197 2301-2319/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
                                                 Process: com.subhi.tabhost, PID: 2301
                                                 java.lang.RuntimeException: An error occured while executing doInBackground()
                                                     at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                     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:841)
                                                  Caused by: java.lang.NullPointerException
                                                     at com.subhi.tabhost.Registeration$InsertData.doInBackground(Registeration.java:287)
                                                     at com.subhi.tabhost.Registeration$InsertData.doInBackground(Registeration.java:221)
                                                     at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                     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:841) 
02-11 12:06:15.201 530-843/? W/ActivityManager:   Force finishing activity com.subhi.tabhost/.Registeration
02-11 12:06:15.265 153-502/? W/genymotion_audio: out_write() limiting sleep time 42152 to 39909
02-11 12:06:15.469 530-843/? D/dalvikvm: GC_FOR_ALLOC freed 621K, 27% free 9319K/12628K, paused 6ms, total 7ms
02-11 12:06:15.481 530-843/? D/dalvikvm: GC_FOR_ALLOC freed 376K, 27% free 9315K/12628K, paused 12ms, total 12ms
02-11 12:06:15.497 530-545/? D/dalvikvm: GC_FOR_ALLOC freed 13K, 23% free 9791K/12628K, paused 12ms, total 12ms
02-11 12:06:15.501 530-545/? I/dalvikvm-heap: Grow heap (frag case) to 10.747MB for 1127532-byte allocation
02-11 12:06:15.509 530-539/? D/dalvikvm: GC_FOR_ALLOC freed 15K, 21% free 10876K/13732K, paused 11ms, total 11ms
</code></pre>

<p>and the log cat errors shows that are in code in two places:</p>

<pre><code>1-                    `os.close();`
2-      private class InsertData extends AsyncTask&lt;String,Void,Boolean&gt;
</code></pre>

<p>so if anyone can help me please?!</p>
