【问题标题】:Android: deleting a row from a tableAndroid:从表中删除一行
【发布时间】:2015-05-20 16:50:15
【问题描述】:

当我尝试从表中删除一行时遇到问题,当我创建一个 JSON 文件以将表的数据保存在那里时出现了这个问题。一切正常,除非我按下删除图标,然后该行仍然存在。我将在下面发布 mainactivity 类和数据库类。 如果您能帮助我,我将不胜感激。

public class MainActivity extends Activity {

    LinearLayout mainLayout=null;
    EditText name=null,brand=null,cost=null;
    Button insertRecord=null,showRecords=null;
    Button orderbyname=null,orderbybrand=null,orderbycost=null;
    ArrayList<Car> result=new ArrayList<Car>();
    TableLayout resultLayout=null;
    Database db=null;

    LinearLayout jsonLayout=null;
    Button loadJSON=null,saveJSON=null;

    public void makeJSON()
    {
        jsonLayout=new LinearLayout(this);
        mainLayout.addView(jsonLayout);
        loadJSON=new Button(this);
        loadJSON.setText("LOAD JSON");
        jsonLayout.addView(loadJSON);
        loadJSON.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                 AlertDialog.Builder alert = new 
                            AlertDialog.Builder(MainActivity.this);
                 alert.setTitle("Load FILE");
                 alert.setMessage("Specify file name: ");
                 final EditText input = new EditText(MainActivity.this);
                 alert.setView(input);
                 alert.setPositiveButton("Ok", 
                            new DialogInterface.OnClickListener() 
                          {
                            public void onClick(DialogInterface dialog, int whichButton) 
                            {
                                  String value = input.getText().toString();
                                  File myfile=new File(
                                            Environment.getExternalStorageDirectory(),value);
                                    try {
                                        BufferedReader br = new BufferedReader(
                                                new InputStreamReader(new 
                                                    FileInputStream(myfile), "utf8"),65536);
                                          String line="";
                                          line=br.readLine();
                                          try {
                                            JSONArray x=new JSONArray(line);
                                            Log.d("TEST","I have read "+x);
                                            int i;
                                            db.clearData();
                                            for(i=0;i<x.length();i++)
                                            {
                                                JSONObject p=x.getJSONObject(i);
                                                String name=p.getString("name");
                                                String brand=p.getString("brand");
                                                double cost =p.getDouble("cost");
                                                db.insert(name, brand, cost);
                                            }
                                        } catch (JSONException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                          br.close();

                                    }catch(IOException e)
                                    {
                                        Log.d("TEST",e.getMessage());
                                    }
                            }});
                 alert.setNegativeButton("Cancel", new 
                            DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) 
                      {
                      }
                    });

                    alert.show();
                }       

        });
        saveJSON=new Button(this);
        saveJSON.setText("SAVE JSON");
        saveJSON.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                result=db.getResults();
                final JSONArray x=new JSONArray();
                int i;
                for(i=0;i<result.size();i++)
                {
                    JSONObject p=new JSONObject();
                    try {
                        p.put("name", result.get(i).name);
                        p.put("brand",result.get(i).brand);
                        p.put("cost", result.get(i).cost);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    x.put(p);
                }
                String s=x.toString();
             AlertDialog.Builder alert = new 
                        AlertDialog.Builder(MainActivity.this);
             alert.setTitle("Create FILE");
             alert.setMessage("Specify file name: ");
             final EditText input = new EditText(MainActivity.this);
             alert.setView(input);
             alert.setPositiveButton("Ok", 
                        new DialogInterface.OnClickListener() 
                      {
                        public void onClick(DialogInterface dialog, int whichButton) 
                        {
                              String value = input.getText().toString();
                              File myfile=new File(
                                        Environment.getExternalStorageDirectory(),value);
                                try {
                                    Writer out = new BufferedWriter(new OutputStreamWriter(
                                            new FileOutputStream(myfile), "UTF8"));
                                    out.append(x.toString());
                                    out.flush();
                                    out.close();
                                    Log.d("TEST", "Write "+x);
                                }catch(IOException e)
                                {
                                    Log.d("TEST",e.getMessage());
                                }
                        }});
             alert.setNegativeButton("Cancel", new 
                        DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) 
                  {
                  }
                });

                alert.show();
            }       


        });
        jsonLayout.addView(saveJSON);

    }

    public void makeInputs()
    {
        LinearLayout l1=new LinearLayout(this);
        mainLayout.addView(l1);
        name=new EditText(this);
        name.setHint("Car name");
        l1.addView(name);
        brand=new EditText(this);
        brand.setHint("Car brand");
        l1.addView(brand);
        cost=new EditText(this);
        cost.setHint("Car cost");
        l1.addView(cost);
    }   
    public void makeButtons()
    {
        LinearLayout l2=new LinearLayout(this);
        mainLayout.addView(l2);
        insertRecord=new Button(this);
        insertRecord.setText("INSERT RECORD");
        l2.addView(insertRecord);
        showRecords=new Button(this);
        showRecords.setText("SHOW RECORDS");
        l2.addView(showRecords);
        insertRecord.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                db.insert(name.getText().toString(),
                        brand.getText().toString(),
                        Double.parseDouble(cost.getText().toString()));

            }

        });
        showRecords.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                result=db.getResults();
                updateTable();

            }

        });
    }

    public void makeTable()
    {
        resultLayout=new TableLayout(this);
        ScrollView scroll=new ScrollView(this);
        mainLayout.addView(scroll);
        scroll.addView(resultLayout);
        TableRow r1=new TableRow(this);
        resultLayout.addView(r1);
        orderbyname=new Button(this);
        orderbyname.setText("NAME");
        r1.addView(orderbyname);
        orderbybrand=new Button(this);
        orderbybrand.setText("BRAND");
        r1.addView(orderbybrand);
        orderbycost=new Button(this);
        orderbycost.setText("COST");
        r1.addView(orderbycost);
        orderbyname.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                int i,j;
                for(i=0;i<result.size();i++)
                {
                    for(j=0;j<result.size()-1;j++)
                    {
                        Car c1=result.get(j);
                        Car c2=result.get(j+1);
                        if(c1.name.compareTo(c2.name)<0)
                        {
                            result.set(j, c2);
                            result.set(j+1, c1);
                        }
                    }
                }
                updateTable();

            }

        });
        orderbybrand.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                int i,j;
                for(i=0;i<result.size();i++)
                {
                    for(j=0;j<result.size()-1;j++)
                    {
                        Car c1=result.get(j);
                        Car c2=result.get(j+1);
                        if(c1.brand.compareTo(c2.brand)<0)
                        {
                            result.set(j, c2);
                            result.set(j+1, c1);
                        }
                    }
                }
                updateTable();

            }

        });
        orderbycost.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                int i,j;
                for(i=0;i<result.size();i++)
                {
                    for(j=0;j<result.size()-1;j++)
                    {
                        Car c1=result.get(j);
                        Car c2=result.get(j+1);
                        if(c1.cost<c2.cost)
                        {
                            result.set(j, c2);
                            result.set(j+1, c1);
                        }
                    }
                }
                updateTable();

            }

        });

    }

    public void updateTable()
    {
        resultLayout.removeAllViews();
        makeTable();
        int i;
        for(i=0;i<result.size();i++)
        {
            Car c=result.get(i);
            TableRow r=new TableRow(this);
            resultLayout.addView(r);
            TextView t1,t2,t3;
            t1=new TextView(this);
            t1.setText(c.name);
            t2=new TextView(this);
            t2.setText(c.brand);
            t3=new TextView(this);
            t3.setText(""+c.cost);
            r.addView(t1);
            r.addView(t2);
            r.addView(t3);
            ImageView delimage=new ImageView(this);
            r.addView(delimage);
            delimage.setId(i);
            delimage.setImageResource(R.drawable.delete);
            delimage.setClickable(true);
            delimage.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    String cardetails="Name: "+
                        result.get(v.getId()).name+
                        " Brand: "+
                        result.get(v.getId()).brand+
                        " Cost: "+
                        result.get(v.getId()).cost;
                    Log.d("TEST","Delete Car is "+cardetails);

                }

            });
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainLayout=new LinearLayout(this);
        setContentView(mainLayout);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        db=new Database(this, "cars.db", null, 2);
        makeInputs();
        makeButtons();
        makeJSON();
        makeTable();
    }
}


public class Database extends SQLiteOpenHelper{

    private Context mcontext;
    private SQLiteDatabase database; 
    public Database(Context context, String name, CursorFactory factory,
            int version) {

        super(context, name, factory, version);
        mcontext=context;
        database=this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table autos(name text,brand text,cost double)");

    }
    public ArrayList<Car> getResults()
    {
        ArrayList<Car> x=new ArrayList<Car>();
        Cursor cursor=database.rawQuery("select * from autos",null);
        if(cursor.getCount()==0)
        {
            cursor.close();
            return null;
        }
        int nameindex=cursor.getColumnIndex("name");
        int brandindex=cursor.getColumnIndex("brand");
        int costindex=cursor.getColumnIndex("cost");
        cursor.moveToFirst();
        do
        {
            Car c;
            c=new Car(cursor.getString(nameindex),
                    cursor.getString(brandindex),
                    cursor.getDouble(costindex));
            x.add(c);
        }while(cursor.moveToNext());
        cursor.close();
        return x;

    }
    public void insert(String name,String brand,double cost)
    {
        database.execSQL("insert into autos(name,brand,cost) values('"+
            name+"','"+brand+"',"+cost+")");
    }

    public void clearData()
    {
        database.execSQL("delete from autos");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table autos");
        onCreate(db);
    }


}

【问题讨论】:

  • 尝试深入了解与您的问题相关的代码区域。如果用户不必解析整个类,您将获得更多答案!
  • 您没有任何代码可以从表中删除一行!
  • 是的,我的问题是代码,我试过了,但最终当我在我的平板电脑上运行应用程序时,当我按下删除按钮时它崩溃并关闭......你能建议使用什么代码吗?从表中删除一行?

标签: android json sqlite


【解决方案1】:

delimage 上的点击监听器在桌面上什么都不做。只需记录要删除的汽车:

    delimage.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            String cardetails="Name: "+
                result.get(v.getId()).name+
                " Brand: "+
                result.get(v.getId()).brand+
                " Cost: "+
                result.get(v.getId()).cost;
            Log.d("TEST","Delete Car is "+cardetails);

        }

    });

【讨论】:

  • 是的,这样我可以在 logcat 中看到一条消息,说明该项目已被删除。我试图编写一个代码来从表中删除一行,但是当我按下删除图像按钮时它会崩溃。这是我尝试过的代码: db.delete(result.get(v.getId()).name, result.get(v.getId()).brand, result.get(v.getId()).cost);结果=db.getResults();更新表();你有什么建议吗?
  • 你能贴出db.delete的代码是什么吗? db.delete(result.get(v.getId()).name, result.get(v.getId()).brand, result.get(v.getId()).cost); 这条线毫无意义。如果您指的是SQLiteDatabase.delete 方法...似乎您没有提供正确的表名,只是为了开始。请详细说明描述。
  • 别的。 Here你可以找到正确删除一行的样本。让我指出我认为最安全的this answer
  • 抱歉回复晚了,函数就是这个,它在数据库类中。 public void delete(String title, String name, String surname, double mark, String cmets) { database.execSQL("delete from subj where title='"+title+"' and name= '"+name+"' and surname=' "+surname+"' and mark="+mark+" and cmets = '"+cmets);我也会发布我如何调用该函数,我认为它是正确的.. 但是每当我单击要从表中删除的行旁边的删除图像时,程序就会崩溃并且 logcat 说有一个错误删除功能:/
  • delimage.setId(i); delimage.setImageResource(R.drawable.delete); delimage.setClickable(true); delimage.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String subjectdetails= "Title: "+ result.get(v.getId()).title+ "Name: "+ result.get(v. getId()).name+ "姓氏: "+ result.get(v.getId()).surname+ " Mark: "+ result.get(v.getId()).mark+ "Commnts: "+ result.get(v .getId()).cmets; Log.d("TEST","删除主题为"+subjectdetails);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 2011-02-18
  • 2014-12-29
相关资源
最近更新 更多