q通过查找名称列以检索其他数据(描述,价格,持续时间)从另一个sqlite数据库检索数据

时间:2019-03-19 06:54:38

标签: android sqlite listview onclick

我的应用当前正在正常运行,我只想添加一项功能,通过该功能,单击列表视图(ListView of items)上的项目即可:

它可以将数据检索到Buyerhome活​​动(BuyerHome Activity(Retrieve data from Database)

从该特定商品名称中检索并从SellerHome活动(SellerHome Activity(Insert data to database))创建的数据库中检索其他数据,例如图像,起始价格,起始持续时间和说明。

Onclick列表视图:

mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            //code for onclick to go to BuyerHome activity
        }
    });

BuyerHome活动:

public class BuyerHome extends AppCompatActivity implements AdapterView.OnItemSelectedListener, NavigationView.OnNavigationItemSelectedListener {
EditText nameIn;
EditText commentIn;
TextView viewComment;
TextView textPrice;
Button postComment;
ListView olderComments;
private DrawerLayout drawer; //Drawer
private int currentPrice = 1 ;



DatabaseHelper2 myDB;
Cursor oldermessages, latestmessage;
Cursor latestprice;
//<<<<<<<<<< Added
SimpleCursorAdapter sma; //<<<<<<<<<< Added adapter for the ListView

DatabaseHelper4 myDB2;

//TextView countdownText;

//Button startTime;

private static final long START_TIME_IN_MILLIS = 600000;

private TextView mTextViewCountDown;
private Button mButtonStart;
private Button mButtonReset;

private CountDownTimer mCountDownTimer;

private boolean mTimerRunning;

private long mTimeLeftInMillis;
private long mEndTime;

private TextView TextViewPrice;
private Button newPrice;

DatabaseHelperUpload mDBUpload;

//private CountDownTimer countDownTimer;
//private long timeLeft = 10000;
//private boolean timerRunning;





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

    Spinner spinner = findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.Addon,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);


    newPrice = (Button)findViewById(R.id.button_bid);

    mDBUpload = new DatabaseHelperUpload(this);
    nameIn = (EditText) findViewById(R.id.nameInput);
    commentIn = (EditText) findViewById(R.id.commentText);
    viewComment = (TextView) findViewById(R.id.viewCommentText);
    olderComments = (ListView) findViewById(R.id.olderComments); //<<<<<<<<<< Added
    textPrice = (TextView)findViewById(R.id.textPrice);
    TextViewPrice = (TextView)findViewById(R.id.textview_newprice);


    Toolbar toolbar = findViewById(R.id.toolbar); //Drawer
    setSupportActionBar(toolbar);


    drawer = findViewById(R.id.drawer_layout); //Drawer

    mTextViewCountDown = (TextView)findViewById(R.id.text_view_countdown);
    mButtonStart = (Button)findViewById(R.id.buttonStart);
    mButtonReset = findViewById(R.id.button_reset);



    myDB2 = new DatabaseHelper4(this);
    newPrice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String price = textPrice.getText().toString();

            if (nameIn.length() != 0) {
                    String name = nameIn.getText().toString();

                    myDB2.addPrice(name, price);
                    nameIn.setEnabled(false);

                    displayPrice();
                    displayPrice2();

            }else{
                Toast.makeText(BuyerHome.this, "Please Insert Username To Bid.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,
            R.string.navigation_drawer_open,R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState(); //Drawer
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    myDB = new DatabaseHelper2(this);
    postComment = (Button) findViewById(R.id.buttonComment);
    postComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = nameIn.getText().toString();
            String comment = commentIn.getText().toString();

            if (nameIn.length() != 0 && commentIn.length() != 0) {
                myDB.addData(name, comment); //<<<<<<<<<< method starts changed lower case a
                nameIn.setEnabled(false);
                commentIn.setText("");
            } else {
                Toast.makeText(BuyerHome.this, "Insert fields",
                        Toast.LENGTH_SHORT).show();
            }
            displayComments(); //<<<<<<<<<< added to refresh the display according to the latest comments
        }
    });



    mButtonStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startTimer();
        }
    });

    mButtonReset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resetTimer();
        }
    });
}

@Override //Drawer
public void onBackPressed() {
    if(drawer.isDrawerOpen(GravityCompat.START)){
        drawer.closeDrawer(GravityCompat.START);
    } else{
        super.onBackPressed();
    }

}

//<<<<<<<<<< ADDED so will display comments whenever called including returning from another activity
@Override
protected void onResume() {
    super.onResume();
    displayComments();
    displayPrice();
    displayPrice2();

}

private void displayPrice2() {
    latestprice = myDB2.getLatestPrice();
    if (latestprice.moveToFirst()) {
        String a = String.valueOf(latestprice.getString(latestprice.getColumnIndex(DatabaseHelper4.COL_BID_PRICE)));
        currentPrice = Integer.parseInt(a);

    } else {
        TextViewPrice.setText("");
    }
}

private void displayPrice() {
    latestprice = myDB2.getLatestPrice();
    if (latestprice.moveToFirst()) {
        TextViewPrice.setText( latestprice.getString(latestprice.getColumnIndex(DatabaseHelper4.COL_BID_NAME))+
                " Bids $" + latestprice.getString(latestprice.getColumnIndex(DatabaseHelper4.COL_BID_PRICE)));
    } else {
        TextViewPrice.setText("");
    }
}

//<<<<<<<<<< ADDED entire method for displaying comments
private void displayComments() {
    latestmessage = myDB.getLatestComment();

    if (latestmessage.moveToFirst()) {
        viewComment.setText(
                latestmessage.getString(latestmessage.getColumnIndex(DatabaseHelper2.COL_COMMENT_NAME)) +
                        " said : " +
                        latestmessage.getString(latestmessage.getColumnIndex(DatabaseHelper2.COL_COMMENT_COMMENT)));
    } else {
        viewComment.setText("");
    }
    oldermessages = myDB.getAllButLatestComment();
    if (sma == null) {
        sma = new SimpleCursorAdapter(
                this,
                android.R.layout.simple_list_item_2,oldermessages,
                new String[]{DatabaseHelper2.COL_COMMENT_NAME,DatabaseHelper2.COL_COMMENT_COMMENT},
                new int[]{android.R.id.text1,android.R.id.text2},
                0
        );
        olderComments.setAdapter(sma);
    } else {
        sma.swapCursor(oldermessages);
    }
}

public void startTimer(){
    mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;

    mCountDownTimer = new CountDownTimer(mTimeLeftInMillis,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mTimeLeftInMillis = millisUntilFinished;
            updateTimer();
        }

        @Override
        public void onFinish() {
            Spinner spinner = findViewById(R.id.spinner);
            spinner.setEnabled(false);//upon finish,stop the function to bid and wait for seller to delete post.
        }
    }.start();
    mTimerRunning = true;
}

private void resetTimer() {
    mTimeLeftInMillis = START_TIME_IN_MILLIS;
    updateTimer();
    mButtonReset.setVisibility(View.INVISIBLE);
    mButtonStart.setVisibility(View.VISIBLE);
}

public void updateTimer(){
    int minutes = (int) (mTimeLeftInMillis/1000)/60;
    int seconds = (int) (mTimeLeftInMillis/1000) %60;

    String timeLeftFormat = String.format(Locale.getDefault(),"%02d:%02d", minutes,seconds);

    mTextViewCountDown.setText(timeLeftFormat);

}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String text = String.valueOf(parent.getItemAtPosition(position));

    int numberInSpinner = Integer.parseInt(text);

    int sum = numberInSpinner + currentPrice;
    textPrice.setText(Integer.toString(sum));
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    switch(menuItem.getItemId()){
        case R.id.nav_inst:
            startActivity(new Intent(getApplicationContext(), Instructions.class));
            break;
        case R.id.nav_buy:
            startActivity(new Intent(getApplicationContext(), BuyerHome.class));
            break;
        case R.id.nav_sell:
            startActivity(new Intent(getApplicationContext(), SellerHome.class));
            break;
        case R.id.nav_logout:
            startActivity(new Intent(getApplicationContext(), AucOn.class));
            break;
        case R.id.nav_email:
            startActivity(new Intent(getApplicationContext(), CustomerSupport.class));
            break;

    }
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
protected void onStop(){
    super.onStop();

    SharedPreferences prefs = getSharedPreferences("prefs",MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    editor.putLong("millisLeft",mTimeLeftInMillis);
    editor.putBoolean("timerRunning",mTimerRunning);
    editor.putLong("endTime",mEndTime);

    editor.apply();

    if (mCountDownTimer != null) {
        mCountDownTimer.cancel();
    }
}

@Override
protected void onStart(){
    super.onStart();

    SharedPreferences prefs = getSharedPreferences("prefs",MODE_PRIVATE);
    mTimeLeftInMillis = prefs.getLong("millisLeft", START_TIME_IN_MILLIS);
    mTimerRunning = prefs.getBoolean("timerRunning",false);

    updateTimer();

    if(mTimerRunning){
        mEndTime = prefs.getLong("endTime", 0);
        mTimeLeftInMillis = mEndTime - System.currentTimeMillis();


        if (mTimeLeftInMillis<0){
            mTimeLeftInMillis = 0;
            mTimerRunning = false;
            updateTimer();

        } else{
            startTimer();

        }
    }
}
}

SellerHome中的数据库:

public class DatabaseHelperUpload extends SQLiteOpenHelper {

private final static String DBNAME = "Auction";
private final static int DBVERSION = 2;

DatabaseHelperUpload(Context context){
    super(context, DBNAME, null, DBVERSION);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

public void insertData(String name, String description, String price, String duration, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO RECORD VALUES(NULL,?,?,?,?,?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1,name);
    statement.bindString(2,description);
    statement.bindString(3,price);
    statement.bindString(4,duration);
    statement.bindBlob(5,image);

    statement.executeInsert();

}

public void updateData(String name,String description,String price,String duration,byte[] image,int id){
    SQLiteDatabase database = getWritableDatabase();

    String sql = "UPDATE RECORD SET name=?,description=?,price=?,duration=?,image=? WHERE id=?";

    SQLiteStatement statement = database.compileStatement(sql);

    statement.bindString(1,name);
    statement.bindString(2,description);
    statement.bindString(3,price);
    statement.bindString(4,duration);
    statement.bindBlob(5,image);
    statement.bindDouble(5,(double)id);

    statement.execute();
    database.close();
}

public void deleteData(int id){
    SQLiteDatabase database = getWritableDatabase();

    String sql = "DELETE FROM RECORD WHERE id=?";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();
    statement.bindDouble(1,(double)id);

    statement.execute();
    database.close();
}

public Cursor getData(String sql){
    SQLiteDatabase database=getReadableDatabase();

    return database.rawQuery(sql,null);
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}

0 个答案:

没有答案