Referencing or Creating a Drawable from its Res ID (Int) Value? - android

I would like to be able to store a drawables INT value (ResourceID) in SQLite and later be able to pull it from the database and convert it to a drawable to be viewed in a listview.
The following snippit generates 2 values, the ResID portion is a int value that I would like to be able to convert back to the drawable in another activity.\
Drawable myDrawable = getResources().getDrawable(
images[position]);
Log.e("DRAWABLE", "DrawableId 1: " + myDrawable);
int resId = images[position];
Log.e("DRAWABLE", "DrawableId 2: " + resId);
What should I do to convert ResID to a drawable? If possible
PicturePickerFragment
public class PicturePickerFragment extends DialogFragment {
ListView listView;
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
// attach adapter to a list view
// A String[] array that will hold the names of the items.
public static final String[] descriptions = { "Baby", "Baking",
"Barbershop", "Camping", "Conference Call", "Funeral", "Gambling",
"Gardening", "Halloweeen", "Medicine", "Meeting", "Poker",
"Christmas", "Wedding" };
public static final Integer[] images = { R.drawable.baby,
R.drawable.baking, R.drawable.barbershop, R.drawable.camping,
R.drawable.conferencecall, R.drawable.funeral, R.drawable.gambling,
R.drawable.gardening, R.drawable.halloween, R.drawable.medicine,
R.drawable.meeting, R.drawable.poker, R.drawable.santa,
R.drawable.wedding };
Button btn_pic;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.dialog_view, null);
// defining the alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(convertView);
builder.setTitle(R.string.event_type);
builder.setPositiveButton(R.string.select_picture,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// call the method on the parent activity when
// user click the positive button
}
});
// populating the array list
for (int i = 0; i < descriptions.length; i++) {
RowItem item = new RowItem(images[i], descriptions[i]);
rowItems.add(item);
}
// defining listview and using array adapter
listView = (ListView) convertView.findViewById(R.id.listViewFragment2);
DrawableAdapter adapter = new DrawableAdapter(getActivity(), rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
// final int item = images[position];
Drawable myDrawable = getResources().getDrawable(
images[position]);
Log.e("DRAWABLE", "DrawableId 1: " + myDrawable);
int resId = images[position];
Log.e("DRAWABLE", "DrawableId 2: " + resId);
Button b = (Button) getActivity()
.findViewById(R.id.btn_picture);
b.setCompoundDrawablesWithIntrinsicBounds(null, myDrawable,
null, null);
}
});
adapter.addAll(rowItems);
return builder.create();
}
}
CreateActivity
public class CreateActivity extends Activity implements OnClickListener {
EditText etTitle;
Button btDate;
Button btTime;
Button btPic;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//onclicklistener
findViewById(R.id.btn_confirm).setOnClickListener(this);
findViewById(R.id.btn_back).setOnClickListener(this);
etTitle = (EditText) findViewById(R.id.editTextTitle);
btDate = (Button) findViewById(R.id.btn_date);
btTime = (Button) findViewById(R.id.btn_time);
btPic = (Button) findViewById(R.id.btn_picture);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_confirm:
String title = etTitle.getText().toString();
String time = btTime.getText().toString();
String date = btDate.getText().toString();
Drawable drawable = btPic.getCompoundDrawables()[1];
int
Log.e("DRAWABLE", "DrawableId 3: " + drawable);
//Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
Log.e("LOG", title);
Log.e("LOG", time);
Log.e("LOG", date);
Bundle newBundle = new Bundle();
newBundle.putString("TITLE", title);
newBundle.putString("TIME", time);
newBundle.putString("DATE", date);
//newBundle.putInt
//Trying to pass a drawable from one activity to another
//newBundle.putParcelable("DRAWABLE", bitmap);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtras(newBundle);
setResult(RESULT_OK, intent);
finish();
break;
case R.id.btn_back:
finish();
break;
}
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
public void showPicturePickerDialog(View v) {
DialogFragment newFragment = new PicturePickerFragment();
newFragment.show(getFragmentManager(), "picturePicker");
}
}
Main Activity
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;
boolean _isBack = true;
ImageButton add;
String title;
String date;
String time;
int resId;
static final int PICK_CONTACT_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
/////////////////////////////////LISTVIEW////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
/////////////////////////////////LISTVIEW////////////////////////////////////////
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
List<Event> events = db.getAllContacts();
adapter.addAll(events);
adapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
// retrieving bitmap from CreateActivity
int drawable = b.getInt("DRAWABLE");
//Bitmap bitmap = (Bitmap) b.getParcelable("DRAWABLE");
// converting from bitmap to drawable
//Drawable drawable = new BitmapDrawable(getResources(), bitmap);
// Event newEvent = new Event();
// newEvent.set_date(date);
// newEvent.set_title(title);
// newEvent.set_time(time);
// set drawable
// newEvent.set_drawable(drawable);
// lstEvents.add(newEvent);
// adapter.addAll(lstEvents);
// adapter.notifyDataSetChanged();
///////////////////////////////DATABASE/////////////////////////////////////////////
/**
* CRUD OPERATIONS
*/
Log.e("Insert: ", "Inserting ..");
db.addEvent(new Event(0, title, time, date, drawable));
// Reading all contacts
Log.e("Reading: ", "Reading all contacts..");
// List<Event> events = db.getAllContacts();
List<Event> events = db.getAllContacts();
adapter.addAll(events);
adapter.notifyDataSetChanged();
//logging all events
for (Event ev : events) {
String log = "Id: " + ev.get_Id() + " ,Title: "
+ ev.get_title() + " ,Date: " + ev.get_date();
// Writing Contacts to log
Log.e("Name: ", log);
}
///////////////////////////////DATABASE/////////////////////////////////////////////
}
}
}
}

I believe storing the Resource Id is not the right approach, since Id's are only unique to each type of resource. So there are possible of same Id for two different resources.
The best approach would be to store the file name of resource as string.
You can retrieve the resource id with the resource file name using Resource Identifier
int resourceId = getResources().getIdentifier("file_name", "drawable", getPackageName());

Related

How to update and add a new list in listView?

In my Activity A, it has one icon button and one listView. The icon button is used to intent to B and C while the listView is used to intent B to do some edit.
I have 3 activities, A, B and C.The flow of activity is from A to B then C. From C, all the images and value will be returned to B then A. All the returned value and image will be loaded in listView A.
Now what I trying to achieve is load all value which is get from C and B to A. Next, the list can be updated when listView is clicked.
Activity C
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
selectImage();
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
cancel=(Button)findViewById(R.id.button15);
ok=(Button)findViewById(R.id.button16);
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
finish();
}
});
ok.setOnClickListener(new View.OnClickListener()
{ // return to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
ImageButton imageButton;
ImageView viewImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt = (EditText) findViewById(R.id.editText36);
txt1=(TextView)findViewById(R.id.textView57);
Button b = (Button) findViewById(R.id.button17);
addListenerOnButton();
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img);
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Global.img=null;
Intent i = new Intent(B.this,C.class);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) { // receive fom C
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image from C can be shown here
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
}
Activity A
public class Claims1 extends Fragment {
private int mClickedPosition;
ListView listV;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
mClickedPosition = position;
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
return claims;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create1: // icon is clicked
AlertDialogRadio();
return true;
}
return (super.onOptionsItemSelected(item));
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"B", "Petrol"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Class");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(),B.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition,Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
But now, when I click the icon button to intent class B and C and return values from C and B to A, it only update the listView instead of create a new one. Why would this happen ?
Check my edit
public class Claims1 extends Fragment {
private int mClickedPosition;
ListView listV;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
setMyAdapter();
return claims;
}
public void setMyAdapter() {
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV.setAdapter(adapter);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
m_listItems.clear();
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
setMyAdapter();
break;
}
}
}

How to put a ListView in Fragment

I have a very big problem, well for me it is... So here it is.
I have a fragment that contains a TextView and a Button, when I click the button and choose contacts and I need there numbers and names stored in a ListView and to the right of the name and number I want a button that will be there so that the choosen contact can be deleted... I don't know if you understand, so in the ListView all that will be stored as a single item, NAME than under the name is the contact's NUMBER and on the right side is the delete button... I know that I have to use custom adapter, but I just don't get it.
Here is the code for my adapter
private class MessageAdapter extends ArrayAdapter<Message> {
public MessageAdapter(ArrayList<Message> messages) {
super(getActivity(), 0, messages);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_contact, null);
}
// Configure the view for this Contact
Message m = getItem(position);
TextView nameTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_nameTextView);
nameTextView.setText(m.getNames());
TextView numberTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_numberTextView);
numberTextView.setText(m.getNumbers());
return convertView;
}
}
and here is what I try to do to put the contact in the list...
if (requestCode == REQUEST_CONTACT) {
Uri result = data.getData();
Log.v("Contact", "Got a result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for phone numbers for the selected contact id
Cursor c = getActivity().getContentResolver()
.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?",
new String[] { id },
ContactsContract.Contacts.DISPLAY_NAME);
int phoneIdx = c.getColumnIndex(Phone.NUMBER);
int phoneType = c.getColumnIndex(Phone.TYPE);
int nameIdx = c.getColumnIndex(Phone.DISPLAY_NAME);
if (c.getCount() == 1) {
c.moveToFirst();
// contact has a single phone number, so there's no need to
// display a second dialog
mName = c.getString(nameIdx);
mNumber = c.getString(phoneIdx);
// Ovo radim ovako da bih mogao da ih upisem u fajl
mMessage.setmNames(mName);
mMessage.setmNumbers(mNumber);
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
c.close();
}
}
So when I get the number and name of the selected contact I want to add it to the list, but I always get only the last selected number and name... Hope you understand what I mean, thank you.
And here are the onCreate and onCreateView, just in case:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_message, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Ovo ispod omogucava da se ugase sve activities i da se vrati na
// pocetnu valjda
// Zavisi sta smo stavili da nam bude parent class u xml manifest
if (NavUtils.getParentActivityName(getActivity()) != null) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
mTextField = (EditText) v.findViewById(R.id.message_text);
mTextField.setText(mMessage.getmText());
mTextField.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mMessage.setmText(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mAddContactButton = (Button) v.findViewById(R.id.message_contact);
mAddContactButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, REQUEST_CONTACT);
}
});
return v;
}
and onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMessage = new Message();
UUID messageId = (UUID) getArguments()
.getSerializable(EXTRA_MESSAGE_ID);
mMessage = MessageLab.get(getActivity()).getMessage(messageId);
mMessages = MessageLab.get(getActivity()).getMessages();
MessageAdapter adapter = new MessageAdapter(mMessages);
setListAdapter(adapter);
setHasOptionsMenu(true);
}
the class
public class MessageFragment extends ListFragment {
private ArrayList<String> names_list = new ArrayList<String>();
private ArrayList<String> numbers_list = new ArrayList<String>();
private ArrayList<Message> mMessages;
private Message mMessage;
private EditText mTextField;
private Button mAddContactButton;
private String mName, mNumber;
private String build_name="", build_number="";
public static final String EXTRA_MESSAGE_ID = "com.falca.emergencymessage.message_id";
private static final int REQUEST_CONTACT = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMessage = new Message();
UUID messageId = (UUID) getArguments()
.getSerializable(EXTRA_MESSAGE_ID);
mMessage = MessageLab.get(getActivity()).getMessage(messageId);
mMessages = MessageLab.get(getActivity()).getMessages();
MessageAdapter adapter = new MessageAdapter(mMessages);
setListAdapter(adapter);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (NavUtils.getParentActivityName(getActivity()) != null) {
NavUtils.navigateUpFromSameTask(getActivity());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_message, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Ovo ispod omogucava da se ugase sve activities i da se vrati na
// pocetnu valjda
// Zavisi sta smo stavili da nam bude parent class u xml manifest
if (NavUtils.getParentActivityName(getActivity()) != null) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
mTextField = (EditText) v.findViewById(R.id.message_text);
mTextField.setText(mMessage.getmText());
mTextField.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mMessage.setmText(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mAddContactButton = (Button) v.findViewById(R.id.message_contact);
mAddContactButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, REQUEST_CONTACT);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_CONTACT) {
Uri result = data.getData();
Log.v("Contact", "Got a result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for phone numbers for the selected contact id
Cursor c = getActivity().getContentResolver()
.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?",
new String[] { id },
ContactsContract.Contacts.DISPLAY_NAME);
int phoneIdx = c.getColumnIndex(Phone.NUMBER);
int phoneType = c.getColumnIndex(Phone.TYPE);
int nameIdx = c.getColumnIndex(Phone.DISPLAY_NAME);
if (c.getCount() > 1) { // contact has multiple phone numbers
final CharSequence[] numbers = new CharSequence[c.getCount()];
int i = 0;
if (c.moveToFirst()) {
mName = c.getString(nameIdx);
while (!c.isAfterLast()) { // for each phone number, add it
// to the numbers array
String type = (String) Phone.getTypeLabel(
this.getResources(), c.getInt(phoneType), ""); // insert
// a
// type
// string
// in
// front
// of
// the
// number
String number = type + ": " + c.getString(phoneIdx);
numbers[i++] = number;
c.moveToNext();
}
// build and show a simple dialog that allows the user to
// select a number
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle(R.string.select_contact_phone_number_and_type);
builder.setItems(numbers,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int item) {
mNumber = (String) numbers[item];
int index = mNumber.indexOf(":");
mNumber = mNumber.substring(index + 2);
// Ovo radim ovako da bih mogao da ih upisem
// u fajl
build_name += mName + ";";
build_number += mNumber + ";";
mMessage.setmNames(build_name);
mMessage.setmNumbers(build_number);
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(getActivity());
alert.show();
} else
Log.w("Contact", "No results");
} else if (c.getCount() == 1) {
c.moveToFirst();
// contact has a single phone number, so there's no need to
// display a second dialog
mName = c.getString(nameIdx);
mNumber = c.getString(phoneIdx);
// Ovo radim ovako da bih mogao da ih upisem u fajl
build_name += mName + ";";
build_number += mNumber + ";";
mMessage.setmNames(build_name);
mMessage.setmNumbers(build_number);
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
c.close();
}
}
}
#Override
public void onResume() {
super.onResume();
// Update the list view
((MessageAdapter) getListAdapter()).notifyDataSetChanged();
}
//MessageAdapter sluzi za rucno pravljenje liste poruka
private class MessageAdapter extends ArrayAdapter<Message> {
public MessageAdapter(ArrayList<Message> messages) {
super(getActivity(), 0, messages);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_contact, null);
}
// Configure the view for this Message
Message m = getItem(position);
TextView nameTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_nameTextView);
nameTextView.setText(m.getmNames());
TextView numberTextView = (TextView) convertView
.findViewById(R.id.contact_list_item_numberTextView);
numberTextView.setText(m.getmNumbers());
return convertView;
}
}
public static MessageFragment newInstance(UUID messageId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_MESSAGE_ID, messageId);
MessageFragment fragment = new MessageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onPause() {
super.onPause();
MessageLab.get(getActivity()).saveMessages();
}
}
It seems that you always update the same single mMessage field.
mMessage.setmNames(build_name);
mMessage.setmNumbers(build_number);
When you have a new entry you have to update you ArrayList mMessages. Add an entry to the list. The adapter always has this arrayList as data source so you have to update this arrayList.
So for every entry create a new message and add it to the mMessages array list.

Android SQLite Passing Item selected in gridview into another Activity for editing

Basically I have a Database with Accounts in them. I use GridView for viewing them, and from there you can select an Account and it will direct you to my Activity AccountManagement wherein you can modify, delete or just view all of the details of the selected Account from the GridView.
My problem is passing the data from the selection in GridView to AccountManagement.I'm not entirely sure how to use Intents for this properly. So far the code below doesn't work because I don't know how to pass the data into my AccountManagement and reference it properly from there.
Code is here, anything with Acc is problematic since Acc is where I'm supposed to put the data from GridView. I marked all those lines with a long ------ to make it easier to spot. Feel free to ask for any missing code.
EDIT DOWN BELOW WITH FINAL CODE FOR REFERENCE.
AccountManagement snippet:
public class AccountDetails extends Activity {
DatabaseHelper dbHelper;
static public LinearLayout Linlay;
EditText txtName;
EditText txtAmt;
EditText txtPurpose;
TextView txtDate;
TextView txtEditDate;
Spinner spinStat;
Spinner spinTerm;
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
super.onCreate(savedInstanceState);
setContentView(R.layout.accdetails);
Linlay = (LinearLayout) findViewById(R.id.Linlay);
spinStat = (Spinner) findViewById(R.id.spinStat);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
txtName = (EditText) findViewById(R.id.txtDelName);
txtAmt = (EditText) findViewById(R.id.txtDelAmt);
txtPurpose = (EditText) findViewById(R.id.txtDelPurpose);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
txtDate = (TextView) findViewById(R.id.colDate);
txtEditDate = (TextView) findViewById(R.id.colEditDate);
spinStat = (Spinner) findViewById(R.id.spinStat);
Utilities.ManageTermSpinner(AccountDetails.this, spinTerm);
for(int i=0;i<spinTerm.getCount();i++)
{
long id=spinTerm.getItemIdAtPosition(i);
if(id==Acc.getTerms())--------------------------------------------
{
spinTerm.setSelection(i, true);
break;
}
}
Utilities.ManageStatSpinner(AccountDetails.this, spinStat);
for(int j=0;j<spinStat.getCount();j++)
{
long id=spinStat.getItemIdAtPosition(j);
if(id==Acc.getStatus())--------------------------------------------
{
spinStat.setSelection(j, true);
break;
}
}
txtName.setText(Acc.getName());---------------------------------------
txtAmt.setText(String.valueOf(Acc.getAmt()));-------------------------
txtPurpose.setText(Acc.getPurpose());---------------------------------
Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog diag = Alerts.DeleteConfirm(AccountDetails.this, Acc );--------------------------------
diag.show();
}
});
}
GridView snippet:
This is where I should be getting the data to put into Acc but I'm not sure how, so everything here can be changed since I'm not sure if this is the ideal way to do it.
try {
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
try {
SQLiteCursor cr = (SQLiteCursor) parent.getItemAtPosition(position);
String name = cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
int amount = cr.getInt(cr.getColumnIndex(DatabaseHelper.colAmount));
String purpose = cr.getString(cr.getColumnIndex(DatabaseHelper.colPurpose));
String Terms = cr.getString(cr.getColumnIndex(DatabaseHelper.colTermsClass));
String Status = cr.getString(cr.getColumnIndex(DatabaseHelper.colStatClass));
String date = cr.getString(cr.getColumnIndex(DatabaseHelper.colDate));
String editdate = cr.getString(cr.getColumnIndex(DatabaseHelper.colEditDate));
Account acc = new Account(name, amount, purpose, db.GetTermsID(Terms),date,editdate,db.GetStatID(Status));
acc.SetID((int) id);
Intent myIntent = new Intent(AccountManager.this, AccountDetails.class);
Bundle extras = new Bundle();
myIntent.putExtras(extras);
startActivityForResult(myIntent, 0);
} catch (Exception ex) {
Alerts.CatchError(AccountManager.this, ex.toString());
}
}
});
} catch (Exception ex) {
}
EDIT:
GridView final snippet:
try {
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
try {
SQLiteCursor cr = (SQLiteCursor) parent.getItemAtPosition(position);
String name = cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
int amount = cr.getInt(cr.getColumnIndex(DatabaseHelper.colAmount));
String purpose = cr.getString(cr.getColumnIndex(DatabaseHelper.colPurpose));
String Terms = cr.getString(cr.getColumnIndex(DatabaseHelper.colTermsClass));
String Status = cr.getString(cr.getColumnIndex(DatabaseHelper.colStatClass));
String date = cr.getString(cr.getColumnIndex(DatabaseHelper.colDate));
String editdate = cr.getString(cr.getColumnIndex(DatabaseHelper.colEditDate));
Account acc = new Account(name, amount, purpose, db.GetTermsID(Terms),date,editdate,db.GetStatID(Status));
acc.SetID((int) id);
Intent myIntent = new Intent(AccountManager.this, AccountDetails.class);
myIntent.putExtra("AccountObject", acc);
startActivityForResult(myIntent, 0);
} catch (Exception ex) {
Alerts.CatchError(AccountManager.this, ex.toString());
}
}
});
} catch (Exception ex) {
}
AccountManagement final snippet:
#Override
public void onCreate(Bundle savedInstanceState) {
final Account Acc = (Account) getIntent().getSerializableExtra("AccountObject");
super.onCreate(savedInstanceState);
setContentView(R.layout.accdetails);
Linlay = (LinearLayout) findViewById(R.id.Linlay);
spinStat = (Spinner) findViewById(R.id.spinStat);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
txtName = (EditText) findViewById(R.id.txtDelName);
txtAmt = (EditText) findViewById(R.id.txtDelAmt);
txtPurpose = (EditText) findViewById(R.id.txtDelPurpose);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
txtDate = (TextView) findViewById(R.id.colDate);
txtEditDate = (TextView) findViewById(R.id.colEditDate);
spinStat = (Spinner) findViewById(R.id.spinStat);
Utilities.ManageTermSpinner(AccountDetails.this, spinTerm);
for(int i=0;i<spinTerm.getCount();i++)
{
long id=spinTerm.getItemIdAtPosition(i);
if(id==Acc.getTerms())
{
spinTerm.setSelection(i, true);
break;
}
}
Utilities.ManageStatSpinner(AccountDetails.this, spinStat);
for(int j=0;j<spinStat.getCount();j++)
{
long id=spinStat.getItemIdAtPosition(j);
if(id==Acc.getStatus())
{
spinStat.setSelection(j, true);
break;
}
}
txtName.setText(Acc.getName());
txtAmt.setText(String.valueOf(Acc.getAmt()));
txtPurpose.setText(Acc.getPurpose());
Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog diag = Alerts.DeleteConfirm(AccountDetails.this, Acc );
diag.show();
}
});
Button modify = (Button) findViewById(R.id.modify);
modify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog diag = Alerts.ShowEditDialog(AccountDetails.this, Acc);
diag.show();
}
});
}
You aren't putting that 'acc' object into the Bundle and there by you are starting AccountDetails activity with empty Intent.
Here is an example: Send object from one activity to another Activity using Intent

ListView does not refresh dynamically and causes Error

I am unable to remove an object in a ListView. I have been trying to remove an object from an adapter, and then call onDataSetChanged(); but it does not seem to ever remove the object from the screen.
I can successfully remove the object from the database, but the object persists on screen regardless.
I believe that because the view does not refresh properly, it allows me to continue to swipe-to-dismiss the items in the list and eventually leads to an IndexOutOfBoundsException.
Does anyone see why my ListView will not update properly? I know there are plenty of questions similar to this one, but most refer to onDataSetChanged() as a solution, and it doesn't seem to be my problem.
06-01 19:33:46.734: E/AndroidRuntime(9011): Process: com.example.datetracker, PID: 9011
06-01 19:33:46.734: E/AndroidRuntime(9011): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
06-01 19:33:46.734: E/AndroidRuntime(9011): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
06-01 19:33:46.734: E/AndroidRuntime(9011): at java.util.ArrayList.get(ArrayList.java:308)
06-01 19:33:46.734: E/AndroidRuntime(9011): at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:337)
06-01 19:33:46.734: E/AndroidRuntime(9011): at com.example.datetracker.MainActivity$1.onDismiss(MainActivity.java:97)
06-01 19:33:46.734: E/AndroidRuntime(9011): at com.example.datetracker.SwipeDismissListViewTouchListener$3.onAnimationEnd(SwipeDismissListViewTouchListener.java:362)
06-01 19:33:46.734: E/AndroidRuntime(9011): at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1056)
06-01 19:33:46.734: E/AndroidRuntime(9011): at android.animation.ValueAnimator.access$400(ValueAnimator.java:50)
06-01 19:33:46.734: E/AndroidRuntime(9011): at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:644)
06-01 19:33:46.734: E/AndroidRuntime(9011): at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:660)
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
List<Event> lstEvents = new ArrayList<Event>();
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;
boolean _isBack = true;
ImageButton add;
String title;
String date;
String time;
int resId;
Context context;
static final int PICK_CONTACT_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
// ///////////////////////////////LISTVIEW////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, db.getAllContacts());
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
context = this;
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
DatabaseHandler db = new DatabaseHandler(context);
EventAdapter adapter = new EventAdapter(context,
db.getAllContacts());
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView,
int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
adapter.addAll(db.getAllContacts());
db.deleteEvent(adapter.getItem(position));
adapter.remove(adapter.getItem(position));
}
adapter.clear();
adapter.notifyDataSetChanged();
}
});
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during
// // ListView scrolling,
// // we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());
adapter.addAll(db.getAllContacts());
adapter.notifyDataSetChanged();
}
// #Override
// protected void onResume() {
// // TODO Auto-generated method stub
// super.onResume();
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
// DatabaseHandler db = new DatabaseHandler(this);
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
//
// super.onResume();
// adapter.swapItems(db.getAllContacts());
// }
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, db.getAllContacts());
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
Bitmap bitmap = b.getParcelable("BITMAP");
// ///CONVERTING A BITMAP TO A BYTE[]
byte[] image = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
image = bos.toByteArray();
// ///////
// /////////////////////////////DATABASE/////////////////////////////////////////////
/**
* CRUD OPERATIONS
*/
Log.e("Insert: ", "Inserting ..");
db.addEvent(new Event((int) Math.floor(Math.random() * 101),
title, time, date, image));
// Reading all contacts
Log.e("Reading: ", "Reading all contacts..");
adapter.addAll(db.getAllContacts());
adapter.notifyDataSetChanged();
// logging all events
for (Event ev : db.getAllContacts()) {
String log = "Id: " + ev.get_Id() + " ,Title: "
+ ev.get_title() + " ,Date: " + ev.get_date()
+ " ,RESOURCEID: " + ev.get_image();
// Writing Contacts to log
Log.e("Name: ", log);
}
// /////////////////////////////DATABASE/////////////////////////////////////////////
}
}
}
}
EventAdapter
public class EventAdapter extends ArrayAdapter<Event> {
private List<Event> events;
// View lookup cache
private static class ViewHolder {
//adding drawable to imageview
ImageView img;
TextView title;
TextView time;
TextView date;
}
public EventAdapter(Context context, List<Event> objects) {
super(context, R.layout.date_detail);
this.events = events;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event event = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.date_detail, null);
viewHolder.title = (TextView) convertView
.findViewById(R.id.textViewTitle);
viewHolder.time = (TextView) convertView
.findViewById(R.id.textViewTime);
viewHolder.date = (TextView) convertView
.findViewById(R.id.textViewDate);
//adding drawable to imageview
viewHolder.img = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(event._title);
viewHolder.time.setText(event._time);
viewHolder.date.setText(event._date);
//convert from byte array to bitmap
Bitmap bitmap = convertByteArrayToBitmap(event._image);
// CONVERT BITMAP TO DRAWABLE
viewHolder.img.setImageBitmap(bitmap);
// Return the completed view to render on screen
return convertView;
}
public static Bitmap convertByteArrayToBitmap(
byte[] byteArrayToBeCOnvertedIntoBitMap)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(
byteArrayToBeCOnvertedIntoBitMap, 0,
byteArrayToBeCOnvertedIntoBitMap.length);
return bitmap;
}
public void swapItems(List<Event> events) {
this.events = events;
notifyDataSetChanged();
}
}
The problem was solved by removing the following lines of code in the swipeDismissViewListener and the OnActivityResult.
DatabaseHandler db = new DatabaseHandler(context);
EventAdapter adapter = new EventAdapter(context, db.getAllContacts());

How should I handle run again my app while I have one minimized?

I wrote android app that reads information from database and show on ListView it has ActionBar at top of the page and ButtonBar at bottom, It is worked correct till I press BackButton of my phone and my application minimized. Then I tried to run new one(without put away previous one) by click on Icon of that from list of installed application. when I try to open new one open application but not show any row of database. Just ActionBar at top of the page and the ButtonBar came up and top edge of that fix to bottom edge of ActionBar. how should i fix it?
I added code of my first Activity as follow, I will be thanks full if don't minus me if my question is incorrect.
#SuppressLint({ "NewApi", "ServiceCast" })
public class Index extends Activity implements OnItemClickListener {
private final static String EXTRA_MASSAGE = "";
private final static String MESSAGE_TO_SETTING = null;
// add for data base
private static final String DB_NAME = "amam-khmini.gdb";
// database
private static final String TABLE_NAME = "cat";
private static final String CAT_ID = "_id";
private static final String CAT_TEXT = "text";
private static final String TABLE_NAME2 = "font";
private static final String FONT_ID = "_id";
private static final String FONT_TYPE = "font_type";
private static final String FONT_SIZE = "font_size";
private SQLiteDatabase database;
static ListView listView;
List<RowItem> rowItems;
private ArrayList<String> poemtype;
private ArrayList<Integer> ids;
private String fontName;
private int fontSize;
// end of database
static CustomListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// set custom view
View actionBarView = getLayoutInflater().inflate(R.layout.actionbar,
null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
actionBar.setCustomView(actionBarView, params);
// Hide the home icon
actionBar.setIcon(android.R.color.transparent);
actionBar.setLogo(android.R.color.transparent);
TextView title = (TextView) findViewById(R.id.title);
setContentView(R.layout.activity_index);
// add for database
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this,
DB_NAME);
database = dbOpenHelper.openDataBase();
fillIndex();
getFont();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < poemtype.size(); i++) {
RowItem item = new RowItem(poemtype.get(i));
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListViewAdapter(this, R.layout.indexitem_row,
rowItems);
adapter.setFontType(fontName);
adapter.setFontize(fontSize);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
listView.setAdapter(null);
super.onDestroy();
}
private void getFont() {
// TODO Auto-generated method stub
String[] tableColumns = new String[] { FONT_TYPE, FONT_SIZE };
String whereClause = FONT_ID + " LIKE ?";
String[] whereArgs = new String[] { String.valueOf(1) };
Cursor fontCursor = database.query(TABLE_NAME2, tableColumns,
whereClause, whereArgs, null, null, FONT_ID);
fontCursor.moveToFirst();
if (!fontCursor.isAfterLast()) {
fontName = fontCursor.getString(0);
fontSize = fontCursor.getInt(1);
}
Log.d("type of font in getFont Index", fontName);
Log.d("size of font in getFont Index", Integer.toString(fontSize));
fontCursor.close();
}
private void fillIndex() {
poemtype = new ArrayList<String>();
ids = new ArrayList<Integer>();
String[] tableColumns = new String[] { CAT_ID, CAT_TEXT };
String whereClause = "PARENT_ID = ?";
String[] whereArgs = new String[] { "6001" };
Cursor poetCursor = database.query(TABLE_NAME, tableColumns,
whereClause, whereArgs, null, null, CAT_ID);
poetCursor.moveToFirst();
if (!poetCursor.isAfterLast()) {
do {
Integer id = poetCursor.getInt(0);
String name = poetCursor.getString(1);
poemtype.add(name);
ids.add(id);
} while (poetCursor.moveToNext());
}
poetCursor.close();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent intent = new Intent(this, PoemType.class);
String[] extra = { ids.get(position).toString(),
poemtype.get(position).toString() };
intent.putExtra(EXTRA_MASSAGE, extra);
startActivity(intent);
}
public void showSettings(View view) {
Intent intent = new Intent(this, Options.class);
String message = "Index";
intent.putExtra(MESSAGE_TO_SETTING, message);
startActivity(intent);
}
public static void setFont(String fontName1, int fontSize1) {
// TODO Auto-generated method stub
adapter.setFontType(fontName1);
adapter.setFontize(fontSize1);
listView.setAdapter(adapter);
}
public void showFontSetting(final View view) {
PopupMenu popup = new PopupMenu(this, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
String message = "Index";
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(Index.this,
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(view.getContext(),
IndexFont.class);
intent.putExtra(MESSAGE_TO_SETTING, message);
startActivity(intent);
break;
case R.id.item2:
Intent intent2 = new Intent(view.getContext(),
HemistichFont.class);
intent2.putExtra(MESSAGE_TO_SETTING, message);
startActivity(intent2);
break;
}
return true;
}
});
}
}
just move the following code from onCreate to onResume. now even if the application got minimized, when opened again the onResume will be triggered and the listView will be populated again
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this,
DB_NAME);
database = dbOpenHelper.openDataBase();
fillIndex();
getFont();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < poemtype.size(); i++) {
RowItem item = new RowItem(poemtype.get(i));
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListViewAdapter(this, R.layout.indexitem_row,
rowItems);
adapter.setFontType(fontName);
adapter.setFontize(fontSize);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
don't forget to remove the lines from your onCreate or you will be populating the listview twice.
Hope this work out with you. give me a feedback

Categories

Resources