如何在databasehelper android studio上进行额外查询?

时间:2018-04-11 07:53:25

标签: android sqlite android-studio

  

我想从databasehelper的查询中获取列表,其中id_instrumen从另一个活动的listview获取。这是我的代码   DatabaseHelper

public List<Pengecekan> getListPengecekan() {

    Pengecekan pengecekan = null;
    List<Pengecekan> PengecekanList = new ArrayList<>();
    openDataBase();
    Cursor cursor = myDataBase.rawQuery("SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat FROM  tb_pengecekan A, tb_alat B, tb_instrumen C  " +
            "WHERE C.id_instrumen = B.id_instrumen AND A.id_alat = B.id_alat AND C.id_instrumen = '?' ", null);


    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
        PengecekanList.add(pengecekan);
        cursor.moveToNext();
    }
    cursor.close();
    close();
    return PengecekanList;
}
  

ListInstrumen.java

    package com.example.ibtb.bmkg;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ibtb.bmkg.adapter.ListInstrumenAdapter;
import com.example.ibtb.bmkg.adapter.ListPengecekanAdapter;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.Instrumen;
import com.example.ibtb.bmkg.model.Pengecekan;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class ListInstrumen extends AppCompatActivity {
    private ListView lvInstrumen;
    private ListInstrumenAdapter adapterinstrumen;
    private TextView instrumen;
    private List<Instrumen> mInstrumenList;

    private DatabaseHelper myDbHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_instrumen);
        lvInstrumen = (ListView) findViewById(R.id.listview_instrumen);
        //instrumen = (TextView) findViewById(R.id.tv_instrumenn);
        myDbHelper = new DatabaseHelper(this);


        File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
        if(false == database.exists()) {
            myDbHelper.getReadableDatabase();
            //Copy db
            if(copyDatabase(this)) {
                Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        mInstrumenList = myDbHelper.getListInstrumen();
        adapterinstrumen = new ListInstrumenAdapter(this, mInstrumenList);
        lvInstrumen.setAdapter(adapterinstrumen);

        lvInstrumen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int idInstrumen = (int) view.getTag();
                //Toast.makeText(getApplicationContext(), idInstrumen + "", Toast.LENGTH_SHORT).show();
                //Toast.makeText(getApplicationContext(), ((TextView) view.findViewById(R.id.tv_instrumenn)).getText().toString(), Toast.LENGTH_SHORT).show();

                //TextView a = (TextView) findViewById(R.id.tv_instrumenn);
                String str = ((TextView) view.findViewById(R.id.tv_instrumenn)).getText().toString();
                Intent i = new Intent (ListInstrumen.this, ListPengecekan.class);
                i.putExtra("ins", String.valueOf(str));
                startActivity(i);

                Intent j = new Intent (ListInstrumen.this, ListPengecekan.class);
                j.putExtra("id", String.valueOf(id));
                startActivity(j);


            }
        });}

    private boolean copyDatabase(Context context) {
        try {
            InputStream inputStream = context.getAssets().open(DatabaseHelper.DB_NAME);
            String outFileName = DatabaseHelper.DB_PATH + DatabaseHelper.DB_NAME;
            OutputStream outputStream = new FileOutputStream(outFileName);
            byte[] buff = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buff)) > 0) {
                outputStream.write(buff, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            Log.v("ListInstrumen", "DB copied");
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // });

        // }

    }

}
  

ListPengecekan.java

    package com.example.ibtb.bmkg;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ibtb.bmkg.adapter.ListPengecekanAdapter;
import com.example.ibtb.bmkg.database.DatabaseHelper;
import com.example.ibtb.bmkg.model.Pengecekan;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class ListPengecekan extends AppCompatActivity {
    private ListView lvPengecekan;
    private TextView instrumen;

    private ListPengecekanAdapter adapter;

    private List<Pengecekan> mPengecekanList;
    private Button btnAdd;
    private DatabaseHelper myDbHelper;

    //Cursor c = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pengecekan);
        lvPengecekan = (ListView) findViewById(R.id.listview_pengecekan);

        btnAdd = (Button)findViewById(R.id.Badd);
        myDbHelper = new DatabaseHelper(this);

        String instrumen = getIntent().getStringExtra("ins");
        String X = getIntent().getStringExtra("id");
        TextView tv = (TextView) findViewById(R.id.tv_instrumen);
        tv.setText(instrumen);

        File database = getApplicationContext().getDatabasePath(DatabaseHelper.DB_NAME);
        if(false == database.exists()) {
            myDbHelper.getReadableDatabase();
            //Copy db
            if(copyDatabase(this)) {
                Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //String id = getIntent().getStringExtra("id");
        mPengecekanList = myDbHelper.getListPengecekan(X);
        adapter = new ListPengecekanAdapter (this, mPengecekanList);
        lvPengecekan.setAdapter(adapter);


            }


    @Override
    protected void onResume() {
        super.onResume();
        String X = getIntent().getStringExtra("id");
        mPengecekanList = myDbHelper.getListPengecekan(X);
        //Init adapter
        adapter.updateList(mPengecekanList);
    }

    private boolean copyDatabase(Context context) {
        try {
            InputStream inputStream = context.getAssets().open(DatabaseHelper.DB_NAME);
            String outFileName = DatabaseHelper.DB_PATH + DatabaseHelper.DB_NAME;
            OutputStream outputStream = new FileOutputStream(outFileName);
            byte[] buff = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buff)) > 0) {
                outputStream.write(buff, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            Log.v("ListPengecekan", "DB copied");
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // });

         }



    public void onRadioButtonClicked(View view) {

        String kondisi="";
        boolean checked = ((RadioButton) view).isChecked();


        switch(view.getId()) {
            case R.id.B:
                if (checked)
                    kondisi = "Baik";

                break;
            case R.id.RR:
                if (checked)
                    kondisi = "Rusak ringan";
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(ListPengecekan.this);
                View mView = getLayoutInflater().inflate(R.layout.dialogrusak, null);
                mBuilder.setTitle("Keterangan kerusakan");
                final Spinner mSpinner = (Spinner) mView.findViewById(R.id.Spenanganan);
                final Spinner mSpinner1 = (Spinner) mView.findViewById(R.id.Shasil);
                final EditText kronologi = (EditText) mView.findViewById(R.id.ekro);
                final EditText lapor = (EditText) mView.findViewById(R.id.elapor);

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSpinner.setAdapter(adapter);

                ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
                adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSpinner1.setAdapter(adapter1);

                mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String Kronologi = kronologi.getText().toString();
                        Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();

                        if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
                            Toast.makeText(ListPengecekan.this, mSpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                            dialogInterface.dismiss();
                        }

                        if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
                            Toast.makeText(ListPengecekan.this, mSpinner1.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                            dialogInterface.dismiss();
                        }

                        String Lapor = lapor.getText().toString();
                        Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
                    }
                });

                mBuilder.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();

                    }
                });

                mBuilder.setView(mView);
                AlertDialog dialog = mBuilder.create();
                dialog.show();




                    break;
            case R.id.RB:
                if (checked)
                    kondisi = "Rusak berat";

                AlertDialog.Builder mBuilder1 = new AlertDialog.Builder(ListPengecekan.this);
                View mView1 = getLayoutInflater().inflate(R.layout.dialogrusak, null);
                mBuilder1.setTitle("Keterangan kerusakan");
                final Spinner mSpinner2 = (Spinner) mView1.findViewById(R.id.Spenanganan);
                final Spinner mSpinner3 = (Spinner) mView1.findViewById(R.id.Shasil);
                final EditText kronologi1 = (EditText) mView1.findViewById(R.id.ekro);
                final EditText lapor1 = (EditText) mView1.findViewById(R.id.elapor);

                ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.penaganan));
                adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSpinner2.setAdapter(adapter2);

                ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(ListPengecekan.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.hasil));
                adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSpinner3.setAdapter(adapter3);

                mBuilder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String Kronologi = kronologi1.getText().toString();
                        Toast.makeText(ListPengecekan.this, Kronologi, Toast.LENGTH_SHORT).show();

                        if (!mSpinner2.getSelectedItem().toString().equalsIgnoreCase("Pilih penanganan…")) {
                            Toast.makeText(ListPengecekan.this, mSpinner2.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                            dialogInterface.dismiss();
                        }

                        if (!mSpinner3.getSelectedItem().toString().equalsIgnoreCase("Pilih hasil…")) {
                            Toast.makeText(ListPengecekan.this, mSpinner3.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
                            dialogInterface.dismiss();
                        }

                        String Lapor = lapor1.getText().toString();
                        Toast.makeText(ListPengecekan.this, Lapor, Toast.LENGTH_SHORT).show();
                    }
                });

                mBuilder1.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();

                    }
                });

                mBuilder1.setView(mView1);
                AlertDialog dialog1 = mBuilder1.create();
                dialog1.show();

                break;
        }

        //myDbHelper.execSQl
    }
}

1 个答案:

答案 0 :(得分:0)

您需要传递id,然后在rawQuery的第二个参数中将其用作String数组,如下所示: -

public List<Pengecekan> getListPengecekan(long id) { //<<<< CHANGED 

    String[] whereargs = new String[]{String.valueOf(id)}; //<<<< ADDED

    Pengecekan pengecekan = null;
    List<Pengecekan> PengecekanList = new ArrayList<>();
    openDataBase();
    Cursor cursor = myDataBase.rawQuery(
        "SELECT A.id_pengecekan, A.pengecekan, A.normal, B.nama_alat " +
        "FROM  tb_pengecekan A, tb_alat B, tb_instrumen C  " +
        "WHERE C.id_instrumen = B.id_instrumen AND A.id_alat = B.id_alat AND C.id_instrumen = '?' ", whereargs); //<<<< CHANGED 
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
        PengecekanList.add(pengecekan);
        cursor.moveToNext();
    }
    cursor.close();
    close();
    return PengecekanList;
}

现在只需调用传递相应id的getListPengecekan方法即可。

P.S。当您使用唯一标识行的ID时,您可以使用: -

    if (cursor.moveToFirst()) {
        pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
        PengecekanList.add(pengecekan);
    }

而不是: -

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        pengecekan = new Pengecekan(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
        PengecekanList.add(pengecekan);
        cursor.moveToNext();
    }