I am trying to create an android app that takes information about an album and displays it in an expandable list view.The artist's name will be displayed as the parent item, and when artist is selected the albums by that artist will be displayed as the child. I have been able to get the list working so far by initializing the strings in the MyExpandableListAdapter class. However, I want to be able to press a button and add a new view to the List that contains the information.
Here is my code:
package droid.musiclibrary;
/**
* Some code taken from:
* http://www.dreamincode.net/forums/topic/270612-how-to-get-started-with-expandablelistview/
*/
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ExpandableListActivity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddContent extends Activity {
private Spinner spinArtist, spinGenre;
private EditText addArtist, addGenre, addTitle, addYear;
private ArrayAdapter<String> adapterArtist, adapterGenre;
private ArrayList<String> artists = new ArrayList<String>();
private ArrayList<String> genres = new ArrayList<String>();
private ArrayList<String> albums = new ArrayList<String>();
private ArrayList<String> albumList = new ArrayList<String>();
List<List<String>> albumArray = new ArrayList<List<String>>();
private ExpandableListView expList;
private MyExpandableListAdapter expAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.add_content);
expList = (ExpandableListView) findViewById(R.id.artistList);
expAdapter = new MyExpandableListAdapter(this);
expList.setAdapter(expAdapter);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed
// in the Action Bar.
Intent parentActivityIntent = new Intent(this, MainActivity.class);
parentActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public AddContent() {
}
public void addArtist(View view) {
spinArtist = (Spinner) findViewById(R.id.spinArtist);
addArtist = (EditText) findViewById(R.id.txtAddArtist);
if(addArtist.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter an artist.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
artists.add(addArtist.getText().toString());
adapterArtist = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, artists);
adapterArtist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinArtist.setAdapter(adapterArtist);
addArtist.setText("");
}
public void addGenre(View view) {
spinGenre = (Spinner) findViewById(R.id.spinGenre);
addGenre = (EditText) findViewById(R.id.txtAddGenre);
if(addGenre.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter a genre.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
genres.add(addGenre.getText().toString());
adapterGenre = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, genres);
adapterGenre.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinGenre.setAdapter(adapterGenre);
addGenre.setText("");
}
public void addAlbum(View view) {
addTitle = (EditText) findViewById(R.id.txtAddTitle);
addYear = (EditText) findViewById(R.id.txtAddYear);
if(addTitle.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter a title.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else if(spinArtist.getSelectedItem().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to select an artist.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else if(spinGenre.getSelectedItem().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to select a genre.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else if(addYear.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter a year.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
albums.add(addTitle.getText().toString().trim());
}
}
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
String[] groups = {"Silverstein"};
String[][] children = {{"Discovering the Waterfront"}};
public MyExpandableListAdapter(Context context) {
this.context = context;
}
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return children[groupPosition].length;
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
TextView tv = new TextView(this.context);
tv.setLayoutParams(lp);
// Center the text vertically
tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
tv.setPadding(45, 0, 0, 0);
return tv;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getChild(groupPosition, childPosition).toString());
return textView;
}
public Object getGroup(int groupPosition) {
return groups[groupPosition];
}
public int getGroupCount() {
return groups.length;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
/*public void setArtist(ArrayList<String> artist) {
this.artists = artist;
}
public ArrayList<String> getArtist() {
return artist;
}
public void setAlbum(ArrayList<String> album) {
this.albums = album;
}
public ArrayList<String> getAlbum() {
return albums;
}
/**
* This will actually be used to sort the added content.
* For example, when sorting by artist, the parent will be the artist's name
* and the child entries will be the albums by that artist.
* This will probably have to moved to a separate class (Sort.java???)
*/
/*public void addItem(ExpandListChild item, ExpandListParent group) {
if(!artistList.contains(group)) {
artistList.add((group));
}
int index = artistList.indexOf(group);
ArrayList<ExpandListChild> ch = artistList.get(index).getItems();
ch.add(item);
artistList.get(index).setItems(ch);
}
public Object getChild(int parentPosition, int childPosition) {
ArrayList<ExpandListChild> chList = artistList.get(parentPosition).getItems();
return chList.get(childPosition);
}
public long getChildId(int parentPosition, int childPosition) {
return childPosition;
}*/
}
Is there some way to add the artists and albums ArrayList to the String[] in MyExpandableListAdpter class? I have tried that many different ways and each time I get a NullPointerException.
Any help would be appreciated, I have spent hours searching for an answer to this.
Related
I seem to be stuck with this problem where I want to update the Recycler View in real-time. Meaning I want the recycler view to update its list when a user swipes to delete a row.
As you can see in the code below I have tried to use NotifyDataSetChange() in the DatabaseAdapter java class but I only get the error "RecyclerViewAdapter.notifyDataSetChanged() on a null object reference".
I have both googled the error above and how to update Recycle view in real-time but none of the solutions I found worked. Please help me because I am losing it with this problem.
NamesAdapter.Java
package com.example.myapplication.ui;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.DatabaseAdapter;
import com.example.myapplication.R;
import org.w3c.dom.NameList;
import java.util.ArrayList;
import java.util.List;
public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.ViewHolder> {
Context context;
List<Names> namesList;
RecyclerView rvPrograms;
final View.OnClickListener onClickListener = new MyOnClickListner();
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView rowID;
TextView rowName;
TextView rowAmount;
TextView rowDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Store the item sub-views in member variables
rowID = itemView.findViewById(R.id.idTextView);
rowName = itemView.findViewById(R.id.nameTextView);
rowAmount = itemView.findViewById(R.id.amountEditText);
rowDate = itemView.findViewById(R.id.dateTextView);
}
}
public NamesAdapter(Context context, List<Names> namesList, RecyclerView rvPrograms){
this.context = context;
this.namesList= namesList;
this.rvPrograms = rvPrograms;
}
#NonNull
#Override
public NamesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.recycler_list, viewGroup, false);
view.setOnClickListener(onClickListener);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NamesAdapter.ViewHolder holder, int i) {
Names name = namesList.get(i);
holder.rowID.setText(""+name.getId());
holder.rowName.setText(name.getName());
holder.rowAmount.setText(name.getAmount());
holder.rowDate.setText(name.getDate());
holder.itemView.setTag(name.getId());
}
#Override
public int getItemCount() {
return namesList.size();
}
private class MyOnClickListner implements View.OnClickListener {
#Override
public void onClick(View v) {
int itemPosition = rvPrograms.getChildLayoutPosition(v);
String item = namesList.get(itemPosition).getName();
Toast.makeText(context, item, Toast.LENGTH_SHORT).show();
}
}
}
DatabaseAdapter.Java
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.myapplication.ui.Names;
import com.example.myapplication.ui.NamesAdapter;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
List<Names> namesList = new ArrayList<>();
NamesAdapter na;
public DatabaseAdapter(Context context) {
helper = new DatabaseHelper(context);
db = helper.getWritableDatabase();
}
public int deleteData(String name){
String whereArgs[] = {name};
int count = db.delete(DatabaseHelper.Table_Name, DatabaseHelper.Key_Name+ "=?", whereArgs);
return count;
}
public int removeItem (long id){
int count = db.delete(DatabaseHelper.Table_Name, DatabaseHelper.Key_ID+ "="+ id, null);
//na.notifyDataSetChanged();
return count;
}
public int updateAmount(String name, String amount){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.Key_Amount, amount);
String whereArgs[] = {name};
int count = db.update(DatabaseHelper.Table_Name, contentValues, DatabaseHelper.Key_Name + "=?", whereArgs);
return count;
}
public String searchData(String sname){
String columns[] = {DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount};
String selectionArgs[] = {sname};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, DatabaseHelper.Key_Name + "=?", selectionArgs, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
String name = cursor.getString(index1);
String amount = cursor.getString(index2);
buffer.append(name + " " + amount + "\n");
}
return buffer.toString();
}
// This is for the Toast dispaly
public String getAllData(){
String columns[] = {DatabaseHelper.Key_ID, DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, null, null, null, null, null, null );
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_ID);
int rowid = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
String name = cursor.getString(index2);
int index3 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
int amount = cursor.getInt(index3);
buffer.append(rowid + " " + name + " " + amount + "\n");
}
return buffer.toString();
}
public List<Names> getAllNames(){
String columns[] = {DatabaseHelper.Key_ID, DatabaseHelper.Key_Name, DatabaseHelper.Key_Amount, DatabaseHelper.Key_Date};
Cursor cursor = db.query(DatabaseHelper.Table_Name, columns, null, null, null, null, DatabaseHelper.Key_ID+" DESC",null );
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DatabaseHelper.Key_ID);
int rowid = cursor.getInt(index1);
int index2 = cursor.getColumnIndex(DatabaseHelper.Key_Name);
String name = cursor.getString(index2);
int index3 = cursor.getColumnIndex(DatabaseHelper.Key_Amount);
Double amount = cursor.getDouble(index3);
int index4 = cursor.getColumnIndex(DatabaseHelper.Key_Date);
String date = cursor.getString(index4);
Names names = new Names(rowid, name, amount, date);
namesList.add(names);
}
return namesList;
}
public long insertData (String name, Double amount, String date){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.Key_Name, name);
contentValues.put(DatabaseHelper.Key_Amount, amount);
contentValues.put(DatabaseHelper.Key_Date, date);
long id = db.insert(DatabaseHelper.Table_Name, null ,contentValues);
return id;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String Database_Name = "Demoze.db";
private static final String Table_Name = "salary";
private static final int Database_Version= 10;
private static final String Key_ID = "_id";
private static final String Key_Name = "name";
private static final String Key_Amount = "amount";
private static final String Key_Date = "date";
private static final String Create_table = "create table "+Table_Name+
" ("+Key_ID+" integer primary key autoincrement, "+Key_Name+
" text, "+Key_Amount+ " real, "+Key_Date+" text)";
private static final String Table_Drop = "drop table if exists "+Table_Name;
private Context context;
public DatabaseHelper(#Nullable Context context) {
super(context, Database_Name, null, Database_Version);
this.context = context;
Toast.makeText(context, "Constructor Called", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Create_table);
Toast.makeText(context, "OnCreate Called", Toast.LENGTH_SHORT).show();
} catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Toast.makeText(context, "OnUpgrade Called", Toast.LENGTH_SHORT).show();
db.execSQL(Table_Drop);
onCreate(db);
} catch (SQLException e) {
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}
}
SpendingActivity.Java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.ui.Names;
import com.example.myapplication.ui.NamesAdapter;
import java.util.ArrayList;
import java.util.List;
public class SpendingActivity extends AppCompatActivity {
DatabaseAdapter databaseAdapter;
EditText crud;
RecyclerView rvPrograms;
NamesAdapter namesAdapter;
RecyclerView.LayoutManager layoutManager;
List<Names> namesList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spending_list);
databaseAdapter = new DatabaseAdapter(this);
namesList = databaseAdapter.getAllNames();
rvPrograms = findViewById(R.id.rvDBdata);
rvPrograms.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvPrograms.setLayoutManager(layoutManager);
namesAdapter = new NamesAdapter(this, namesList, rvPrograms);
rvPrograms.setAdapter(namesAdapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
databaseAdapter.removeItem((long) viewHolder.itemView.getTag());
}
}).attachToRecyclerView(rvPrograms);
crud = findViewById(R.id.crudEditText);
String data = databaseAdapter.getAllData();
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}
public void Home (View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void Search (View view){
String name = crud.getText().toString().trim();
String result = databaseAdapter.searchData(name);
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
public void Update (View view) {
String amount = crud.getText().toString().trim();
databaseAdapter.updateAmount("taxi", amount);
}
public void Delete (View view) {
String name = crud.getText().toString().trim();
databaseAdapter.deleteData(name);
}
}
In your NamesAdapter you could expose a method called deleteItem:
public class NamesAdapter extends RecyclerView.Adapter<NamesAdapter.ViewHolder> {
...
public void deleteItem(int position){
namesList.remove(position);
notifyItemRemoved(position);
}
}
Inside of onSwiped() method, you need to call NameAdapter' deleteItem method:
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
namesAdapter.deleteItem(position);
databaseAdapter.removeItem((long) viewHolder.itemView.getTag());
}
Recycleview adapterclass
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
ArrayList<String> animalNames
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
animalNames.remove(position);
adapter.notifyItemRemoved(position);
}
}
I have custom list view and my data is coming from sqlite database. Now I want to change specific listview item's background color according to the id. First, I check the id if exist in database, then change particular item row background color according to the id.
My problem is that it checks successfully, but when I tried to change background color it changes whole listview background color. Here is picture and code of my data. Then you'll get my point, what actually I want to say you!
My db:
Whole listview color change:
My code:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean highlight=false;
LinearLayout linearLayout;
public String ex="switch";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
//check if id is exits in db
if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
{
holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
}
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();
/* ColorPicker colorPicker = new ColorPicker(activity);
ArrayList<String>colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
// holder.linearLayout.setBackgroundColor(color);
}
#Override
public void onCancel() {
}
}).show();*/
return false;
}
});
/*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
return false;
}
});*/
//verselist highlight
/*holder.verselist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*/
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
/* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
*/
//My toggle button
/* holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
private LinearLayout linearLayout;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
/*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)v.findViewById(R.id.layout);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public void opecolorpicker(){
}
}
Assuming you store the IDs in private List<String>verseid;, you can use it to check the ID of current ListView item.
The current item position is passed to you in final int position parameter.
So to check and apply color:
Remove
if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
{
holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
}
from if (convertView == null) {
Then add this code right outside that if:
if("1001001".equals(verseid.get(position))) {
//change the color
} else {
//set the color to default
}
Note that due to the way the ListView works (recycling items) you have to set the default color inside else.
I am new to android development and I have custom ListView which have favourite and removefavourite button now i want save this button state in SharedPreferences please tell me how i can save this button state in shared preference when user click on favourite button, the button change into favourite and when click on favourite the button change into removefavourite here is my code?
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
}
});
holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=false;
holder.addfavoruite.setVisibility(View.VISIBLE);
holder.removefavoruite.setVisibility(View.GONE);
}
});
My custom ListView whole code
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean ischeckd;
String My_PREF="MY_PREF";
SharedPreferences sharedPreferences;
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ImageView)convertView.findViewById(R.id.adbookmark);
holder.removefavoruite=(ImageView)convertView.findViewById(R.id.removebookmark);
try {
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
}
});
holder.removefavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=false;
holder.addfavoruite.setVisibility(View.VISIBLE);
holder.removefavoruite.setVisibility(View.GONE);
}
});
}catch (Exception e){
Toast.makeText(activity, ""+e, Toast.LENGTH_SHORT).show();
}
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ImageView addfavoruite;
private ImageView removefavoruite;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
addfavoruite=(ImageView)v.findViewById(R.id.adbookmark);
removefavoruite=(ImageView)v.findViewById(R.id.removebookmark);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
}
you just need to create an AppPreference class :-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean isButtonCLicked(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("button_clicked", true);
}
public static void setButtonCLicked(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("button_clicked", value);
mPrefsEditor.commit();
}
}
and set this method in your button click:-
holder.addfavoruite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ischeckd=true;
holder.addfavoruite.setVisibility(View.GONE);
holder.removefavoruite.setVisibility(View.VISIBLE);
AppPreference.setButtonCLicked(activity, ture);
}
});
and get your button state like this :-
boolean isButtonClicked = AppPreference.isButtonCLicked(activity);
I have a few suggestions. First, I'd recommend you use a ToggleButton for your favourite button. Second, I'd recommend you use a RecyclerView instead of a ListView (which is essentially deprecated). Third, I'd recommend you create a data class (ideally with AutoValue):
class Verse {
private final int number;
private final String list;
private final String ref;
private final String id;
private final boolean isFavourite;
//Constructor and getters...
}
And replace this:
List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid
with this:
List<Verse> verses
With respect to persisting which verses are checked and which aren't, then I'd recommend you favour an SQLiteDatabase over SharedPreferences. However, if you use shared preferences, you'll need a way to link your verse to its checked state. I'm assuming your id value is unique, so you can use that:
class VersePreferences {
private static final String VERSE_KEY = "com.my.packagename.VERSE_KEY";
private final SharedPreferences prefs;
private VersePreferences(SharedPreferences prefs) {
this.prefs = prefs;
}
static VersePreferences from(Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
return new VersePreferences(prefs);
}
void save(List<Verse> verses) {
final Set<String> set = new HashSet<>(verses.size());
for(Verse verse : verses) {
final String serialized = String.format("%s:%s", verse.id(), Boolean.toString(verse.isFavourite()));
}
prefs.edit().putStringSet(VERSE_KEY, set).apply();
}
Map<String, Boolean> load() {
final Set<String> set = prefs.getStringSet(VERSE_KEY, new HashSet<>());
final Map<String, Boolean> map = new HashMap<>();
for(String serialized : set) {
final String[] parts = serialized.split(":");
map.put(parts[0], Boolean.parseBoolean(parts[1]);
}
return map;
}
}
You can identify which verse is an isn't a favourite by comparing the String id value in the map against the Boolean value
Example usage...
//OnClick
VersePreferences.from(Context).save(verses); //save all verses
//To load
final Map<String, Boolean> checkedStates = VersePreferences.from(context).load();
for(int i = 0; i < verses.size(); i++) {
final Verse current = verses.get(i);
final boolean checkedState = checkedState.get(current.id());
final Verse checked = current.toBuilder().setChecked(checkedState).build(); //Example using builder pattern
verses.set(i, checked);
}
I'm fairly new to Java and android development. I am having trouble implementing a spinner in an android app. The spinner populates fine, but I cannot get it to the labels of the conversions variables to change when the index changes in the spinner. Essentially, the class I am having trouble getting to work is selectOption() or public void onItemSelected(AdapterView parent, View view, int position, long id) class.
Any help is extremely appreciated.
package com.example.conversion;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;
public class MainActivity extends ActionBarActivity implements OnEditorActionListener, AdapterView.OnItemSelectedListener{
//Graphical Variables
private Spinner option;
private TextView inputTextView;
private TextView outputTextView;
private EditText conversionInput;
private TextView conversionOutput;
//Conversions
private float
milesToKil = 1.6093f,
kilToMiles = 0.6214f,
inchToCent = 2.54f,
centToInch = 0.3937f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get IDs
option = (Spinner) findViewById(R.id.option);
inputTextView = (TextView) findViewById(R.id.inputTextView);
outputTextView = (TextView) findViewById(R.id.outputTextView);
conversionInput = (EditText) findViewById(R.id.conversionInput);
conversionOutput = (TextView) findViewById(R.id.conversionOutput);
conversionInput.setOnEditorActionListener(this);
//Add values to spinner
addToSpinner();
//selectOption();
display("");
}
//Spinner
public void addToSpinner() {
option = (Spinner) findViewById(R.id.option);
List<String> list1 = new ArrayList<String>();
list1.add("Miles To Kilometers");
list1.add("Kilometers To Miles");
list1.add("Inches To Centimeters");
list1.add("Centimeters to Inches");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
option.setAdapter(dataAdapter1);
}
/*public void selectOption()
{
int position;
position = option.getSelectedItemPosition();
String cAmountString = conversionInput.getText().toString();
float temp = Float.parseFloat(cAmountString);
if(position == 0)
{
inputTextView.setText("Miles");
outputTextView.setText("Kilometers");
convertMilesToKilometers(temp);
}
else if(position == 1)
{
inputTextView.setText("Kilometers");
outputTextView.setText("Miles");
convertKilometersToMiles(temp);
}
else if(position == 2)
{
inputTextView.setText("Inches");
outputTextView.setText("Centimeters");
//convertInchesToCentimeters(cAmountString);
}
else if(position == 3)
{
inputTextView.setText("Centimeters");
outputTextView.setText("Inches");
//convertCentimetersToInches(cAmountString);
}
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
display("");
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
TextView myText = (TextView) view;
Toast.makeText(this, "You selected " + myText.getText() + " ", Toast.LENGTH_LONG).show();
String cAmountString = conversionInput.getText().toString();
float temp = Float.parseFloat(cAmountString);
if(position == 0)
{
inputTextView.setText("Miles");
outputTextView.setText("Kilometers");
convertMilesToKilometers(temp);
}
else if(position == 1)
{
inputTextView.setText("Kilometers");
outputTextView.setText("Miles");
convertKilometersToMiles(temp);
}
else if(position == 2)
{
inputTextView.setText("Inches");
outputTextView.setText("Centimeters");
//convertInchesToCentimeters(cAmountString);
}
else if(position == 3)
{
inputTextView.setText("Centimeters");
outputTextView.setText("Inches");
//convertCentimetersToInches(cAmountString);
}
}
public void display(String displayText)
{
if(displayText.equals(""))
{
conversionOutput.setText("0.0");
}
else
{
conversionOutput.setText(displayText);
}
}
private void convertMilesToKilometers(float cAmount) {
float total;
total = cAmount * milesToKil;
String temp2 = total + "";
display(temp2);
}
private void convertKilometersToMiles(float cAmount) {
float total;
total = cAmount * kilToMiles;
String temp2 = total + "";
display(temp2);
}
private void convertInchesToCentimeters(String cAmount) {
float temp;
float total;
temp = Float.parseFloat(cAmount);
total = temp * inchToCent;
String temp2 = total + "";
display(temp2);
}
private void convertCentimetersToInches(String cAmount) {
float temp;
float total;
temp = Float.parseFloat(cAmount);
total = temp * centToInch;
String temp2 = total + "";
display(temp2);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
In your oncreate method, after the line addToSpinner();
add this line of code
option.setOnItemSelectedListener(this);
It would work.
You need to set an onItemSelectedListener to your spinner.
Override the onItemSelected method in the listener.
For example
option.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// if you have the spinner
String toastText = option.getSelectedItem().toString();
// if you havent
String toastText = parent.getItemAtPosition(pos).toString();
});
Hope this can bring you further.
I separated my app in 3 classes. the main class where the user can choose which feature to use. The map feature works fine but my directions features doesn't when the user clicks on the button is causes a force close, I think it has something to do with the layout.
Main Class file
package com.sammy.umass;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
public class UMassGuide extends Activity {
/** Called when the activity is first created. */
//buttons
private Button goHereButton;
private Button mapButton;
private Button spireButton;
private Button sparkButton;
private Button websiteButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goHereButton = (Button) findViewById(R.id.button1);
goHereButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new Intent(UMassGuide.this, DirectionsScreenActivity.class);
startActivity(i);
}
});
mapButton = (Button) findViewById(R.id.button2);
mapButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new Intent(UMassGuide.this, UmassMap.class);
startActivity(i);
}
});
spireButton = (Button) findViewById(R.id.button3);
spireButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Uri uri = Uri.parse("https://spire.umass.edu/psp/heproda/EMPLOYEE/HRMS/?cmd=login&languageCd=ENG&");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
}
});
sparkButton = (Button) findViewById(R.id.button4);
sparkButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Uri uri = Uri.parse("https://spark.oit.umass.edu/webct/logonDisplay.dowebct");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
}
});
websiteButton = (Button) findViewById(R.id.button5);
websiteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Uri uri = Uri.parse("http://www.umass.edu/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
}
});
}
}
Directions File (Force Close happens when this classes is being opened)
package com.sammy.umass;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
public class DirectionsScreenActivity extends ExpandableListActivity {
ExpandableListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up our adapter
mAdapter = new MyExpandableListAdapter();
setListAdapter(mAdapter);
registerForContextMenu(getExpandableListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Sample menu");
menu.add(0, 0, 0, R.string.expandable_list_sample_action);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
String title = ((TextView) info.targetView).getText().toString();
int type = ExpandableListView.getPackedPositionType(info.packedPosition);
if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
Toast.LENGTH_SHORT).show();
return true;
} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
/**
* A simple adapter which maintains an ArrayList of photo resource Ids.
* Each photo is displayed as an image. This adapter supports clearing the
* list of photos and adding a new photo.
*
*/
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// Sample data set. children[i] contains the children (String[]) for groups[i].
private String[] groups = { " Academic Buildings", " Residential Buildings", " Dining Commons", " All Buildings A-Z" };
private String[][] children = {
{ "Agricultural Engineering Bldg", "Army ROTC Bldg", "Arnold House", "(Studio) Arts Building" },
{ "Baker Hall", "Brett Hall", "Brooks Hall", "Brown Hall" },
{ "Berkshire", "Franklin","Hampden","Hampshire","Worcester" },
{ "Agricultural Engineering Bldg", "Army ROTC Bldg", "Arnold House", "(Studio) Arts Building" }
};
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return children[groupPosition].length;
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 64);
TextView textView = new TextView(DirectionsScreenActivity.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(36, 0, 0, 0);
return textView;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getChild(groupPosition, childPosition).toString());
return textView;
}
public Object getGroup(int groupPosition) {
return groups[groupPosition];
}
public int getGroupCount() {
return groups.length;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
}
Have you added the DirectionScreenActivity to your Manifest file? If not, that could cause a fatal crash.