I'm working on Android Studio Project for my university (app calendar and more), and one of the functionalities is touch in a day of a calendar (CalendarView), display a layout for add event and later the event is saved in a SQLITE, (in another activity is where the list of events is displayed) the problem is when I want to delete an event (java.lang.ArrayIndexOutOfBoundsException: length=5; index=5).
In Viewevents eliminar(String dato) is the code with error, How do I fix the issue? Thanks.
View events:
public class ViewEventsActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener {
//al mantener la wea apretada
private SQLiteDatabase db;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_events);
listView=(ListView) findViewById(R.id.ltvListaEventos);
listView.setOnItemLongClickListener(this);
Bundle bundle= getIntent().getExtras();
int dia,mes,anio;
dia=mes=anio=0;
dia=bundle.getInt("dia");
mes=bundle.getInt("mes");
anio=bundle.getInt("anio");
String cadena= dia+" - "+ mes + " - "+ anio;
BDSQLite bd= new BDSQLite(getApplicationContext(), "eventos", null,1);
db= bd.getReadableDatabase();
String sql="select * from eventos where fechadesde='"+cadena+"'";
Cursor c;
String nombre,fechadesde,horadesde,fechahasta,horahasta,descripcion,ubicacion;
try {
c=db.rawQuery(sql,null);
arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
if(c==null||c.getCount()==0) {
Toast.makeText(getBaseContext(), "No hay eventos disponibles", Toast.LENGTH_LONG).show();
}
if(c.moveToFirst()){
do {
nombre=c.getString(1);
ubicacion=c.getString(2);
fechadesde=c.getString(3);
horadesde=c.getString(4);
fechahasta=c.getString(5);
horahasta=c.getString(6);
descripcion=c.getString(7);
arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);
} while(c.moveToNext());
listView.setAdapter(arrayAdapter);
}
}catch (Exception ex) {
Toast.makeText(getApplication(), "Error: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
this.finish();
}
}
private void eliminar(String dato){
String []datos= dato.split(", ");
String sql="delete from eventos where nombreEvento='"+datos[0]+"' and" +
" ubicacion='"+datos[1]+"' and fechadesde='"+datos[2]+"' and " +
"horadesde='"+datos[3]+"' and fechahasta='"+datos[4]+"' and horahasta='"+datos[5]+"' and descripcion='"+datos[6];
try {
arrayAdapter.remove(dato); //eliminar del menĂº
listView.setAdapter(arrayAdapter);
db.execSQL(sql);
Toast.makeText(getApplication(),"Evento eliminado",Toast.LENGTH_SHORT).show();
}catch (Exception ex){
Toast.makeText(getApplication(),"Error:"+ ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder builder= new AlertDialog.Builder(this);
CharSequence []items= new CharSequence[2];
items[0]="Eliminar Evento";
items[1]="Cancelar";
builder.setTitle("Eliminar evento")
.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(i==0){
//eliminar evento
eliminar(adapterView.getItemAtPosition(i).toString());
}
}
});
AlertDialog dialog= builder.create();
dialog.show();
return false;
}
}
BDSQlite:
public class BDSQLite extends SQLiteOpenHelper {
private String sql = "create table eventos(" +
"idEvento int identity,"+
"nombreEvento varchar(40)," +
"ubicacion varchar(60)," +
"fechadesde date,"+
"horadesde time,"+
"fechahasta date,"+
"horahasta time," +
"descripcion varchar(60))";
Add event activity
public class AddActivity extends AppCompatActivity implements View.OnClickListener {
private EditText nombreEvento, ubicacion, fechadesde, horadesde, fechahasta, horahasta;
private EditText descripcion;
private Button guardar, cancelar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
nombreEvento = (EditText) findViewById(R.id.edtNombreEvento);
ubicacion = (EditText) findViewById(R.id.edtUbicacion);
fechadesde = (EditText) findViewById(R.id.edtFechaDesde);
fechahasta = (EditText) findViewById(R.id.edtFechaHasta);
horadesde = (EditText) findViewById(R.id.edtHorainicio);
horahasta = (EditText) findViewById(R.id.edtHoraHasta);
descripcion = (EditText) findViewById(R.id.edtDescripcion);
Bundle bundle = getIntent().getExtras();
int dia = 0, mes = 0, anio = 0;
dia=bundle.getInt("dia");
mes=bundle.getInt("mes");
anio=bundle.getInt("anio");
fechadesde.setText(dia + " - " + mes + " - " + anio);
fechahasta.setText(dia + " - " + mes + " - " + anio);
guardar = (Button) findViewById(R.id.btnguardar);
cancelar = (Button) findViewById(R.id.btncancelar);
guardar.setOnClickListener(this);
cancelar.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == guardar.getId()) {
//guardar datos cajas de texto
BDSQLite bd = new BDSQLite(getApplication(), "eventos", null, 1);
SQLiteDatabase db = bd.getWritableDatabase();
String sql = "insert into eventos" +
"(nombreEvento, ubicacion, fechadesde, horadesde, fechahasta, horahasta," +
"descripcion) values('" +
nombreEvento.getText()+
"','"+ ubicacion.getText()+
"','" +fechadesde.getText()+
"','" + horadesde.getText()+
"','"+fechahasta.getText()+
"','"+horahasta.getText()+
"','"+descripcion.getText();
try {
db.execSQL(sql);
nombreEvento.setText("");
ubicacion.setText("");
fechadesde.setText("");
fechahasta.setText("");
horadesde.setText("");
horahasta.setText("");
descripcion.setText("");
Toast.makeText(getBaseContext(), "Evento guardado", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplication(),"Error"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
} else {
this.finish();
return;
}
}
}
ERROR:
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.example.niikoo.fondocelular.ViewEventsActivity.eliminar(ViewEventsActivity.java:87)
at com.example.niikoo.fondocelular.ViewEventsActivity.access$000(ViewEventsActivity.java:17)
at com.example.niikoo.fondocelular.ViewEventsActivity$1.onClick(ViewEventsActivity.java:116)
EDIT: The code with the structure of sql and datos, how i fix the error:(
Exception line (java.lang.ArrayIndexOutOfBoundsException: length=5; index=5) clearly mentions that you are Trying to get index=5but the length of the dato is 5(length=5).
So, use only proper index i.e. index 0 to 4. OR Make sure that enough indexes exists to access.
Note: You have used dato.split(", ");. Try with dato.split(",");. May be the problem is with pattern of splitter.
It looks like your String dato which you are splitting by commas to an array may not be the length that you think. The error is showing 5 items in the array, so the greatest index you can access in that case would be datos[4] since arrays are 0-based.
Debug your array after you split:
String []datos= dato.split(", ");
Check the input of this method, it's not in the code.
eliminar(adapterView.getItemAtPosition(i).toString());
The error you get occurs because the array you get after splitting the String has only 5 elements (4 commas):
private void eliminar(String dato) {
String []datos= dato.split(", ");
...
But then you try to get the 6th (index 5) and 7th (index 6) elements from that array:
datos[5]+"' and descripcion='"+datos[6];
There are no such elements, therefore you get this ArrayIndexOutOfBoundsException error.
To fix, try to find the input of your adapterView.
EDIT: In this line 2 Strings appear to be empty:
arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);
Hence, when you get a ", , " and split it with split(", ") it doesn't count the "" String and you get less items in the resulting array, which leads to the error.
I am making an app and I'm stuck with one problem. I want to know what can I do to make this happen:
I want to check if the edit text is empty or not and if it is not, then perform a particular piece of the task and if it is empty then make a toast which says please enter the names.
Here is my code: `
final TextView percentage = (TextView) findViewById(R.id.percentage_text);
Button calculateButton = (Button) findViewById(R.id.calculate_button);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random noGen = new Random();
int number = noGen.nextInt(101);
EditText firestName = (EditText) findViewById(R.id.first_name);
String firstNameString = firestName.getEditableText().toString();
EditText secName = (EditText) findViewById(R.id.sec_name);
String secNameString = secName.getEditableText().toString();
percentage.setText(Integer.toString(number));
Toast.makeText(getApplicationContext(), "The love score between " + firstNameString +" & " + secNameString + " is " + number + "%", Toast.LENGTH_SHORT ).show();
}
});
`
I know I can easily do this with if else statement but I am not able to do it
Thanks in advance!!!
Try this:
if(firestName.getText()!=null &&
!firestName.getText().equals("") && secName.getText()!=null &&
!secName.getText().equals("")){
// do your task
}else{
// show msg
}
You can check String variable that whether is empty or not. You can refer below code. You can find more String operation on Internet.
Button calculateButton = (Button) findViewById(R.id.calculate_button);
EditText firestName = (EditText) findViewById(R.id.first_name);
EditText secName = (EditText) findViewById(R.id.sec_name);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random noGen = new Random();
int number = noGen.nextInt(101);
String firstNameString = firestName.getEditableText().toString();
String secNameString = secName.getEditableText().toString();
if(!firstNameString.isEmpty() && !secNameString.isEmpty()){
//Perform your task
}
percentage.setText(Integer.toString(number));
Toast.makeText(getApplicationContext(), "The love score between " + firstNameString +" & " + secNameString + " is " + number + "%", Toast.LENGTH_SHORT ).show();
}
});
Try below code;
EditText firestName = (EditText) findViewById(R.id.first_name);
String firstNameString = firestName.getEditableText().toString();
EditText secName = (EditText) findViewById(R.id.sec_name);
String secNameString = secName.getEditableText().toString();
if(firstNameString.matches("") && secNameString.matches("")){
//Do your code here
}
if(firestName.getText().toString().equals("")){
//do some stuff
}else{
Toast.makeText(getApplicationContext(), "Please enter", Toast.LENGTH_SHORT ).show();
}
I am a new guy to android development. I have created a SMS Inbox application.
I managed to get the SMS Inbox of the phone. Now I want to set a onclick method to open a specific message in a new activity with the phone number and the message.
Here is the code for my inbox activity. I do not understand, the place to put my onclicklistitem method.
public class MessageInboxActivity extends ActionBarActivity implements OnItemClickListener {
private static MessageInboxActivity inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static MessageInboxActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_inbox);
smsListView = (ListView) findViewById(R.id.SMSList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.my_adapter_item, R.id.product_name, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
refreshSmsInbox();
}
public void refreshSmsInbox() {
ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
"\n" + smsInboxCursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (smsInboxCursor.moveToNext());
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can someone help me to start new activity with the phone number and the message.
I'd put this in a comment but I can't comment, can you clarify your problem? What activity are you trying to link to and what exactly do you want to achieve? it seems like you just need to add to your onItemClick()
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Intent in = new Intent(getApplicationContext,/*whatever activity you want to open*/);
in.putStringExtra(/*some static keystring*/,smsMessage);
startActivity(in);
but it's hard to say for sure without knowing more
I have a program that will retrieve some data from database, and show it on the screen as some buttons. How can I give an Id to every button created and make button.OnClickListener to every button with the correct id?
Here is my codes :
private void selectAllGroup() {
// TODO Auto-generated method stub
MyGroup = (TextView) findViewById(R.id.tvListGroup);
Database allGroup = new Database(MyGroupActivity.this);
allGroup.open();
listGroup = allGroup.countHowManyGroups(username);
layout = (LinearLayout) findViewById(R.id.LLMyGroup);
String groupName[] = allGroup.fetchGroupName(username);
for (int i = 0; i < listGroup; i++) {
newBt = new Button(this);
newBt.setText(groupName[i]);
layout.addView(newBt);
}
allGroup.close();
}
And here is my database code (if needed) :
public int countHowManyGroups(String username) {
// TODO Auto-generated method stub
String Query = "SELECT " + GROUP_NAME + " From " + MS_GROUP
+ " a INNER JOIN " + MS_GROUP_DETAIL + " b ON a." + GROUP_ID
+ "=b." + GROUP_ID + " WHERE " + MEMBER_USERNAME + "=?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username });
int cnt = c.getCount();
c.close();
return cnt;
}
public String[] fetchGroupName(String username){
int i=0;
String Query = "SELECT " + GROUP_NAME + " From " + MS_GROUP
+ " a INNER JOIN " + MS_GROUP_DETAIL + " b ON a." + GROUP_ID
+ "=b." + GROUP_ID + " WHERE " + MEMBER_USERNAME + "=?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username });
String groupName[] = new String [c.getCount()];
int iGroupName = c.getColumnIndex(GROUP_NAME);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
groupName[i] = c.getString(iGroupName);
i++;
}
c.close();
return groupName;
}
Regarding to your question "How can I give an Id to every button created and make button.OnClickListener to every button with the correct id?"
Simply use inside your for-loop:
newBt.setId(id to set) // Should be positive, doesn't have to be unique
newBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//The View carries the Id
v.getId();
//Then you can simply set up a fast Switch-case for example
switch (v.getid()) {
case 1:
break;
default:
break;
}
});
Update
No Problem just cast Button to the View in the onClick-Method and get the String:
newBt.setId(id to set) // Should be positive, doesn't have to be unique
newBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button myClickedButton = (Button) v;
String buttonText = myClickedButton.getText();
//Do something with your logic here.
//You can also Switch-case on a String ! But AFAIK
//it's only possible on Java Compiler 1.7 or above.
//But Eclipse will guide you if you want to Switch on String
});
You can setTag for each button inside the for loop as
newBt.setTag(i);
newBt.setOnClickListener(this);
and inside your OnClick method get the tag as the position like
#Override
public void onClick(View view){
int buttonClicked = (int) view.getTag();
// Do your code here according to the position of the button clicked
}
for (int i = 0; i < listGroup; i++) {
newBt = new Button(this);
newBt.setText(groupName[i]);
newBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//write your logic to do the work you need when button is clicked.You do not need id for this.
}
});
layout.addView(newBt);
}
You don't need id for listening to button click event.
Currently I am trying to create a phonebook app that, when the delete button is clicked will delete the entry in the SQLite database that is shown on screen. However, when I click the delete button the method runs but the data stays in the sql database table until I restart the emulator I am using. On restart the data table has updated itself and my "Next" and "Previous" buttons do not pick up the data that was previously deleted.
Does anyone know why this is? I will put some of the relevant code..
public void Deletedata (View view)
{
int dRow;
dRow = Integer.parseInt((cursor.getString(0)));
db.deleteRecord(dRow);
Toast.makeText(this, "Contact Deleted", Toast.LENGTH_LONG).show();
Nextdata(view);
}
public void DisplayRecord(Cursor c)
{
EditText nameTxt = (EditText)findViewById(R.id.Name);
EditText phoneTxt = (EditText)findViewById(R.id.Phone);
EditText emailTxt = (EditText)findViewById(R.id.Email);
if (c!= null)
{
nameTxt.setText(c.getString(1));
phoneTxt.setText(c.getString(2));
emailTxt.setText(c.getString(3));
}
}
public void Nextdata (View view)
{
if (cursor.moveToNext())
{
DisplayRecord(cursor);
}
else
{
Toast.makeText(this, "Last Entry in Phone Book", Toast.LENGTH_LONG).show();
Previousdata(view);
}
}
public void Previousdata (View view)
{
if (cursor.moveToPrevious())
{
DisplayRecord(cursor);
}
else
{
Toast.makeText(this, "First Entry in Phone Book", Toast.LENGTH_LONG).show();
Nextdata(view);
}
This piece of code is in my DBAdaptor class,
public boolean deleteRecord(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor getAllRecords()
{
Cursor gaRecords = db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_PHONENUMBER, KEY_EMAIL}, null, null, null, null, null);
gaRecords.moveToFirst();
return gaRecords;
}
You need to refresh your Cursor. My best guess for your code is:
public void Deletedata (View view)
{
int position = cursor.getPosition();
int dRow;
dRow = Integer.parseInt((cursor.getString(0)));
db.deleteRecord(dRow);
Toast.makeText(this, "Contact Deleted", Toast.LENGTH_LONG).show();
// Refresh the cursor
cursor.close();
cursor = db.getAllRecords();
cursor.moveToPosition(position);
Nextdata(view);
}