How to add an Image URI to Listview - android

I have created a student information app that will ask the user for their picture, lastname, firstname and their course. I already have the code to let the user upload their picture.
I want to get the image that I have uploaded and add it to my listview. Thanks
Here is my code:
AddStudentActivity.java
ListView listView;
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);
listView = (ListView) findViewById(R.id.listview);
cboCourse.setOnItemSelectedListener(this);
studentImage.setOnClickListener(this);
btnSave.setOnClickListener(this);
btnCancel.setOnClickListener(this);
studentAdapter = new StudentAdapter(this, studentArrayList);
}
#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());
listView.setAdapter(studentAdapter);
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("");
cboCourse.setSelection(0);
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) {
}
MainActivity.java
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;
}
Student.java
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;
}

There are lots of library like Fresco, Glide etc that helps you to load images in list view. BTW why you are using listview now? I should say you need to use Recyclerview instead of LV.
Is there any particular reason to use Serializable? you can use android provided Percelable which is much more relevant.

Related

Why is my Listview not showing anything on my activity?

I have created a custom list and then put some data and inflate it into my listview but it is not showing. Can you please tell me what am I missing on my code? It doesn't show any errors related to this problem on my logcat.
What I wanted to happen is when the user enter all the details from AddStudentActivity, all the data will be shown in another activity which is in the MainActivity.
I am using intent on this one. Thanks for any help.
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<Student> studentArrayList = new ArrayList<>();
CustomAdapter adapter;
private Uri imageUri;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
adapter = new CustomAdapter(this, studentArrayList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
//for menu
#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);
}
//inflate the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.addmenu, menu);
return super.onCreateOptionsMenu(menu);
}
//handles the onclick listener for the listview
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
Bundle b = data.getExtras();
imageUri = b.getParcelable("image");
String lastname = b.getString("lastname");
String firstname = b.getString("firstname");
String course = b.getString("course");
Student student = new Student(imageUri, lastname, firstname, course);
studentArrayList.add(student);
adapter.notifyDataSetChanged();
}else{
}
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#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.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
AddStudentActivity.java
public class AddStudentActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
ListView lv;
ImageView studImage;
Uri studImageUri;
EditText lastname, firstname;
String selectedCourse;
Spinner course;
Button btnsave, btncancel;
CustomAdapter adapter;
private static final int PICK_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student);
//
studImage = (ImageView) findViewById(R.id.addstudentimage);
lastname = (EditText) findViewById(R.id.editTextLastname);
firstname = (EditText) findViewById(R.id.editTextFirstname);
course = (Spinner) findViewById(R.id.spinnerCourse);
btnsave = (Button) findViewById(R.id.btn_save);
btncancel = (Button) findViewById(R.id.btn_cancel);
studImage.setOnClickListener(this);
btnsave.setOnClickListener(this);
btncancel.setOnClickListener(this);
course.setOnItemSelectedListener(this);
}
//on click listeners for the buttons and imageview
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.addstudentimage:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
break;
case R.id.btn_save:
String lname = lastname.getText().toString();
String fname = firstname.getText().toString();
String newCourse = course.getSelectedItem().toString();
if(!studImage.equals(R.drawable.user) && !lastname.equals(" ") && !firstname.equals("") && !course.getSelectedItem().toString().trim().equals(0)){
Intent intent = new Intent();
intent.putExtra("image", this.studImageUri);
intent.putExtra("lastname", lname);
intent.putExtra("firstname", fname);
intent.putExtra("course", newCourse);
this.setResult(Activity.RESULT_OK, intent);
Toast.makeText(getApplicationContext(), "New student successfully added!", Toast.LENGTH_SHORT).show();
finish();
}else{
Toast.makeText(getApplicationContext(), "Error in adding a new student!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
studImage.setImageResource(R.drawable.user);
lastname.setText("");
firstname.setText("");
course.setSelection(0);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != 0){
if(data != null){
studImageUri = data.getData();
studImage.setImageURI(studImageUri);
}
}else {
}
}
//on click listeners for the spinners
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int sid = parent.getId();
switch (sid){
case R.id.spinnerCourse:
selectedCourse = this.course.getItemAtPosition(position).toString();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
You used the wrong syntax, replace startActivity -> startActivityForResult
refer : https://developer.android.com/training/basics/intents/result

How to add items to a Listview without using a database?

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.

how to add display images and sort from newest uploaded

I have fork from github this source code
https://github.com/quocnguyenvan/food-sqlite-demo
I need some help here
How to add display image in full screen? If we are in food list and click an image, the image will show at full screen
And one more, how to add sorting file? So the newest uploaded will be at the top of the list, thanks for helping me, i need this for my office
======================================================
here is my code
FoodList class
public class FoodList extends AppCompatActivity {
GridView gridView;
ArrayList<Food> list;
FoodListAdapter adapter = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_list_activity);
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new FoodListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Preview", "Download"};
AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent i = new Intent(getApplicationContext(), ImageDisplay.class);
i.putExtra("id", position);
startActivity(i);
Toast.makeText(getApplicationContext(),"You click on " + position, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"you download " + position, Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
//return true;
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
// update
Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
// show dialog update at here
showDialogUpdate(FoodList.this, arrID.get(position));
} else {
// delete
Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
showDialogDelete(arrID.get(position));
}
}
});
dialog.show();
return true;
}
});
}
ImageView imageViewFood;
private void showDialogUpdate(Activity activity, final int position){
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.update_food_activity);
dialog.setTitle("Update");
imageViewFood = (ImageView) dialog.findViewById(R.id.imageViewFood);
final EditText edtName = (EditText) dialog.findViewById(R.id.edtName);
final EditText edtPrice = (EditText) dialog.findViewById(R.id.edtPrice);
Button btnUpdate = (Button) dialog.findViewById(R.id.btnUpdate);
// set width for dialog
int width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.95);
// set height for dialog
int height = (int) (activity.getResources().getDisplayMetrics().heightPixels * 0.7);
dialog.getWindow().setLayout(width, height);
dialog.show();
imageViewFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// request photo library
ActivityCompat.requestPermissions(
FoodList.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
888
);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MainActivity.sqLiteHelper.updateData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
MainActivity.imageViewToByte(imageViewFood),
position
);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Update successfully!!!",Toast.LENGTH_SHORT).show();
}
catch (Exception error) {
Log.e("Update error", error.getMessage());
}
updateFoodList();
}
});
}
private void showDialogDelete(final int idFood){
final AlertDialog.Builder dialogDelete = new AlertDialog.Builder(FoodList.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you want to this delete?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
MainActivity.sqLiteHelper.deleteData(idFood);
Toast.makeText(getApplicationContext(), "Delete successfully!!!",Toast.LENGTH_SHORT).show();
} catch (Exception e){
Log.e("error", e.getMessage());
}
updateFoodList();
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialogDelete.show();
}
private void updateFoodList(){
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 888){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 888);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 888 && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageViewFood.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
i want to display image in fullscreen when user click on it
here is my DisplayImage class
public class ImageDisplay extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageView imageViewFood = (ImageView) findViewById(R.id.fullimage);
imageViewFood.setImageResource(position);
}
}
is it correct code ? please help me, thanks

Android pass selected item in listview to popupMenu

I would like to pass the selected item "id" from listview to popupMenu , the mainActivity:
public class ListChildrenActivity extends AppCompatActivity implements Config, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "ListChildrenActivity";
ProgressDialog progressDialog;
Toolbar toolbar;
ChildrenAdapter adapter;
ListView listView;
int idConnexion, id;
private SwipeRefreshLayout refreshLayout;
Intent intent;
Child childObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_child);
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Listes des enfants");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), MainMedecinActivity.class);
startActivity(intent);
}
});
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
showChildren();
}
});
showChildren();
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View view, int itemInt, long lng) {
//String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
//Toast.makeText(ListChildrenActivity.this, selectedFromList, Toast.LENGTH_SHORT).show();
//TextView v = (TextView)view.findViewById(R.id.tv);
//String itemId = v.getText().toString();
childObj = (Child) listView.getItemAtPosition(itemInt);
id = childObj.getIdEnfant();
Toast.makeText(ListChildrenActivity.this, ""+id, Toast.LENGTH_SHORT).show();
}
});
}
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
}
private ArrayList<Child> generateData(String content) {
ArrayList<Child> children = new ArrayList<Child>();
JSONObject jObj = null;
JSONArray ja = null;
try {
ja = new JSONArray(content);
for (int i = 0; i < ja.length(); i++) {
jObj = ja.getJSONObject(i);
children.add(new Child(jObj.getInt("idEnfant"), jObj.getString("nomEnfant"), jObj.getString("prenomEnfant")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return children;
}
public void showChildren() {
if (!validate()) {
failed();
return;
}
SharedPreferences prefs = getSharedPreferences("Info_Connexion", Context.MODE_PRIVATE);
idConnexion = prefs.getInt("idConnexion", 0);
progressDialog = new ProgressDialog(ListChildrenActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("La liste des enfants ...");
progressDialog.show();
if (isOnline()) {
requestData(SERVER_URL + "enfant/read/", idConnexion);
} else {
Toast.makeText(ListChildrenActivity.this, "Eroor network", Toast.LENGTH_SHORT).show();
}
}
private void requestData(String url, int id) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
RequestPackage p = new RequestPackage();
p.setMethod("POST");
p.setUri(url);
p.setParam("idMedecin", String.valueOf(id));
MessagesTask task = new MessagesTask();
task.execute(p);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public void success(final int id, final ProgressDialog progressDialog, String content, SwipeRefreshLayout refreshLayout) {
// 1. pass context and data to the custom adapter
adapter = new ChildrenAdapter(this, generateData(content));
// 2. Get ListView from activity_main.xml
// 3. setListAdapter
listView.setAdapter(adapter);
if (id != 0) {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
} else {
refreshLayout.setRefreshing(false);
progressDialog.dismiss();
Toast.makeText(ListChildrenActivity.this, "Eroor server or input", Toast.LENGTH_SHORT).show();
}
}
public boolean validate() {
boolean valid = true;
return valid;
}
public void failed() {
Toast.makeText(getBaseContext(), "List Children failed", Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
TextView scoreView = (TextView) findViewById(R.id.score);
switch (item.getItemId()) {
case R.id.infos:
intent = new Intent(getBaseContext(), ChildInformationsActivity.class);
intent.putExtra("idEnfant", id );
startActivity(intent);
return true;
case R.id.signes_diagnostic:
intent = new Intent(getBaseContext(), ChildSignesDiagnosticActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.bilan_bio:
intent = new Intent(getBaseContext(), ChildBilanBioActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.traitement_medical:
intent = new Intent(getBaseContext(), ChildTraitementMedicalActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
case R.id.imagerie:
intent = new Intent(getBaseContext(), ChildImagerieActivity.class);
intent.putExtra("idEnfant", id);
startActivity(intent);
return true;
default:
return false;
}
}
private class MessagesTask extends AsyncTask<RequestPackage, String, String> {
#Override
protected String doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
#Override
protected void onPostExecute(String content) {
Log.i(TAG, "------------------------" + content);
success(idConnexion, progressDialog, content, refreshLayout);
}
}
}
enter image description here
class adapter:
public class ChildrenAdapter extends ArrayAdapter<Child> {
private final Context context;
private final ArrayList<Child> childrenArrayList;
public ChildrenAdapter(Context context, ArrayList<Child> childrenArrayList) {
super(context, R.layout.row_child, childrenArrayList);
this.context = context;
this.childrenArrayList = childrenArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowChildView = inflater.inflate(R.layout.row_child, parent, false);
// 3. Get the two text view from the rowView
TextView nameView = (TextView) rowChildView.findViewById(R.id.name);
TextView dateView = (TextView) rowChildView.findViewById(R.id.date);
TextView scoreView = (TextView) rowChildView.findViewById(R.id.score);
// 4. Set the text for textView
//String text = childrenArrayList.get(position).getNomEnfant())+" "+childrenArrayList.get(position).getNomEnfant();
nameView.setText(childrenArrayList.get(position).getNomEnfant()+" "+childrenArrayList.get(position).getPrenomEnfant());
dateView.setText("22/12/2012");
scoreView.setText(String.valueOf(childrenArrayList.get(position).getIdEnfant()));
scoreView.setBackgroundResource(R.drawable.circular_textview);
// 5. retrn rowView
return rowChildView;
}
}
Whene i click to the row of listview i get the "id" but how i can pass it to the popupMenu.
The solution: it just add settag(position) to imageview in getview, then :
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.poupup_menu);
popup.show();
listView.performItemClick(v, (Integer) v.getTag(),listView.getItemIdAtPosition((Integer) v.getTag()));
}
You can use interface to communicate between them
In your adapter class, initialize
private OnItemSelectedListener mListener;
and add these methods
public void setOnItemClickLister(OnItemSelectedListener mListener) {
this.mListener = mListener;
}
//Creating an interface
public interface OnItemSelectedListener {
public void onItemSelected(String s);
}
in onClick function in adapter
use this
mListener.onItemSelected(id);
//id is your string
you can call it in MainActivity,
adapter.setOnItemClickLister(new OnItemSelectedListener() {
#Override
public void onItemSelected(String s) {
//you will get the string here, you can pass it as an argument in popup menu
}
});
On the adapter Side:
view.findViewById(R.id.menu_btn).setTag(id);
On the ListActivity Side:
public void showPopUp(View v){
currentId = v.getTag().toString();
PopupMenu popupMenu=new PopupMenu(this,v);
popupMenu.setOnMenuItemClickListener(ListActivity.this);
MenuInflater inflater=popupMenu.getMenuInflater();
inflater.inflate(R.menu.my_pop_up,popupMenu.getMenu());
popupMenu.show();
}
On XML side:
<ImageButton android:id="#+id/menu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_overflow"
android:layout_marginStart="10dp"
android:layout_marginEnd="20dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:onClick="showPopUp"/>
Note: onClick="showPopUp" is very critical here.
This should be helpful. Thank you.

pass data from fragment inside view pager to another activity

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")
}

Categories

Resources