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;
}
}
}
Related
I've already exhausted my efforts on this one but can't seem to find answers. So our instructor told us not to use Database. So the app is like filling up a form, asking for your picture, lastname, firstname and your course and then will display the items on your listview which is another activity.
How can I do this without using a database? Thanks! Please check out the my code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ArrayList<Student> studentArrayList = new ArrayList<Student>();
StudentAdapter studentAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
studentAdapter = new StudentAdapter(this, studentArrayList);
listView.setAdapter(studentAdapter);
}
//back button
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}else if(id == R.id.action_add){
Intent add = new Intent(MainActivity.this, AddStudentActivity.class);
startActivity(add);
}
return super.onOptionsItemSelected(item);
}
//show add menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_menu, menu);
return true;
}
StudentAdapter.java
Context context;
ArrayList<Student> studentArrayList;
LayoutInflater inflater;
//contructor
public StudentAdapter(Context context, ArrayList<Student> studentArrayList) {
this.context = context;
this.studentArrayList = studentArrayList;
}
#Override
public int getCount() {
return studentArrayList.size();
}
#Override
public Object getItem(int position) {
return studentArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLName);
holder.fname = (TextView) convertView.findViewById(R.id.textFName);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
//
holder.image.setImageResource(studentArrayList.get(position).getImage());
holder.lname.setText(studentArrayList.get(position).getLname());
holder.fname.setText(studentArrayList.get(position).getFname());
holder.course.setText(studentArrayList.get(position).getCourse());
return convertView;
}
private static class ViewHolder{
ImageView image;
TextView lname, fname, course;
}
AddStudentActivity.java
ImageView studentImage;
EditText studLname, studFname;
Button btnSave, btnCancel;
Spinner cboCourse;
String selectedCourse;
Uri imageUri;
private static final int PICK_IMAGE = 100;
ArrayList<Student> studentArrayList = new ArrayList<Student>();
StudentAdapter studentAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student);
//
studentImage = (ImageView) findViewById(R.id.imageView2);
studLname = (EditText) findViewById(R.id.editText1);
studFname = (EditText) findViewById(R.id.editText2);
cboCourse = (Spinner) findViewById(R.id.spinner);
btnSave = (Button) findViewById(R.id.btnsave);
btnCancel = (Button) findViewById(R.id.btncancel);
cboCourse.setOnItemSelectedListener(this);
studentImage.setOnClickListener(this);
btnSave.setOnClickListener(this);
btnCancel.setOnClickListener(this);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved Changes");
builder.setMessage("Are you sure you want to leave?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.imageView2:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
break;
case R.id.btnsave:
if(studLname.equals("") || studFname.equals("") || cboCourse.getSelectedItem().equals(0)){
Toast.makeText(getApplicationContext(), "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}else{
//add a statement to add an item here
studentArrayList.add(studentImage.getResources().toString(), studLname.getText().toString(), studFname.getText().toString(), cboCourse.getSelectedItem());
// studentArrayList.add(studentImage.getBaseline(), studLname.getText().toString(), studFname.getText().toString(), cboCourse.getSelectedItem().toString());
Toast.makeText(getApplicationContext(), "Item successfully added!", Toast.LENGTH_SHORT).show();
Intent home = new Intent(AddStudentActivity.this, MainActivity.class);
startActivity(home);
studentAdapter.notifyDataSetChanged();
}
break;
case R.id.btncancel:
studLname.setText("");
studFname.setText("");
break;
}
}
//handles opening the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
studentImage.setImageURI(imageUri);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//for the spinner
int sid = parent.getId();
switch (sid){
case R.id.spinner:
selectedCourse = this.cboCourse.getItemAtPosition(position).toString();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Student.java
package com.example.studentinfoapplication;
import java.io.Serializable;
public class Student implements Serializable {
private int image;
private String lname, fname, course;
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Student class
I added a global Arraylist to your Student Class.
public class Student implements Serializable {
public static ArrayList<Student> studentArrayList = new ArrayList<>();
private Uri image;
private String lname, fname, course;
public Student(){ //Add your constructor.
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
StudentAdapter studentAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
Log.d("test", "students" + Student.studentArrayList);
if (Student.studentArrayList != null) {
studentAdapter = new StudentAdapter(this, Student.studentArrayList);
listView.setAdapter(studentAdapter);
}
}
AddStudentActivity
ArrayList<Student> studentArrayList = new ArrayList<Student>();
Remove this line at the top because we are referring to the global arraylist in Student class.
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.imageView2:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
break;
case R.id.btnsave:
if(!studLname.equals("") || !studFname.equals("") || !cboCourse.getSelectedItem().equals(0)){
String lname = studLname.getText().toString();
String fname = studFname.getText().toString();
String course = cboCourse.getSelectedItem().toString();
student.setLname(lname);
student.setFname(fname);
student.setCourse(course);
Student.studentArrayList.add(student); //Global arraylist
Log.d("test", "students:" + Student.studentArrayList);
Toast.makeText(getApplicationContext(), "Item successfully added!", Toast.LENGTH_SHORT).show();
Intent home = new Intent(AddStudentActivity.this, MainActivity.class);
startActivity(home);
}else{
Toast.makeText(getApplicationContext(), "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btncancel:
studLname.setText("");
studFname.setText("");
cboCourse.setSelection(0);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
if (data != null) {
imageUri = data.getData();
}
student.setImage(imageUri);
studentImage.setImageURI(imageUri);
}
}
StudentAdapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLName);
holder.fname = (TextView) convertView.findViewById(R.id.textFName);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
//
holder.lname.setText(studentArrayList.get(position).getLname());
holder.fname.setText(studentArrayList.get(position).getFname());
holder.image.setImageURI(studentArrayList.get(position).getImage());
holder.course.setText(studentArrayList.get(position).getCourse());
return convertView;
}
There can be couple of approaches you can try
a) Create singleton class and maintain a list of students that you add and then use the same singleton object in mainactivity to populate list.
b) create serializable/parcellable model having list of studuent ,every time you add the student and send this list to main activity and vice versa to use same model b/w two activities. This is just workaround apprach. I will prefer first one.
So I've run into an issue where I have an item that I click in a listview, it does a makes a few extras, and moves on the my next activity. I get an issue where my app goes to a black screen and the Console tells me
I/Choreographer: Skipped 630 frames! The application may be doing too much work on its main thread.
I've tried reading up on Async but I'm not sure how to use it in my code. So I'm posting my Main activity since this happens without interacting with the second activity.
public class MainActivity extends AppCompatActivity {
ListView ListofList;
ArrayList<String> Lists;
ArrayAdapter<String> ListAdapter;
Button button;
ArrayList<String> Subject = new ArrayList<>();
int Size = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListofList = findViewById(R.id.LofL);
Lists = new ArrayList<String>();
ListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Lists);
ListofList.setAdapter(ListAdapter);
button = findViewById(R.id.AddList);
Lists.add("Test");
ListofList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getBaseContext(), ItemList.class);
String s = (String) ListofList.getItemAtPosition(position);
i.putExtra("Title", s);
i.putExtra("size", Size);
int a = 0;
for (String t : Subject) {
i.putExtra("Item" + a, t);
a++;
}
startActivityForResult(i, 2);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CreateItem.class);
String message = "Please enter the name of the list below.";
i.putExtra("mess", message);
startActivityForResult(i, 1);
}
});
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (data == null) {
}
if (data != null) {
if (requestCode == 1) {
String item = (data.getStringExtra("item"));
Lists.add(item);
ListAdapter.notifyDataSetChanged();
}
}
if (requestCode == 2) {
ArrayList<String> subject = new ArrayList<String>();
int i = 0;
assert data != null;
int size = (data.getIntExtra("ListSize", 0));
Size = size;
while (i <= size) {
String item = (data.getStringExtra("item" + i));
subject.add(item);
i++;
}
Subject = subject;
}
}
}
At the request of Ben P.
public class ItemList extends AppCompatActivity {
static ArrayList<String> customItems;
ArrayAdapter<String> adapter;
ListView lvItems;
Button button;
Button button2;
ArrayAdapter<String> trashAdapter;
ArrayList<String> trash;
ListView itemtrash;
static TextView Title;
String Tit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Title = findViewById(R.id.Title);
//set up Item List
customItems = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, customItems);
lvItems = (ListView) findViewById(R.id.lvItems);
//Set up trash List
trash = new ArrayList<String>();
trashAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, trash);
itemtrash = findViewById(R.id.itemtrash);
//Initialize Buttons
button = findViewById(R.id.AddItem);
button2 = findViewById(R.id.ClearTrash);
Bundle extras = getIntent().getExtras();
if (extras != null) {
((TextView)findViewById(R.id.Title)).setText(extras.getString("Title"));
Tit = extras.getString("Title");
int i = 0;
int size = (extras.getInt("size", 0));
while (i <= size) {
String item = (extras.getString("Item" + i));
if (item == null) {
continue;
}
customItems.add(item);
i++;
}
}
//CharSequence Titlefilter = Title.getText();
//lvItems.setTextFilterEnabled(true);
//ItemList.this.adapter.getFilter().filter(Titlefilter);
//adapter.notifyDataSetChanged();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CreateItem.class);
String message = "Please enter new item below.";
i.putExtra("mess", message);
startActivityForResult(i, 1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
trashAdapter.clear();
trashAdapter.notifyDataSetChanged();
}
});
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = adapter.getItem(position);
trashAdapter.add(s);
adapter.remove(s);
assert s != null;
adapter.notifyDataSetChanged();
trashAdapter.notifyDataSetChanged();
}
});
itemtrash.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = trashAdapter.getItem(position);
customItems.add(s);
trash.remove(s);
adapter.notifyDataSetChanged();
trashAdapter.notifyDataSetChanged();
}
});
lvItems.setAdapter(adapter);
itemtrash.setAdapter(trashAdapter);
}
#Override
public void onBackPressed() {
Intent i = new Intent();
int a = 0;
for (String s : customItems){
String t = adapter.getItem(a);
i.putExtra("item" + a, t);
a++;
}
int size = customItems.size();
i.putExtra("ListSize", size);
setResult(2, i);
finish();
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (data == null) {
}
if (data != null) {
String item = (data.getStringExtra("item"));
String title = Tit;
customItems.add(title + "\n\n" + item);
adapter.notifyDataSetChanged();
}
}
}
I figured it out. I accidentally made an infinite loop with while in the ItemList activity.
I try to make items appear in my list view, when add new contact then add it to list view ,it's not appear when I add new contact.
here is main_fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
ImageView contactImage;
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) view.findViewById(R.id.txtName);
emailTxt = (EditText) view.findViewById(R.id.txtEmail);
phoneTxt = (EditText) view.findViewById(R.id.txtPhone);
addressTxt = (EditText) view.findViewById(R.id.txtAddress);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
if (contactAdapter != null) contactAdapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
resetAddContactPanel();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
final Button addContact = (Button) view.findViewById(R.id.btnadd);
nametxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addContact.setEnabled(!nametxt.getText().toString().trim().equals(""));
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
ArrayAdapter<import_fragment.Contact> contactAdapter;
ListView contactListView;
DatabaseHandler dbHandler;
int longClickedItemIndex;
public void onActivityResult(int reqCode, int resCode, Intent data) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
ImageView contactImageImgView;
contactImageImgView = (ImageView) getActivity().findViewById(R.id.ivContactImage);
if (resCode == Activity.RESULT_OK) {
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void resetAddContactPanel() {
final EditText nametxt, emailTxt, phoneTxt, addressTxt;
nametxt = (EditText) getActivity().findViewById(R.id.txtName);
emailTxt = (EditText) getActivity().findViewById(R.id.txtEmail);
phoneTxt = (EditText) getActivity().findViewById(R.id.txtPhone);
addressTxt = (EditText) getActivity().findViewById(R.id.txtAddress);
nametxt.setText("");
phoneTxt.setText("");
emailTxt.setText("");
addressTxt.setText("");
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
{
ImageView contactImageImgView;
contactImageImgView = (ImageView) view.findViewById(R.id.ivContactImage);
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
if (dbHandler.getContactsCount() != 0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Contact Options");
menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Contact");
menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Contact");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO: Implement editing a contact
break;
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(import_fragment.Contact contact) {
String name = contact.getName();
int contactCount = Contacts.size();
for (int i = 0; i < contactCount; i++) {
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
private void populateList() {
contactAdapter = new ContactListAdapter(getActivity());
contactListView.setAdapter(contactAdapter);
}
final List<import_fragment.Contact> Contacts = new ArrayList<import_fragment.Contact>();
private class ContactListAdapter extends ArrayAdapter<import_fragment.Contact> {
public ContactListAdapter(Context cntx) {
super(cntx, R.layout.fragment_import, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.fragment_import, parent, false);
import_fragment.Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
return view;
}
}
Someone told me u must setAdapter in onCreateView and when I did that i get error Null so I removed it, if this will solve problem then please tell me how to setAdapter in onCreateView without getting null error.
i hope you guys can help me. it`s drivin me crazy find the solution...
i already read some question that similar with my problems, but none solved mine.
here`s the problems
1 have 2 activity...
first --> i have activity that contain a view pager which hold 3 tab fragment.
in this first activity i extends with fragmentActivity
and here the code
public class A_BonRokok_Add_Main_Paged extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Header", "Item", "Info"};
MainActivity main = new MainActivity();
FragmentManager manager;
FragmentTransaction transaction;
Dialog alert;
LayoutInflater li;
LinearLayout someLayout;
Button btnSave_dialog;
Button btnCancel_dialog;
public EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_bon_rokok_add_main_paged);
FragmentPagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
getActionBar().setDisplayHomeAsUpEnabled(true);
pager.setOffscreenPageLimit(3);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_print) {
Toast.makeText(this, "print", Toast.LENGTH_SHORT).show();
}
else if (item.getItemId() == R.id.edit_save) {
Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
}
else{
createDialogConfirm();
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
public void onBackPressed(){
createDialogConfirm();
}
public void createDialogConfirm(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert.show();
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(ChildFragmentPaged.POSITION_KEY, position);
return ChildFragmentPaged.newInstance(args);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
}
public static A_BonRokok_Add_Main_Paged newInstance() {
return new A_BonRokok_Add_Main_Paged();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.save_print, menu);
return super.onCreateOptionsMenu(menu);
}
}
the first activity manage the tab fragment using class which extends fragment...
here the code
public class ChildFragmentPaged extends Fragment {
public static final String POSITION_KEY = "FragmentPositionKey";
private int position;
View root;
static EditText txtDate, txtGudang;
static RadioGroup btnGroupGudang;
static RadioButton btnGudang1, btnGudang2;
static Button btnNewItem, btnNewItem_Cancel;
private database mySQLiteAdapter;
private A_BonRokok_Item_View view = new A_BonRokok_Item_View();
public ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
AdapterView<?> tempAdt;
int tempPos;
public EditText search;
public ArrayList<bonRokokPagedEntity> list;
public ListViewAdapter adapter;
private databasePaged databasePaged;
public static ChildFragmentPaged newInstance(Bundle args) {
ChildFragmentPaged fragment = new ChildFragmentPaged();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
position = getArguments().getInt(POSITION_KEY);
if(position == 0){
root = inflater.inflate(R.layout.t_bon_rokok_header_paged, container,false);
}if (position == 1) {
root = inflater.inflate(R.layout.t_bon_rokok_item_paged, container, false);
settingTabItem();
} else if (position == 2)
root = inflater.inflate(R.layout.t_bon_rokok_info_paged, container, false);
return root;
}
public void settingTabItem() {
listContent = (ListView) root.findViewById(R.id.vl_tab_paged);
btnNewItem = (Button) root.findViewById(R.id.btnNewItem_paged);
search = (EditText)root.findViewById(R.id.search_paged);
try{
databasePaged = new databasePaged(getActivity());
databasePaged.createDataBase();
}catch(IOException ioe){
throw new Error("Unable to craete database");
}
try{
databasePaged.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
btnNewItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(),A_BonRokok_Item_New_Paged.class);
startActivity(intent);
getActivity().finish();
}
});
list = databasePaged.Getvalue();
adapter = new ListViewAdapter(getActivity(), list);
listContent.setAdapter(adapter);
}
private void updateList() {
cursor.requery();
}
public void createMenu(){
final Cursor cursor = (Cursor) tempAdt.getItemAtPosition(tempPos);
final String header = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.d_global_edit_delete,null, false);
ListView lv = (ListView)contentView.findViewById(R.id.d_globalEditDelete_lvEditDelete);
TextView txtHeader = (TextView)contentView.findViewById(R.id.d_globalEditDelete_lblHeader);
Button btnCancel = (Button)contentView.findViewById(R.id.d_globalEditDelete_btnCancel);
txtHeader.setText(header);
ArrayList<String> tempData = new ArrayList<String>();
tempData.add("Edit");
tempData.add("Delete");
int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter tempAdapter = new ArrayAdapter<String>(getActivity(), layoutID, tempData);
lv.setAdapter(tempAdapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(contentView);
final AlertDialog alert = builder.create();
alert.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if (position == 0){ //Edit Data
passStringValue();
updateList();
Intent intent = new Intent(getActivity(),A_BonRokok_Item_View.class);
intent.putExtra("status", true);
startActivity(intent);
getActivity().finish();
}
else if (position == 1){ //Delete Data
final int item_id = cursor.getInt(cursor.getColumnIndex(database.KEY_ID));
mySQLiteAdapter.delete_byID(item_id);
updateList();
alert.cancel();
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
}
public void passStringValue(){
final String nama_Rokok = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
final String kode_Rokok = "102030";
final String pita_Cukai = cursor.getString(cursor.getColumnIndex(database.SPITACUKAI));
final String jumlah = cursor.getString(cursor.getColumnIndex(database.SJUMLAH));
view.Detail(nama_Rokok, kode_Rokok, pita_Cukai, jumlah);
}
}
and the second --> i have activity that contain an edittext.
here the code
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(contentView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
});
// txtSelop.setOnFocusChangeListener(focusSelopChange);
// txtBungkus.setOnFocusChangeListener(focusBungkusChange);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_save) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
} else {
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_print, menu);
MenuItem item = menu.findItem(R.id.edit_print);
item.setVisible(false);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
OnClickListener searchClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
createDialogSearch();
}
};
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> hm = (HashMap<String, String>)arg0.getAdapter().getItem(position);
autoCompleteBonRokok.setText(hm.get("kdRokok"));
txtNamaRokok.setText(hm.get("namaRokok"));
}
};
public void onBackPressed(){
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
OnFocusChangeListener focusBalChange = new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean isFocused) {
if(!isFocused){
if(txtBal.length()==0)
bal = 0;
else
bal = Integer.parseInt(txtBal.getText().toString());
splitValue();
}
}
};
public void saveToDatabase() {
}
private void updateList() {
cursor.requery();
}
public void createDialogSearch(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout)li.inflate(R.layout.d_bon_rokok_search_new_item, null);
DialogDummyAutoComplete[] modelItemsDialog;
final ListView lvDialog = (ListView)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_lvSearch);
modelItemsDialog = new DialogDummyAutoComplete[3];
modelItemsDialog [0] = new DialogDummyAutoComplete("1051200", "Supra need 12");
modelItemsDialog [1] = new DialogDummyAutoComplete("1051600", "Supra need 16");
modelItemsDialog [2] = new DialogDummyAutoComplete("1001200", "NY");
DialogAutoCompleteSearchRokok dialogAdapter = new DialogAutoCompleteSearchRokok(this, modelItemsDialog);
lvDialog.setAdapter(dialogAdapter);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.getWindow().getAttributes().height = LayoutParams.WRAP_CONTENT;
alert.show();
btnCancel = (Button)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
String selectedKdRokok = ((TextView)arg1.findViewById(R.id.kdRokok_dialog)).getText().toString();
String selectedNamaRokok = ((TextView)arg1.findViewById(R.id.namaRokok_dialog)).getText().toString();
autoCompleteBonRokok.setText(selectedKdRokok);
txtNamaRokok.setText(selectedNamaRokok);
alert.cancel();
}
});
}
public void splitValue(){
if (txtJumlah.length()==0)
txtJumlah.setText("0,000");
separated = txtJumlah.getText().toString().split(",");
first = separated[0];
second = separated[1];
first = Integer.toString(bal);
txtJumlah.setText(first + "," + second);
txtJumlah.clearFocus();
}
public void createDialogConfirm(){
LayoutInflater li = LayoutInflater.from(this);
LinearLayout someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
Button btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
Button btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.show();
}
}
My question is
how can i pass a value from second activity (contain edittext) to fragment in view pager, because everytime i try to insert using many way, java lang null pointer always become my nightmare...
please help me... thx you so much
Intent.putExtra("YourValueKey", datatobepassed);
on the other activity
Bundle extras = getIntent().getExtras();
if ( extras != null ){
extras.get("YourValueKey")
}
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());