• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Android polaczenie jdbc z serwerem ms sql co jest nie tak?

0 głosów
254 wizyt
pytanie zadane 1 sierpnia 2016 w Android, Swift, Symbian przez adamek339 Użytkownik (600 p.)

Witam. Muszę chcę napisać aplikacje która połączy się z serwerem ms sql. Znalazłem na youtube ten kod i problem polega na tym, że cały czas gdy próbuję się połączyć dostaje komunikat "Check Your Internet Access!".

Baza jest udostępniona poprawnie ponieważ bez problemu łączę się z nią poprzez sql developer na innym komputerze.

 import android.annotation.SuppressLint;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Environment;
    import android.os.StrictMode;
    import android.provider.MediaStore;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.util.AndroidRuntimeException;
    import android.util.Base64;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import java.io.ByteArrayOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOError;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;

    /*
        This source code could be used for academic purposes only. Posting on other websites or blogs is only allowed with a dofollow link to the orignal content.
    */


    public class MainActivity extends ActionBarActivity
    {

        // Declaring Layouts buttons, imageview extra
        private static final int RESULT_LOAD_IMAGE = 1;
        Button uploadpic;
        ImageView imagebox;
        ProgressBar progressBar;
        // End Layouts buttons, imageview extra

        // Declaring connection variables and array,string to store data in them
        byte[] byteArray;
        String encodedImage;

        Connection con;
        String un,ip,db,password;
        // End Declaring connection variables and array,string to store data in them

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

            // Finding the declared layouts
            uploadpic = (Button) findViewById(R.id.button);
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            imagebox = (ImageView) findViewById(R.id.imageView);
            //End  Finding the declared layouts

            // Declaring connectivity credentials
            ip = "your server ip here";
            db = "your database name here";
            un = "your username for that database here";
            password = "your password for that database here";
            // End Declaring connectivity credentials

            progressBar.setVisibility(View.GONE);

            uploadpic.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // Opening the Gallery and selecting media
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&& !Environment.getExternalStorageState().equals(Environment.MEDIA_CHECKING))
                    {
                        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(galleryIntent,RESULT_LOAD_IMAGE );
                        // this will jump to onActivity Function after selecting image
                    }
                    else
                    {
                        Toast.makeText(MainActivity.this, "No activity found to perform this task", Toast.LENGTH_SHORT).show();
                    }
                    // End Opening the Gallery and selecting media
                }
            });
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK  && null != data)
            {
                // getting the selected image, setting in imageview and converting it to byte and base 64
                progressBar.setVisibility(View.VISIBLE);
                Bitmap originBitmap = null;
                Uri selectedImage = data.getData();
                Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
                InputStream imageStream;
                try
                {
                    imageStream = getContentResolver().openInputStream(selectedImage);
                    originBitmap = BitmapFactory.decodeStream(imageStream);
                }
                catch (FileNotFoundException e)
                {
                   System.out.println(e.getMessage().toString());
                }
                if (originBitmap != null)
                {
                    this.imagebox.setImageBitmap(originBitmap);
                    Log.w("Image Setted in", "Done Loading Image");
                    try
                    {
                        Bitmap image = ((BitmapDrawable) imagebox.getDrawable()).getBitmap();
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        image.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
                        byteArray = byteArrayOutputStream.toByteArray();
                        encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
                        // Calling the background process so that application wont slow down
                        UploadImage uploadImage = new UploadImage();
                        uploadImage.execute("");
                        //End Calling the background process so that application wont slow down
                    }
                    catch (Exception e)
                    {
                        Log.w("OOooooooooo","exception");
                    }
                    Toast.makeText(MainActivity.this, "Conversion Done",Toast.LENGTH_SHORT).show();
                }
                // End getting the selected image, setting in imageview and converting it to byte and base 64
            }
            else
            {
                System.out.println("Error Occured");
            }
        }

        public class UploadImage extends AsyncTask<String,String,String>
        {
            @Override
            protected void onPostExecute(String r)
            {
                // After successful insertion of image
                progressBar.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this , "Image Inserted Succesfully" , Toast.LENGTH_LONG).show();
                // End After successful insertion of image
            }
            @Override
            protected String doInBackground(String... params)
            {
                // Inserting in the database
                String msg = "unknown";
                try
                {
                    con = connectionclass(un, password, db, ip);
                    String commands = "Insert into MYIMAGE (picture) values ('" + encodedImage + "')";
                    PreparedStatement preStmt = con.prepareStatement(commands);
                    preStmt.executeUpdate();
                    msg = "Inserted Successfully";
                }
                catch (SQLException ex)
                {
                    msg = ex.getMessage().toString();
                    Log.d("Error no 1:", msg);
                }
                catch (IOError ex)
                {
                    msg = ex.getMessage().toString();
                    Log.d("Error no 2:", msg);
                }
                catch (AndroidRuntimeException ex)
                {
                    msg = ex.getMessage().toString();
                    Log.d("Error no 3:", msg);
                }
                catch (NullPointerException ex)
                {
                    msg = ex.getMessage().toString();
                    Log.d("Error no 4:", msg);
                }
                catch (Exception ex)
                {
                    msg = ex.getMessage().toString();
                    Log.d("Error no 5:", msg);
                }
                System.out.println(msg);
                return "";
                //End Inserting in the database
            }
        }



        @SuppressLint("NewApi")
        public Connection connectionclass(String user, String password, String database, String server)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Connection connection = null;
            String ConnectionURL = null;
            try
            {
                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                ConnectionURL = "jdbc:jtds:sqlserver://" + server+ database + ";user=" + user + ";password=" + password + ";";
                connection = DriverManager.getConnection(ConnectionURL);
            }
            catch (SQLException se)
            {
                Log.e("error no 1", se.getMessage());
            }
            catch (ClassNotFoundException e)
            {
                Log.e("error no 2", e.getMessage());
            }
            catch (Exception e)
            {
                Log.e("error no 3", e.getMessage());
            }
            return connection;
        }
    }

 

Zaloguj lub zarejestruj się, aby odpowiedzieć na to pytanie.

Podobne pytania

0 głosów
1 odpowiedź 640 wizyt
pytanie zadane 13 września 2017 w Java przez ebo96rok Bywalec (2,980 p.)
+1 głos
5 odpowiedzi 892 wizyt
pytanie zadane 22 września 2016 w Java przez Geek1234 Użytkownik (570 p.)
0 głosów
0 odpowiedzi 163 wizyt

93,754 zapytań

142,714 odpowiedzi

323,359 komentarzy

63,348 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

Twierdza Linux. Bezpieczeństwo dla dociekliwych

Aby uzyskać rabat -10%, użyjcie kodu pasja-linux, wpisując go w specjalne pole w koszyku.

...