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
Related
Listview is setting the filename only in first position. Even though on clicking any positions of the listview it sets the filename for the first position only. Please let me know what changes i need to make so that filename will be set properly on clicked item only instead of first item always. Thanks in advance.
I have done same with in Recycle view I am sharing my project code with you
package com.deepak.myapplication;
public class DocumentActivity extends AppCompatActivity implements
View.OnClickListener {
ImageView toolbar_back;
TextView next, tvDocName;
RecyclerView listView;
ArrayList<Survey_vehiclepojo> mylist = new ArrayList();
My_document_adapter adapter;
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar_back = ( ImageView ) findViewById(R.id.toolbar_back);
//toolbar_back.setOnClickListener(this);
//next = ( TextView ) findViewById(R.id.next);
//next.setOnClickListener(this);
listView = findViewById(R.id.recycleView);
mylist.add(new Survey_vehiclepojo("Pay Slip", "file1"));
mylist.add(new Survey_vehiclepojo("Insurance", "file2"));
mylist.add(new Survey_vehiclepojo("NA Certificate", "file3"));
mylist.add(new Survey_vehiclepojo("NA 1", "file3"));
mylist.add(new Survey_vehiclepojo("NA 2", "file3"));
mylist.add(new Survey_vehiclepojo("NA 3", "file3"));
listView.setLayoutManager(new LinearLayoutManager(this));
adapter = new My_document_adapter(mylist, DocumentActivity.this);
listView.setAdapter(adapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*case R.id.toolbar_back:
finish();
break;
case R.id.next:
Intent n=new Intent(DocumentActivity.this, Loan_checklistActivity.class);
startActivity(n);
break;
}*/
}
}
public void Document(int pos) {
position = pos;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
selectedFile(data, requestCode);
}
private void selectedFile(Intent data, int position) {
String displayName = null;
if (data != null) {
Uri uri = data.getData();
String uriString = null;
if (uri != null) {
uriString = uri.toString();
}
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString != null) {
if (uriString.startsWith("content://")) {
try (Cursor cursor = DocumentActivity.this.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
}
This is Adapter
class My_document_adapter extends
RecyclerView.Adapter<My_document_adapter.ViewHolder>{
ArrayList<Survey_vehiclepojo> mylist;
DocumentActivity documentActivity;
public My_document_adapter(ArrayList<Survey_vehiclepojo> mylist,
DocumentActivity documentActivity) {
this.mylist = mylist;
this.documentActivity = documentActivity;
}
#NonNull
#Override
public My_document_adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new My_document_adapter.ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull My_document_adapter.ViewHolder holder,
final int position) {
holder.name.setText("name"+position);
holder.ivDocument.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Log.d("**Postion", "Postion: "+position);
documentActivity.Document(position);
} });
}
#Override
public int getItemCount() {
return mylist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final TextView tvDocName,name;
ImageView ivDocument;
public ViewHolder(#NonNull View view) {
super(view);
name = view.findViewById(R.id.tvName);
tvDocName = view.findViewById(R.id.tvDocName);
ivDocument = view.findViewById(R.id.ivDocument);
}
}
}
and my file is selecting see this screenshot
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.
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.
Problem - I have list of in app purchases loaded from app store in a Listview.
When user purchases (taps on a button in listview) the item is purchased and the button should be now hidden and the list item purchased should show an image of tick.
What I have tried -
Refresh the listview after item is purchased by calling notifyDataSetChanged
Set the visibility of the button and image using View.GONE and View.VISIBLE
None of the above seems to work.
I am using this in app billing library
public class ListViewAdapter extends ArrayAdapter<Product> {
private ArrayList<Product> iapProducts= new ArrayList<>();
private final LayoutInflater inflater;
private final Activity activity;
public ArrayList<Product> getIapProducts() {
return iapProducts;
}
public void setIapProducts(ArrayList<Product> iapProducts) {
this.iapProducts = iapProducts;
}
public ListViewAdapter(final Activity context) {
super(context, 0);
inflater = LayoutInflater.from(context);
this.activity = context;
}
#Override
public int getCount() {
return this.iapProducts.size();
}
public String getItem(String position) {
return position;
}
#Override
public boolean hasStableIds(){
return true;
}
public void addAll(ArrayList<Product> iapProducts){
this.iapProducts.addAll(iapProducts);
notifyDataSetChanged();
}
public static class ViewHolder {
public TextView name;
public ImageView imageView;
public Button purchaseButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.names_filter_row, null);
holder = new ViewHolder();
holder.name = (TextView) vi.findViewById(R.id.languageName);
holder.imageView = (ImageView) vi.findViewById(R.id.imgTick);
holder.purchaseButton = (Button) vi.findViewById(R.id.iapProductPurchaseBtn);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
final Product product = iapProducts.get(position);
holder.name.setText(product.getTitle());
holder.purchaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemPurchased(v);
}
});
holder.iapProductId.setText(product.getProductId());
holder.purchaseButton.setText(product.getPriceText());
holder.imageView.setVisibility(View.GONE);
if(product.isPurchased()){
holder.purchaseButton.setVisibility(View.GONE);
holder.imageView.setVisibility(View.VISIBLE);
}else{
holder.purchaseButton.setVisibility(View.VISIBLE);
holder.imageView.setVisibility(View.GONE);
}
return vi;
}
private void onItemPurchased(View v){
final RelativeLayout parentLayout = (RelativeLayout)v.getParent();
final TextView productId = (TextView)parentLayout.findViewById(R.id.iapProductId);
final ImageView languageCheck = (ImageView)parentLayout.findViewById(R.id.imgTick);
PurchaseActivity purchaseActivity = (PurchaseActivity) this.activity;
purchaseActivity.purchaseItem(productId.getText().toString(), v);
}
}
public class PurchaseActivity extends AppCompatActivity implements BillingProcessor.IBillingHandler {
private BillingProcessor bp;
boolean isOneTimePurchaseSupported;
private ArrayList<Product> productsToPurchase = new ArrayList<>();
private final static String TAG = PurchaseActivity.class.getName();
private ListViewAdapter adapter;
private ImageView imageTick;
private Button buttonPurchase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
bp = BillingProcessor.newBillingProcessor(this, "billingKey", this); // doesn't bind
bp.initialize(); // binds
adapter = new ListViewAdapter(this);
nameFilterListView.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onBillingInitialized() {
isOneTimePurchaseSupported = bp.isOneTimePurchaseSupported();
if(isOneTimePurchaseSupported){
loadIAPData(false);
}else{
Toast.makeText(this,"Billing not supported",Toast.LENGTH_LONG).show();
}
}
private void loadIAPData(boolean showProgressDialog){
bp.loadOwnedPurchasesFromGoogle();
final List<SkuDetails> productDetails = bp.getPurchaseListingDetails(productList);
if(productDetails!= null && !productDetails.isEmpty()){
//fetch products and add to the list
productsToPurchase.add(product);
}
//add all the products to adapter
adapter.addAll(productsToPurchase);
}
}
public void purchaseItem(#NonNull final String productId, final View imageTick, final View button){
this.imageTick = (ImageView) imageTick;
this.buttonPurchase = (Button) button;
bp.purchase(this,productId);
}
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
//hide button show image
this.imageTick.setVisibility(View.VISIBLE);
this.buttonPurchase.setVisibility(View.GONE);
adapter.setIapProducts(new ArrayList<>(productsToPurchase));
adapter.notifyDataSetChanged();
}
}
(Moved comment into a post)
After a user purchases something, is that Product within productsToPurchase updated? The adapter looks okie so maybe the list you're using isn't being updated after a purchase.
I'm assuming you need to flip the isPurchased flag of the Product in onProductPurchased() using the provided productId.
I have a list view populated threw an SQlitedatabase but I need to pass to a detail activity from the list view. The problem is in passing the details from the listview activity to the detail activity because when I click the detail activity it gives me blank edit texts
Here is my listview activity:
public class consulter_note extends Activity implements AdapterView.OnItemClickListener{
ListView list;
SQLiteDatabase sqLiteDatabase;
DataBaseOperationstwo dataBaseOperationstwo;
Cursor cursor;
ListDataAdapter listDataAdapter;
String titre,objet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulter_note);
list = (ListView) findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.notelist_row);
list.setAdapter(listDataAdapter);
list.setOnItemClickListener(this);
dataBaseOperationstwo = new DataBaseOperationstwo(getApplicationContext());
sqLiteDatabase = dataBaseOperationstwo.getReadableDatabase();
cursor = dataBaseOperationstwo.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do
{
titre = cursor.getString(0);
objet = cursor.getString(1);
DataProvider dataProvider = new DataProvider(titre,objet);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, note_details.class);
startActivity(intent);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
}
}
And here is my array adapter:
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView TITRE,OBJET;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.notelist_row,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.TITRE = (TextView) row.findViewById(R.id.titredemo);
layoutHandler.OBJET = (TextView) row.findViewById(R.id.objetdemo);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.TITRE.setText(dataProvider.getTitre());
layoutHandler.OBJET.setText(dataProvider.getObjet());
return row;
}
}
The data provider class used in the array adapter:
public class DataProvider {
private String titre,objet;
public DataProvider(String titre,String objet)
{
this.titre = titre;
this.objet = objet;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
}
And finally my details activity. I'm only interested in the intent part; the rest has nothing to do with my problem:
public class note_details extends Activity {
ImageButton Del;
EditText PASSTITRE,USEROBJET;
String Passtitre,Userobjet;
DataBaseOperationstwo DOP;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =getIntent();
if(intent != null)
{
String objet = intent.getStringExtra("objet");
String titre= intent.getStringExtra("titre");
PASSTITRE.setText(objet);
USEROBJET.setText(objet);
}
setContentView(R.layout.activity_note_details);
Del = (ImageButton) findViewById(R.id.suppnote);
PASSTITRE = (EditText) findViewById(R.id.titree);
USEROBJET = (EditText) findViewById(R.id.objett);
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passtitre = PASSTITRE.getText().toString();
Userobjet = USEROBJET.getText().toString();
DOP = new DataBaseOperationstwo(CTX);
DOP.deleteNote(DOP,Passtitre,Userobjet);
Toast.makeText(getBaseContext(),"note supprimé",Toast.LENGTH_LONG).show();
finish();
}
});
}
public void liste(View v)
{
Intent i = new Intent(this, consulter_note.class);
startActivity(i);
}
public void supprimer(View v)
{
}
}
My logcat doesn’t show any errors but the details activity shows with empty edittexts.
You should first add extras to the Intent and then fire it:
Intent intent = new Intent(this, note_details.class);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
startActivity(intent);
Another thing worth mentioning is that you should avoid doing DB queries on the main thread, as it will slow down your app. Use Loaders, or just run queries on worker threads.