-1

I have a trouble when I try to delete a row from a table, this problem appeared when I created a JSON file to keep the data of the table there. Everything works fine except when I press the delete icon then the row is still there. I will post the mainactivity class and the database class below. I will appreciate it if you could help me.

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);
    }


}
diatrevolo
  • 2,782
  • 26
  • 45
  • 1
    Try to hone in on the areas of your code relevant to your question. You'll get a lot more answers if users don't have to parse through entire classes! – diatrevolo May 20 '15 at 17:11
  • 1
    You don´t have any code to delete a row from the table!. – Jorgesys May 20 '15 at 17:18
  • Yes, my problem is the code, I tried but eventually when I run the app on my tablet it just crashed and closed when I pressed the delete button...could you suggest what code to use to delete a row from the table? – Ilias Papadopoulos May 20 '15 at 21:23

1 Answers1

1

Your on click listener on the delimage does nothing on the table. Simply logs the car to delete:

    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);

        }

    });
  • yes, this way I can see in the logcat a message saying the item is deleted. I tried to write a code to delete a row from the table but when I press the delete image button then it crashes. here's a code I tried : db.delete(result.get(v.getId()).name, result.get(v.getId()).brand, result.get(v.getId()).cost); result=db.getResults(); updateTable(); do you have any suggestions? – Ilias Papadopoulos May 20 '15 at 18:43
  • Can you post what is the code of the *db.delete*? The line ```db.delete(result.get(v.getId()).name, result.get(v.getId()).brand, result.get(v.getId()).cost); ``` makes little sense. If you are referring to the [SQLiteDatabase](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html).delete method... It seems you are not providing the proper table name, just for a start. Please elaborate a bit more on the description. – Ramón Gil Moreno May 20 '15 at 23:17
  • Something else. [Here](http://stackoverflow.com/questions/7510219/deleting-row-in-sqlite-in-android) you can find a sample of a proper deletion of a row. Let me point to [this answer](http://stackoverflow.com/a/7510442/1898234) which I consider the safest. – Ramón Gil Moreno May 20 '15 at 23:22
  • sorry for the late reply, the function is this and it's in the Database class. public void delete(String title, String name, String surname, double mark, String comments) { database.execSQL("delete from subj where title='"+title+"' and name= '"+name+"' and surname= '"+surname+"' and mark="+mark+" and comments = '"+comments); } I will post how I call the function too, I think it's correct.. but whenever I click on the delete image next to the row that I want to delete from the table, then the program crushes and the logcat says there's an error in the delete function :/ – Ilias Papadopoulos Jun 11 '15 at 01:00
  • 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+ "Surname: "+ result.get(v.getId()).surname+ " Mark: "+ result.get(v.getId()).mark+ "Commnts: "+ result.get(v.getId()).comments; Log.d("TEST","Delete Subject is "+subjectdetails); – Ilias Papadopoulos Jun 11 '15 at 01:07
  • db.delete(result.get(v.getId()).title, result.get(v.getId()).name, result.get(v.getId()).surname, result.get(v.getId()).mark, result.get(v.getId()).comments); result=db.getResults(); updateTable(); } – Ilias Papadopoulos Jun 11 '15 at 01:07
  • Please include any details in the question. Your code within the comments is unreadable. – Ramón Gil Moreno Jun 11 '15 at 14:02
  • sorry for everything, it's the first time I make a question here and I didn't bother to see how to make a comment with a code. Thanks for your response, actually I finally after many hours was able to solve my question and complete my program! – Ilias Papadopoulos Jun 11 '15 at 21:57