简体   繁体   中英

Aplication Crash when i press update or delete

my application crash every time when i press save button to update data or delete on movie details, and i can't figure out why. Here is some info: I added some data to my database (that part working fine), and i managed to display from database in custom list view. And now, on click event on list view i want to pull data from database, part with fetching data and seting in fields is working fine, but when i want to update or delete, application crash.

Please help.

here is my code:

MainActivity.java

public class MainActivity extends AppCompatActivity {

DBAdapter db;
SimpleCursorAdapter adapter;

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

    db = new DBAdapter(this);
    db.open();

    ListView lv = (ListView) findViewById(R.id.listView1);
    int layoutstyle=R.layout.liststyle;
    int[] xml_id = new int[] {
            R.id.txtname,
            R.id.txtnumber,
            R.id.textView2

    };
    String[] column = new String[] {
            "naziv",
            "zanr",
            "rejting"
    };
    Cursor row = db.fetchAllData();
    adapter = new SimpleCursorAdapter(this, layoutstyle,row,column, xml_id, 0);
    lv.setAdapter(adapter);
    //onClick function
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
            Cursor row = (Cursor) adapterview.getItemAtPosition(position);
            String _id = row.getString(row.getColumnIndexOrThrow("_id"));
            String naziv = row.getString(row.getColumnIndexOrThrow("naziv"));
            String zanr = row.getString(row.getColumnIndexOrThrow("zanr"));
            String glumci = row.getString(row.getColumnIndexOrThrow("glumci"));
            Float rejting = row.getFloat(row.getColumnIndexOrThrow("rejting"));
            //go to detailsContact page
            Intent todetais = new Intent(MainActivity.this, DetailsMovie.class);
            todetais.putExtra("ID",_id);
            todetais.putExtra("NAZIV", naziv);
            todetais.putExtra("ZANR",zanr);
            todetais.putExtra("GLUMCI",glumci);
            todetais.putExtra("REJTING",rejting);
            startActivity(todetais);
        }
    });
    //dispay data by filter
    EditText et = (EditText) findViewById(R.id.myFilter);
    et.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchdatabyfilter(constraint.toString(),"naziv");
        }
    });
}

public void addContact(View v) {
    Intent addNewContact = new Intent(MainActivity.this, addNewMovie.class);
    startActivity(addNewContact);
}
}

DetailsMovie.java

public class DetailsMovie extends AppCompatActivity {

DBAdapter db;
String id,naziv,zanr,glumci;
Float rejting;

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

    Intent intent = getIntent();
    naziv = intent.getStringExtra("NAZIV");
    zanr = intent.getStringExtra("ZANR");
    glumci = intent.getStringExtra("GLUMCI");
    rejting = intent.getFloatExtra("REJTING", 1);

    ((TextView) findViewById(R.id.naziv)).setText(naziv);
    ((TextView) findViewById(R.id.zanr)).setText(zanr);
    ((TextView) findViewById(R.id.glumci)).setText(glumci);
    ((RatingBar) findViewById(R.id.rejting2)).setRating(rejting);
    //calling DbAdapter
    db = new DBAdapter(this);
    db.open();
}
public void Edit(View v){
    //go to EdimMovie page
    Intent edit = new Intent(DetailsMovie.this, EditMovie.class);
    edit.putExtra("ID", id);
    edit.putExtra("NAZIV", naziv);
    edit.putExtra("ZANR", zanr);
    edit.putExtra("GLUMCI", glumci);
    edit.putExtra("REJTING",rejting);
    startActivity(edit);
}
public void Delete(View v){
    db.delete(Integer.parseInt(id));
    Toast.makeText(getApplicationContext(),"Uspešno ste obrisali film", Toast.LENGTH_SHORT).show();

    Intent i = new Intent(this, MainActivity.class);
    startActivity(i);
}
@Override
public void onBackPressed() {
    finish();
    Intent i = new Intent(this, MainActivity.class);
    startActivity(i);
}
}

EditMovie.java

public class EditMovie extends AppCompatActivity {

DBAdapter db;
String id,naziv,zanr,glumci;
Float rejting;
EditText etnaziv,etzanr,etglumci;
RatingBar etrejting;

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

    Intent intent = getIntent();
    id = intent.getStringExtra("ID");
    naziv = intent.getStringExtra("NAZIV");
    zanr = intent.getStringExtra("ZANR");
    glumci = intent.getStringExtra("GLUMCI");
    rejting = intent.getFloatExtra("REJTING" ,1);

    ((EditText) findViewById(R.id.naziv)).setText(naziv);
    ((EditText) findViewById(R.id.zanr)).setText(zanr);
    ((EditText) findViewById(R.id.glumci)).setText(glumci);
    ((RatingBar) findViewById(R.id.rejting)).setRating(rejting);
    //calling DbAdapter
    db = new DBAdapter(this);
    db.open();

    //get data from text feld
    etnaziv =(EditText)findViewById(R.id.naziv);
    etzanr =(EditText)findViewById(R.id.zanr);
    etglumci =(EditText)findViewById(R.id.glumci);
    etrejting = (RatingBar) findViewById(R.id.rejting);
}
public void Save(View v){
    naziv = etnaziv.getText().toString();
    zanr = etzanr.getText().toString();
    glumci = etglumci.getText().toString();
    rejting = etrejting.getRating();
    db.update(Integer.parseInt(id),naziv, zanr, glumci, rejting);
    Toast.makeText(getApplicationContext(),"Uspešno ste ažurirali listu", Toast.LENGTH_SHORT).show();
}
@Override
public void onBackPressed() {
    finish();
    Intent i = new Intent(this, MainActivity.class);
    startActivity(i);
}
}

DBAdapter.java

public class DBAdapter {

//define static variable
public static int dbversion =1;
public static String dbname = "FilmoviDb";
public static String dbTable = "filmovi";

private static class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context,dbname,null, dbversion);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS "+dbTable+" (_id INTEGER PRIMARY KEY autoincrement,naziv, zanr, glumci, rejting, UNIQUE(naziv))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+dbTable);
        onCreate(db);
    }
}

//establsh connection with SQLiteDataBase
private final Context c;
private DatabaseHelper dbHelper;
private SQLiteDatabase sqlDb;

public DBAdapter(Context context) {
    this.c = context;
}
public DBAdapter open() throws SQLException {
    dbHelper = new DatabaseHelper(c);
    sqlDb = dbHelper.getWritableDatabase();
    return this;
}

//insert data
public void insert(String text2,String text3,String text4,Float text5) {
    if(!isExist(text2)) {
        sqlDb.execSQL("INSERT INTO filmovi (naziv, zanr, glumci, rejting) VALUES('" + text2 + "','" + text3 + "','" + text4 + "','" + text5 + "')");
    }
}
//check entry already in database or not
public boolean isExist(String num){
    String query = "SELECT naziv FROM filmovi WHERE naziv='"+num+"' LIMIT 1";
    Cursor row = sqlDb.rawQuery(query, null);
    return row.moveToFirst();
}
//edit data
public void update(int id,String text2,String text3,String text4,Float text5) {
    sqlDb.execSQL("UPDATE "+dbTable+" SET naziv='"+text2+"', zanr='"+text3+"', glumci='"+text4+"', rejting='"+text5+"'   WHERE _id=" + id);
}

//delete data
public void delete(int id) {
    sqlDb.execSQL("DELETE FROM "+dbTable+" WHERE _id="+id);
}

//fetch data
public Cursor fetchAllData() {
    String query = "SELECT * FROM "+dbTable;
    Cursor row = sqlDb.rawQuery(query, null);
    if (row != null) {
        row.moveToFirst();
    }
    return row;
}

//fetch data by filter
public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
    Cursor row = null;
    String query = "SELECT * FROM "+dbTable;
    if (inputText == null  ||  inputText.length () == 0)  {
        row = sqlDb.rawQuery(query, null);
    }else {
        query = "SELECT * FROM "+dbTable+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
        row = sqlDb.rawQuery(query, null);
    }
    if (row != null) {
        row.moveToFirst();
    }
    return row;
}
}

Logcat

08-15 15:55:47.064 9521-9521/com.example.peter.androidprojekat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.peter.androidprojekat, PID: 9521
java.lang.IllegalStateException: Could not execute method for android:onClick
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
    at android.view.View.performClick(View.java:5637) 
    at android.view.View$PerformClick.run(View.java:22429) 
    at android.os.Handler.handleCallback(Handler.java:751) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6119) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
 Caused by: java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:483)
    at java.lang.Integer.parseInt(Integer.java:556)
    at com.example.peter.androidprojekat.DetailsMovie.Delete(DetailsMovie.java:47)
    at java.lang.reflect.Method.invoke(Native Method) 
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
    at android.view.View.performClick(View.java:5637) 
    at android.view.View$PerformClick.run(View.java:22429) 
    at android.os.Handler.handleCallback(Handler.java:751) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6119) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

You are trying to parse the String value to Integer . You need to get value of ID in detail Activity screen, like:

id = intent.getStringExtra("ID");

That's the whole fix.

您永远不会为id变量设置一个值,该值会导致NumberFormatException:

db.delete(Integer.parseInt(id));

You are not setting Id from intent in DetailsMovie . So your Id is null hence the exception

You forgot to add this in your DetailsMovie onCreate()

    id = intent.getStringExtra("ID");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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