jeudi 29 octobre 2015

how to fix index out of bound exception : invalid index 0 size is 0 in android studio

here I am storing the response of yes no maybe into userrelation table. for that I have created table in DBCONTRACT and get the values in db helper. when I get the values and store into another variable it throws this error here I am posting the code

this the sql query for userRelation table

 public static abstract class RingeeUserRelationTable implements BaseColumns {

        public static final String TABLE_NAME = "user_relation";
        public static final String COL1_EVENT_USER_ID = "EVENT_USER_ID";
        public static final String COL2_EVENT_ID = "EVENT_ID";
        public static final String COL3_RINGEE_USER_ID = "RINGEE_USER_ID";
        public static final String COL4_IS_ATTENDING = "IS_ATTENDING";
        public static final String COL5_IS_DELETE = "IS_DELETE";

        public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + _ID + " INTEGER PRIMARY KEY," + COL1_EVENT_USER_ID + INTEGER_TYPE + COMMA_SEP + COL2_EVENT_ID + INTEGER_TYPE
                + COMMA_SEP + COL3_RINGEE_USER_ID + INTEGER_TYPE + COMMA_SEP + COL4_IS_ATTENDING + INTEGER_TYPE + COMMA_SEP + COL5_IS_DELETE + INTEGER_TYPE + ")";

        public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

        public static final String RETRIVE_ALL_USER_DATA = "SELECT " + COL1_EVENT_USER_ID + COMMA_SEP + COL2_EVENT_ID + COMMA_SEP + COL3_RINGEE_USER_ID + COMMA_SEP + COL4_IS_ATTENDING + COMMA_SEP
                + COL5_IS_DELETE + " FROM " + TABLE_NAME;
    }

this is the code for getting the value and set to userMOS list

 public ArrayList<UserMO> getAllUserRelation() {
        ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(DatabaseContract.RingeeUserRelationTable.RETRIVE_ALL_USER_DATA, null );
        if (cursor.moveToFirst()) {
            do {
                UserMO userMO = new UserMO();
                userMO.setEventUserId(cursor.getLong(1));
                userMO.setEventId(cursor.getLong(2));
                userMO.setRingeeUserId(cursor.getLong(3));
                userMO.setIsAttending(cursor.getInt(4));
                userMO.setIsDelete(cursor.getInt(5));
            } while (cursor.moveToNext());

            cursor.close();
        }
        return userMOs;
    }

this is the code for getting the is attending value in fragment

context = getActivity().getApplicationContext();
        dbHelper = new DatabaseHelper(context);
        userMOs = dbHelper.getAllUserRelation();
int  isAttending = userMOs.get(position).getIsAttending(); 

I am using this isattending for setting the colour of yes no maybe button

  switch(isAttending)
            {
                case 1:
                    yesBtn.setBackgroundColor(Color.YELLOW);
                    noBtn.setBackgroundColor(Color.BLUE);
                    maybeBtn.setBackgroundColor(Color.BLUE);
                    break;
                case 2:
                    yesBtn.setBackgroundColor(Color.BLUE);
                    noBtn.setBackgroundColor(Color.BLUE);
                    maybeBtn.setBackgroundColor(Color.YELLOW);
                    break;
                case 0:
                    yesBtn.setBackgroundColor(Color.BLUE);
                    noBtn.setBackgroundColor(Color.YELLOW);
                    maybeBtn.setBackgroundColor(Color.BLUE);
                    break;


            }

when I run this project I got a error indexout of bound exception pls tell me what is the cause of the error and how to solve this issue

Insert and extract with sqlite android

I'm trying to insert data into my database, once i click on add button ,app crash.

and how can i extract data and set it into text view like the labels

thank you in advance

Here is my code

MainActivity class

public class MainActivity extends AppCompatActivity {

DB db;
Button addmed,addpl;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    db = new DB(this);
}

public void addmedView(View view){
    Intent ADDMEDVIEW = new Intent(this,ADDMEDCINEVIEW.class);
    startActivity(ADDMEDVIEW);

}
public void addpplview(View view){
    Intent ADDPPLVIEWS = new Intent(this,ADDPPLVIEW.class);
    startActivity(ADDPPLVIEWS);
}}

ADDMEDCINEVIEW Class where I'm trying to insert the data

public class ADDMEDCINEVIEW extends Activity {
DB db;
EditText MEDNAME,MEDPORP,NOT;
Button ADDDATA;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addmedview);
    MEDNAME = (EditText)findViewById(R.id.mednamevalue);
    MEDPORP = (EditText)findViewById(R.id.purposevalue);
    NOT = (EditText)findViewById(R.id.nooftapvalue);
    ADDDATA = (Button)findViewById(R.id.ADDMEDDATA);
    addDATA();
}

public void addDATA(){
    ADDDATA.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            boolean isInserted = db.inserData(
                    MEDNAME.getText().toString(),
                    MEDPORP.getText().toString(),
                    NOT.getText().toString()
            );
            if(isInserted == true){
                Toast.makeText(ADDMEDCINEVIEW.this,"Inserted",Toast.LENGTH_LONG).show();
            }
            else
                Toast.makeText(ADDMEDCINEVIEW.this,"NOT INSERTED",Toast.LENGTH_LONG).show();
        }
    });

}}

DataBase Class

public class DB extends SQLiteOpenHelper {

public final static String DBNAME="MEDCINEDB.db";
public final static String Table_name="MEDCINETable";
public final static String col1="MEDCINEID";
public final static String col2="MEDCINENAME";
public final static String col3="MEDCINEPURPOSE";
public final static String col4="NOTAPLET";


public DB(Context context) {
    super(context, DBNAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + Table_name + "(MEDCINEID INTEGER PRIMARY KEY AUTOINCREMENT,MEDCINENAME TEXT,MEDCINEPURPOSE TEXT,NOTAPLET INTEGER)");
}

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

}
public boolean inserData(String MEDCINENAME,String MEDCINEPURPOSE,String NOTAPLET){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(col2,MEDCINENAME);
    contentValues.put(col3,MEDCINEPURPOSE);
    contentValues.put(col4,NOTAPLET);

    long Result = db.insert(Table_name,null ,contentValues);
    if(Result == -1){
        return false;
    }
    else
        return true;
}}

Manifest

   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ADDMEDCINEVIEW"></activity>
    <activity android:name=".ADDPPLVIEW"></activity>
</application>

Why do I receive an error databaseHandler(android.content.context) cannot be applied to anonymous android.os.Handler

For some Reason it seems i can't store a value in this method in my database. Its my first time in countering this issue. Do I need to extend activity somewhere or is there another method of fixing this issue

final  Handler Newhandler = new Handler(){
    public void handleMessage(Message msg)
    {
        TextView tv;
        switch (msg.what)
        {
            case HEART_RATE:

                Storage value = new Storage(Integer.parseInt(msg.getData().getString("HeartRate")));

                DatabaseHandler db = new DatabaseHandler(this); The error occurs right her on the (this) value.

                db.add(value);

                List<Storage> a=db.getAllContacts();


                for(int i=0;i<a.size();i++){

                    System.out.println("Steps " + Integer.toString(a.get(i).get_heartrate()));





                }

                int Count = db.getContactsCount();
                System.out.println("Count: "+Integer.toString(Count) );*/
        }
                String HeartRatetext = msg.getData().getString("HeartRate");
                tv = (EditText)findViewById(R.id.labelHeartRate);
                System.out.println("Heart Rate Info is "+ HeartRatetext);
                if (tv != null)tv.setText(HeartRatetext);
                break;



        }
    }

};

}

How to check a record is existed in database inside getItemViewType

I have a list of products, each row has a function "Save" which will store the item product to local database. I'm using SwipeMenuListView via http://ift.tt/1qk7zQb and i have to check record is existed or not in getItemViewType in ListAdapter to remove function Save of the row which saved. But the problem is, the "check record is existed or not" made my listview freeze after notifyDataSetChanged for a while (click "Save" then notifyDataSetChanged then list is freezed until i touch listview again). How should i fix it? Every suggestion will be highly appreciated. Thanks in advance. Here is my code: @Override public boolean onMenuItemClick(int position, SwipeMenu menu, int index) { switch (index) { case 0: break; case 1: ProductDetailsVo.ProductInfo productInfo = listResult.get(position); insertProductToDB(productInfo); break; }

and method insertProductToDB: private void insertProductToDB(ProductDetailsVo.ProductInfo productInfo) { databaseManager.insertProductToDB(productInfo); if (adapter != null) { adapter.notifyDataSetChanged(); } }

Adapter:

@Override
public int getViewTypeCount() {
   return 2;
}

@Override
public int getItemViewType(int position) {
   if (databaseManager.isProductSaved(listProds.get(position).getProductId())) {// cause listview freeze
      return 1;
   }
   return 0;
}

Eclipse SQLite database locked on Windows. Will not unlock

I have the strangest problem. I simply cannot get my database to unlock. Even after restarting my machine completely the Database will not unlock.

server.DatabaseException: SQL Error while creating new user DAO
at server.DAO.Users.createUser(Users.java:48)
at shared.model.ModelIndexerData.doUsers(ModelIndexerData.java:26)
at shared.model.ModelIndexerData.readInData(ModelIndexerData.java:15)
at server.dataimport.DataImport.deserializeXML(DataImport.java:106)
at server.dataimport.DataImport.<init>(DataImport.java:35)
at server.dataimport.Main.main(Main.java:12)
Caused by: java.sql.SQLException: [SQLITE_BUSY]  
The database file is locked (database is locked)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.execute(DB.java:339)
at org.sqlite.PrepStmt.execute(PrepStmt.java:65)
at server.DAO.Users.createUser(Users.java:45)

I have searched around and never seen anyone having the error where a database remains locked even after a system is restarted. I was trying to insert 1 user into a completely blank table.

I think the cause of the lock was closing out of my debugger in Eclipse before it went through the closing of the statement but I'm not certain.

Relevant code is:

public void createUser(String username, String password, String firstname, String lastname, String email) throws DatabaseException
{
    PreparedStatement pstmt = null;
    Connection conn = db.getConnection();
    try {
        pstmt = conn.prepareStatement("INSERT INTO USERS (USERNAME,PASSWORD,FIRSTNAME,LASTNAME,EMAIL) VALUES (?,?,?,?,?)");
        pstmt.setString(1, username);
        pstmt.setString(2, password);
        pstmt.setString(3, firstname);
        pstmt.setString(4, lastname);
        pstmt.setString(5, email);
        if (!pstmt.execute())
            throw new DatabaseException("Failed to execute prepared statement createUser UsersDAO");
    } catch (SQLException e) {
        throw new DatabaseException("SQL Error while creating new user DAO", e);
    } finally {
        Database.safeClose(pstmt);
    }

}

Where is SQLite data and other app saved files stored?

Am working on an APP that has a) SQLite database, and b) text files and other files that are saved internally during operation. From what I read, app data is stored in a folder data\data\(app name)

Plugging my Motorola Moto X into my development computer, I can access the Internal Storage via the PC as a "drive". The first folder, does NOT have a data folder but there is an android folder. In that folder, there IS a data. Within that folder are folders such as com.ebay.lid, com.gopro.smarty,com.weather.weather and several others, but my app I am working on is not listed.

I have created a SQLite database and saved a text file internally, but have no idea where they went.

Is this a Moto X issue, a Moto X issue accessing via the PC as a drive, or something else?

Thanks

Core Data Managed Object unable to save context (Error 134030)

when trying to save a managed object with the following configuration in the persistent store coordinator:

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"ParallelPhotosModel.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

i get the following error:

Unresolved error Error Domain=NSCocoaErrorDomain Code=134030 "An error occurred while saving." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/9FCED2FF-F976-4780-8192-208519C8CD11/Documents/ParallelPhotosModel.sqlite, NSAffectedStoresErrorKey=( " (URL: file:///var/mobile/Containers/Data/Application/9FCED2FF-F976-4780-8192-208519C8CD11/Documents/ParallelPhotosModel.sqlite)" ), NSUnderlyingError=0x127335c50 {Error Domain=NSCocoaErrorDomain Code=4 "The file doesn’t exist." UserInfo={NSUnderlyingError=0x12732a670 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory" UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/9FCED2FF-F976-4780-8192-208519C8CD11/Documents/ParallelPhotosModel.sqlite}}}}}, { NSAffectedStoresErrorKey = ( " (URL: file:///var/mobile/Containers/Data/Application/9FCED2FF-F976-4780-8192-208519C8CD11/Documents/ParallelPhotosModel.sqlite)" ); NSFilePath = "/var/mobile/Containers/Data/Application/9FCED2FF-F976-4780-8192-208519C8CD11/Documents/ParallelPhotosModel.sqlite"; NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=4 \"The file doesn\U2019t exist.\" UserInfo={NSUnderlyingError=0x12732a670 {Error Domain=NSPOSIXErrorDomain Code=2 \"No such file or directory\" UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/9FCED2FF-F976-4780-8192-208519C8CD11/Documents/ParallelPhotosModel.sqlite}}}"; }

what is the underlying problem here and how do i avoid it? I ve seen somewhere that a similar error pops up when trying to save inside the App bundle but the storeURL i m using was taken from a tutorial (that is the documents directory).