简体   繁体   English

如何更新我的ListView行

[英]How can I update my ListView row

I have added a data into listview by textboxes .... 我已经通过文本框将数据添加到列表视图中。

I want to update rows of a listview by tapping on a ListView. 我想通过点击ListView更新listview的行。 All row data is from the sqlite db and arrange the data again in my Textboxes. 所有行数据都来自sqlite数据库,然后再次在我的文本框中排列数据。

The listview activity and Addactivity are separated ... enter image description here listview活动和Addactivity是分开的... 在此处输入图像描述

I need your help 我需要你的帮助

SQLiteListAdapter.java: SQLiteListAdapter.java:

package com.androidstudio.myinventory;

import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by HP on 9/15/2017.
 */

public class SQLiteListAdapter extends BaseAdapter {

    Context context;
    ArrayList<String> Item_ID;
    ArrayList<String> ItemName;
    ArrayList<String> Quantity;


    ArrayList<String> Price;
    ArrayList<String> Value;
    //  ArrayList<String> Detail ;


    public SQLiteListAdapter(Context context, ArrayList<String> item_ID, ArrayList<String> itemName,
                             ArrayList<String> quantity, ArrayList<String> price, ArrayList<String> value) {
        this.context = context;
        this.Item_ID = item_ID;
        this.ItemName = itemName;
        this.Quantity = quantity;
        this.Price = price;
        this.Value = value;
        //this.Detail = detail;

    }


    @Override
    public int getCount() {
        return Item_ID.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View child, ViewGroup parent) {


        Holder holder;

        LayoutInflater layoutInflater;

        //Check if this is the first time creating this row for the listview
        if (child == null) {

            //get the Android's layout inflater service which will read row_details.xml
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //Fill the row view with the xml layout file
            child = layoutInflater.inflate(R.layout.edit_stock_row, null);

            //Row was null, need to get components from the row_details.xml
            holder = new Holder();
            //Fill the holder with the text view components
            holder.textviewid = (TextView) child.findViewById(R.id.tvsr);
            holder.textviewname = (TextView) child.findViewById(R.id.tvname);
            holder.textviewquantity = (TextView) child.findViewById(R.id.tvquantity);
            holder.textviewprice = (TextView) child.findViewById(R.id.tvprice);
            holder.textviewvalue = (TextView) child.findViewById(R.id.tvvalue);
            //holder.textviewdetail = (TextView) child.findViewById(R.id.tvdetail);


            //attach the holder to the row
            child.setTag(holder);

        } else {
            //row was created before! thus get the holder object from the row tag
            holder = (Holder) child.getTag();
        }

        //At this point we have our row, either created from new or got it from the row tag object
        //we can now fill the data

        //get our object from the list which is in the position of the listview
        //position is passed to the getView method by the listview


        holder.textviewid.setText(Item_ID.get(position));
        holder.textviewname.setText(ItemName.get(position));
        holder.textviewquantity.setText(Quantity.get(position));
        holder.textviewprice.setText(Price.get(position));
        holder.textviewvalue.setText(Value.get(position));
        // holder.textviewdetail.setText(Detail.get(position));


        //return to listview to show
        return child;
    }

    //A holder will be responsible to hold the components to improve listview performance
//We replicate the components in the row_details.xml
    public class Holder {
        TextView textviewid;
        TextView textviewname;
        TextView textviewquantity;
        TextView textviewprice;
        TextView textviewvalue;
        // TextView textviewdetail;

    }

}

Edit_Stock.java: Edit_Stock.java:

package com.androidstudio.myinventory;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class Edit_Stock extends AppCompatActivity {

    public static final String KEY1 = "key1";
    StockDBHelper stockDBHelper;
    SQLiteListAdapter ListAdapter;
    ListView listView;
    TextView textView;
    String search;
    SQLiteDatabase sqLiteDatabase;
    Cursor cursor;


    ArrayList<String> ID_ArrayList = new ArrayList<String>();
    ArrayList<String> NAME_ArrayList = new ArrayList<String>();
    ArrayList<String> QUANTITY_ArrayList = new ArrayList<String>();
    ArrayList<String> PRICE_ArrayList = new ArrayList<String>();
    ArrayList<String> VALUE_ArrayList = new ArrayList<>();
    // ArrayList<String> DETAIL_ArrayList = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit__stock);
        textView = (TextView) findViewById(R.id.tvdetail);

        stockDBHelper = new StockDBHelper(this);
        listView = (ListView) findViewById(R.id.listviewedit);


    }

    @Override
    protected void onResume() {

        ShowSQLiteDBdata();

        super.onResume();
    }

    private void ShowSQLiteDBdata() {

        sqLiteDatabase = stockDBHelper.getWritableDatabase();

        cursor = sqLiteDatabase.rawQuery("SELECT * FROM tbl_stock1", null);

        ID_ArrayList.clear();
        NAME_ArrayList.clear();
        QUANTITY_ArrayList.clear();
        PRICE_ArrayList.clear();
        VALUE_ArrayList.clear();
        //DETAIL_ArrayList.clear();

        if (cursor.moveToFirst()) {
            do {
                ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(stockDBHelper.COL_1)));

                NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(stockDBHelper.COL_2)));

                QUANTITY_ArrayList.add(cursor.getString(cursor.getColumnIndex(stockDBHelper.COL_10)));

                PRICE_ArrayList.add(cursor.getString(cursor.getColumnIndex(stockDBHelper.COL_9)));
                VALUE_ArrayList.add(cursor.getString(cursor.getColumnIndex(stockDBHelper.COL_5)));

                // DETAIL_ArrayList.add(cursor.getString(cursor.getColumnIndex(stockDBHelper.COL_7)));
               /* DETAIL_ArrayList.add(cursor.getColumnName(cursor.getColumnIndex(stockDBHelper.COL_7)));
                 DETAIL_ArrayList.iterator();
                 tvdetail.setText("Edit");*/
            } while (cursor.moveToNext());
        }

        ListAdapter = new SQLiteListAdapter(Edit_Stock.this, ID_ArrayList,
                NAME_ArrayList,
                QUANTITY_ArrayList,
                PRICE_ArrayList,
                VALUE_ArrayList
                // DETAIL_ArrayList

        );

        listView.setAdapter(ListAdapter);

        cursor.close();
    }


    public void tveditClick(View view) {

        String name = "";
        Intent intent = new Intent(Edit_Stock.this, AddStock.class);


        startActivity(intent);


        Toast.makeText(this, "cliced", Toast.LENGTH_SHORT).show();
    }

    //Edit works....................
    private void EditSQLiteDBdata() {
        // search=textView.toString();

    }
}

AddStock.java: AddStock.java:

package com.androidstudio.myinventory;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class AddStock extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    EditText etproductname, etitemname, etbrand, etdate, etcompany, etprice, etquantity, etnotilimit, etlocation, etphoto;
    EditText etdetail;
    Spinner spinner_category;
    Button btnsave;
    StockDBHelper stockDBHelper;
    Context context;

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


        stockDBHelper = new StockDBHelper(this);

        etproductname = (EditText) findViewById(R.id.etproduct_name);
        etitemname = (EditText) findViewById(R.id.etItem_name);
        etbrand = (EditText) findViewById(R.id.etbrand);
        etdate = (EditText) findViewById(R.id.etDate);
        spinner_category = (Spinner) findViewById(R.id.Spinner_category);
        etdetail = (EditText) findViewById(R.id.etdetail);
        etcompany = (EditText) findViewById(R.id.etcompany);
        etprice = (EditText) findViewById(R.id.etprice);
        etquantity = (EditText) findViewById(R.id.etquantity);
        etnotilimit = (EditText) findViewById(R.id.etnoti_limit);
        etlocation = (EditText) findViewById(R.id.etlocation);
        etphoto = (EditText) findViewById(R.id.etupdate_photo);

        btnsave = (Button) findViewById(R.id.btnsave);

        pupulateSpinner();
        image = (ImageView) findViewById(R.id.imageView);

    }


    DatePickerDialog.OnDateSetListener mpickerDialog;

    //  etDate onClick event method
    public void datePick(View view) {
        etdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(AddStock.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth
                        , mpickerDialog, year, month, day);

                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
            }
        });
        mpickerDialog = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                month = month + 1;
                Log.d("TAG", "onDateSet :" + month + "/" + day + "/" + year);
                String date = month + "/" + day + "/" + year;
                etdate.setText(date);

            }
        };
    }


    // spinner populating method called in oncreate()
    public void pupulateSpinner() {
        spinner_category.setOnItemSelectedListener(this);
        // String[] list = getResources().getStringArray(R.array.Categories);

      /*  ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.activity_add_stock,list);
        spinner_category.setAdapter(arrayAdapter);
*/

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.Categories, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
        spinner_category.setAdapter(adapter);
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

    }

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

    }

    ImageView image;
    Integer REQUEST_CAMERA = 1, SELECT_FILE = 0;

    public void photoClick(View view) {


        final CharSequence[] items = {"Take Photo", "Choose from Gallery",
                "Cancel"};

        AlertDialog.Builder builder = new AlertDialog.Builder(AddStock.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_CAMERA);

                } else if (items[item].equals("Choose from Gallery")) {

                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");

                    startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else if (items[item].equals("Cancel")) {

                    dialog.dismiss();
                }
            }


        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {


            if (requestCode == REQUEST_CAMERA) {
                // onCaptureImageResult(data);
                Bundle bundle = data.getExtras();
                final Bitmap bmp = (Bitmap) bundle.get("data");
                image.setImageBitmap(bmp);
            } else if (requestCode == SELECT_FILE) {
                Uri selectphotoUri = data.getData();
                image.setImageURI(selectphotoUri);
            }


        }
    }


    // save button onClick event
    public void saveStock(View view) {
        // Button button=new Button(context);
        //button.setText("View");
        //etdetail.setText(text);*/

        etdetail.setText("View");
        btnsave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isInserted = stockDBHelper.insertData(etitemname.getText().toString(), etproductname.getText().toString(),
                        etbrand.getText().toString(), etdate.getText().toString(), spinner_category.getSelectedItem().toString(),
                        etcompany.getText().toString(), etprice.getText().toString(), etquantity.getText().toString(),
                        etnotilimit.getText().toString(), etlocation.getText().toString(), etphoto.getText().toString());

                if (isInserted == true) {
                    Toast.makeText(AddStock.this, "Data inserted successfully", Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(AddStock.this, "Data was not inserted", Toast.LENGTH_SHORT).show();
            }
        });


    }

}

StockDBHelper.java StockDBHelper.java

package com.androidstudio.myinventory;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by HP on 9/10/2017.
 */

public class StockDBHelper extends SQLiteOpenHelper {
         public static final String DB_NAME = "stock1.db";
         public static final String TABLE_NAME = "tbl_stock1";
    public static final String COL_1 = "SERIAL";
    public static final String COL_2 = "ITEM_NAME";
    public static final String COL_3 = "PRODUCT_NAME";
    public static final String COL_4 = "BRAND";
    public static final String COL_5 = "DATE";
    public static final String COL_6 = "CATEGORY";
   // public static final String COL_7 = "DETAIL";
    public static final String COL_8 = "COMPANY";
    public static final String COL_9 = "PRICE";
    public static final String COL_10 = "QUANTITY";
    public static final String COL_11 = "NOTIFICATION_LIMIT";
    public static final String COL_12 = "LOCATION";
    public static final String COL_13 = "PHOTO";



    public StockDBHelper(Context context) {
        super(context,DB_NAME, null, 3);


    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + "(SERIAL INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "ITEM_NAME TEXT,PRODUCT_NAME TEXT,BRAND TEXT, DATE INTEGER ,CATEGORY TEXT,COMPANY TEXT,PRICE INTEGER," +
                "QUANTITY INTEGER,NOTIFICATION_LIMIT INTEGER,LOCATION TEXT,PHOTO TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
       sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " +   TABLE_NAME);
       onCreate(sqLiteDatabase);
    }

    public boolean insertData(String item_name,String product_name , String brand , String date , String category, String company,
                                   String price,String quantity, String noti_limit , String location,String photo)
    {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,item_name);
        contentValues.put(COL_3,product_name);
        contentValues.put(COL_4,brand);
        contentValues.put(COL_5,date);
        contentValues.put(COL_6,category);
        //contentValues.put(COL_7,detail);
        contentValues.put(COL_8,company);
        contentValues.put(COL_9,price);
        contentValues.put(COL_10,quantity);
        contentValues.put(COL_11,noti_limit);
        contentValues.put(COL_12 ,location);
        contentValues.put(COL_13,photo);


        long result = sqLiteDatabase.insert(TABLE_NAME,null,contentValues);

        if (result == -1)
        return  false;
        else
        return true;
    }
    public Cursor editdata(String id,SQLiteDatabase sqLiteDatabase){
        Cursor cursor;
        String \[\] projection = {COL_1,COL_2,COL_3,COL_4,COL_5,COL_6,COL_8,COL_9,COL_10,COL_11,COL_12,COL_13};
        String selection= COL_1+ " LIKE ?";
        String\[\] selection_arg={id};

        cursor=sqLiteDatabase.query(TABLE_NAME,projection,selection,selection_arg,null,null,null);
        return cursor;
    }

    // Show data in listview editing
    /*public void ShowListData(String Id, String item_name , String quantity , String price , String value, String detail)
    {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1,Id);
        contentValues.put(COL_2,item_name);
        contentValues.put(COL_10,quantity);
        contentValues.put(COL_9,price);
        // Value is to be brought by java coding
        contentValues.put(COL_7,detail);
    }*/
/*

    public Cursor insertDataIntoList(){
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
        Cursor res=sqLiteDatabase.rawQuery(" SELECT * FROM " + TABLE_NAME,null);
        return res;
    }
*/

}][2]

Just take row's parent click in adapter and catch the ID column from that click. 只需在适配器中获取行的父级单击,然后从该单击中捕获ID列即可。

Item_ID.get(position);

And then pass this through the intent to the Activity where you want to show all the data. 然后通过意图将其传递到要显示所有数据的活动。 And then get that ID and query to the database to get all the data. 然后获取该ID并查询数据库以获取所有数据。

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

You can use adapter.notifyDataSetChanged(); 您可以使用adapter.notifyDataSetChanged(); to refresh the listview. 刷新列表视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM