Получение данных из базы данных SQL - PullRequest
0 голосов
/ 30 марта 2020

Я использую android studio, чтобы создать приложение, которое извлекает данные из базы данных SQL. Я хочу связать некоторые данные с представлением списка на основе предоставленного идентификатора двигателя. Затем этот идентификатор покажет информацию о двигателе. Как я могу go сделать это? Я знаю, что не идеально подключаться напрямую к базе данных, но я просто делаю это, чтобы получить опыт и узнать.

SQL Table

UI

MainActivity . java

public class MainActivity extends AppCompatActivity {

Button button1;
TextView txtView1;
EditText editText1;
ConnectionClass connectionClass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    connectionClass = new ConnectionClass();
    button1=(Button)findViewById(R.id.btnSearch);
    txtView1=(TextView)findViewById(R.id.searchLbl);
    editText1=(EditText)findViewById(R.id.txtSearch);

    button1.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {

            String newValue = editText1.getText().toString().trim();

            if (newValue.toString().trim().equals("")) {
                txtView1.setText("Please Enter ID");
            }
            else
            {
                Connection con = connectionClass.CONN();

                if(con==null)
                {
                    String msg="Error in SQL Connection";
                }
                else
                {
                    String query= "Select * From Motors Where Id='"+newValue+"'";
                }
            }
        }


    });
}


ConnectionClass. java

public class ConnectionClass {

String ip = "*************";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "****";
String un = "*****";
String password = "*****";

@SuppressLint("NewApi")
public Connection CONN() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection conn = null;
    String ConnURL = null;
    try {

        Class.forName(classs);
        ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
                + "databaseName=" + db + ";user=" + un + ";password="
                + password + ";";
        conn = DriverManager.getConnection(ConnURL);
    } catch (SQLException se) {
        Log.e("ERRO", se.getMessage());
    } catch (ClassNotFoundException e) {
        Log.e("ERRO", e.getMessage());
    } catch (Exception e) {
        Log.e("ERRO", e.getMessage());
    }
    return conn;
}


Activity_main. xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">


        <EditText
            android:id="@+id/txtSearch"
            android:layout_width="285dp"
            android:layout_height="42dp"
            android:layout_below="@+id/textHeading"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10px"
            android:layout_marginTop="30px"
            android:layout_weight="1"
            android:background="@android:color/holo_blue_bright"
            android:hint="enter id"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1"
            android:textColor="@color/material_deep_teal_500" />

        <TextView
            android:id="@+id/textHeading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_marginTop="30px"
            android:layout_weight="1"
            android:text="Motor Information"
            android:textAlignment="center"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#2eb114"
            android:textSize="70px" />

        <Button
            android:layout_width="85dp"
            android:layout_height="42dp"
            android:text="Search"
            android:id="@+id/btnSearch"
            android:layout_weight="0.43"
            android:background="@color/background_material_dark"
            android:textColor="#ffffff"
            android:layout_gravity="center_vertical"
            android:layout_alignBottom="@+id/txtSearch"
            android:layout_toRightOf="@+id/txtSearch"
            android:layout_toEndOf="@+id/txtSearch"
            android:layout_marginLeft="10px"
            android:layout_marginStart="10px"
            android:layout_marginRight="10px"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/searchLbl"
            android:layout_below="@+id/txtSearch"
            android:layout_alignLeft="@+id/txtSearch"
            android:layout_alignStart="@+id/txtSearch"
            android:layout_marginTop="64dp" />

        <GridView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/gridViewEmp"
            android:layout_alignRight="@+id/txtSearch"
            android:layout_alignEnd="@+id/txtSearch"
            android:layout_below="@+id/txtSearch" />


    </RelativeLayout>
</RelativeLayout>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...