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.
Related
I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}
Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");
I know for sure that the updateFromDatabase() function works, I've used print statements to see that the entries put into mCoordinatesArray are there and not empty strings. However when I restart the app, the fragment never populates the list view with items in the database. I think it has something to do with the Fragment Lifecycle, but I have no idea.
Additionally, when I don't restart the app and run it for the first time the list view runs fine. When I rotate or restart the app, the list view no longer populates.
public class LocalFragment extends Fragment{
private ListView mLocalList;
private ArrayAdapter<String> adapter;
private ArrayList<String> mCoordinatesArray;
private BroadcastReceiver mBroadcastReceiver;
private LocationBaseHelper mDatabase;
private DateFormat dateFormat;
private String dateString;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_local,container,false);
// SQLite Setup
mDatabase = new LocationBaseHelper(getActivity());
mLocalList = (ListView) v.findViewById(R.id.lv_local);
mCoordinatesArray = new ArrayList<>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mCoordinatesArray);
if(!mDatabase.size().equals("0")){
updateFromDatabase();
}
mLocalList.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
if(mBroadcastReceiver == null){
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dateFormat = new SimpleDateFormat("MM/dd HH:mm:ss a");
dateString = dateFormat.format(new Date());
String[] data = intent.getStringExtra("coordinates").split(" ");
mDatabase.insertEntry(dateString,data[0],data[1]);
System.out.println(mDatabase.size());
mCoordinatesArray.add(dateString + " " + data[0] + " " + data[1]);
adapter.notifyDataSetChanged();
}
};
}
getActivity().registerReceiver(mBroadcastReceiver, new IntentFilter("location_update"));
}
#Override
public void onDestroy() {
super.onDestroy();
if(mBroadcastReceiver!=null){
getActivity().unregisterReceiver(mBroadcastReceiver);
}
}
// THIS METHOD CAN BE USED TO UPDATE THE ARRAY HOLDING COORDINATES FROM THE LOCAL DATABASE
private void updateFromDatabase(){
//mCoordinatesArray.clear();
mCoordinatesArray = mDatabase.getEntireDatabase();
adapter.notifyDataSetChanged();
}
}
Here's my Helper class, just in case, but I don't think the problem is here.
public class LocationBaseHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DATABASE_NAME = "locationBase.db";
public LocationBaseHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + LocationTable.NAME + " (" +
LocationTable.Cols.DATE_TIME + " text, " +
LocationTable.Cols.LATITUDE + " text, " +
LocationTable.Cols.LONGITUDE + " text )"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertEntry(String date_time, String latitude, String longitude){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(LocationTable.Cols.DATE_TIME,date_time);
content.put(LocationTable.Cols.LATITUDE,latitude);
content.put(LocationTable.Cols.LONGITUDE,longitude);
db.insert(LocationTable.NAME,null,content);
}
public ArrayList<String> getEntireDatabase(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + LocationTable.NAME,null);
cursor.moveToFirst();
ArrayList<String> values = new ArrayList<>();
do{
String value = (String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.DATE_TIME)) + " " +
(String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.LATITUDE)) + " " +
(String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.LONGITUDE));
values.add(0,value);
}while(cursor.moveToNext());
return values;
}
public String size(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + LocationTable.NAME,null);
cursor.moveToFirst();
return cursor.getString(0);
}
}
By calling mCoordinatesArray = mDatabase.getEntireDatabase(); you are changing the reference of mCoordinatesArray, and adapter is still holding the old reference, so it does not see any changes.
Instead of creating new instance of mCoordinateArray, you should rather just update values it contains, something like:
mCoordinateArray.clear();
mCoordinateArray.addAll(mDatabase.getData());
adapter.notifyDataSetChange();
That way you are changing the data that is referenced by adapter, instead of creating completely new set of data which the adapter is not aware of.
Try to recreate your ArrayAdapter instead of using .notifyDataSetChanged():
// update Data
mCoordinatesArray = mDatabase.getEntireDatabase();
// create new adapter with new updated array
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mCoordinatesArray);
// set adapter for the listview
mLocalList.setAdapter(adapter);
You can put this method in your fragment and call from activity that attach to fragment.
public void updateList(List<?> result) {
if (multimediaListRent.size()>0) {
multimediaGridView.setAdapter(gridMediaListAdapter);
multimediaListRent.clear();
}
gridMediaListAdapter.notifyDataSetChanged();
}
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 want to display the String number from mySpinner only inside my Toast but I can't find out to do just that thing. Any help is welcome!
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
while (pCur.moveToNext())
{
String name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(name + "\n" + number);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
adapter stuff of no importance
spinnerClickListener();
}
Onclick method for imagebutton to display the selected contact phone number in a toast.
public void spinnerClickListener(){
//spinner item button onclick listener
callBTN = (ImageButton)findViewById(R.id.call);
mySpinner = (Spinner)findViewById(R.id.contacts);
callBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Selected number :" + "\n" + mySpinner.getSelectedItem(), Toast.LENGTH_LONG).show();
}
});
}
thanks in advance!
you should use this
mySpinner.getSelectedItem().toString()
instead of
mySpinner.getSelectedItem()
I'm trying to start a activity everytime an item is clicked on a ListView
i'm using database in my project and using global varaibles in my project
but not able to start GalleryFileActivity activity in project
If you need to know to each of the sections will also provide
Thank you for your continued efforts to advance the perfection
public class DataListView extends ListActivity {
final private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String Path;
final private ArrayList<String> pikh = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final global folder = ((global)getApplicationContext());
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("data is");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
}
public void onListItemClick(
ListView parent, View v, int position,long id, global folder)
{
String pos=results.get(position-1);
super.onListItemClick(parent, v, position, id);
Toast.makeText(this,
"You have selected " + results.get(position-1) ,
Toast.LENGTH_SHORT).show();
folder.setsubfolder (pos);
**startActivity(new Intent(this,GalleryFileActivity.class));**
}
public void onClick(View view) {
ListView lstView = getListView();
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT Path, Header FROM resource1 "
, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
Path = c.getString(c.getColumnIndex("Path"));
String Header = c.getString(c.getColumnIndex("Header"));
results.add( Path + " " + Header);
}while (c.moveToNext()) ;
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
The code looks about right.
Sounds like you may not have GalleryFileActivity declared in your manifest.
Check your logcat output - there's probably an exception in there that mentions this.