Listview is setting text only for first position - android

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

Related

How to update a textview of adapter in an activity

I have a textview in my adapter class and I have to update the textview in activity since I am getting the result in activity. How can i do that?
This is my activity class. I want to update textview tv2 with "some text". I have even tried updating textview in adapter but I wasn't successful in doing that.
public class TextviewActivity extends AppCompatActivity {
ListView lvText;
ArrayList<TextviewPojo> textviewPojos = new ArrayList<>();
TextviewAdapter textviewAdapter;
TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_textview);
lvText = findViewById(R.id.lvText);
textviewAdapter = new TextviewAdapter(textviewPojos,this);
lvText.setAdapter(textviewAdapter);
textviewPojos.add(new TextviewPojo("first text","second text"));
textviewPojos.add(new TextviewPojo("first text","second text"));
}
}
This is my adapter class.
public class TextviewAdapter extends BaseAdapter {
ArrayList<TextviewPojo> textviewPojos = new ArrayList<>();
Context context;
public TextviewAdapter(ArrayList<TextviewPojo> textviewPojos, Context context) {
this.textviewPojos = textviewPojos;
this.context = context;
}
#Override
public int getCount() {
return textviewPojos.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.item_textview,parent,false);
}
TextView tv1,tv2;
TextviewPojo textviewPojo = textviewPojos.get(position);
tv1 = convertView.findViewById(R.id.tv1);
tv2 = convertView.findViewById(R.id.tv2);
tv1.setText(textviewPojo.getText1());
tv2.setText(textviewPojo.getText2());
return convertView;
}
}
Below is my item layout. - item_textview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv1"
android:textSize="30sp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="filename1"/>
<TextView
android:id="#+id/tv2"
android:layout_weight="1"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="filename2"/>
</LinearLayout>
Try this code do not need to take reference of tvDocName again in selected file just change this code in selected file
public class DocumentActivity extends AppCompatActivity {
ImageView toolbar_back;
TextView next;
RecyclerView recyclerView;
ArrayList<Survey_vehiclepojo> mylist = new ArrayList();
My_document_adapter adapter;
TextView tvDocName;
View view;
private int position;
String displayName = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_document);
view = getLayoutInflater().inflate(R.layout.activity_document, null);
tvDocName = findViewById(R.id.tvDocName);
// toolbar_back=(ImageView)findViewById(R.id.toolbar_back);
// toolbar_back.setOnClickListener(this);
// next=(TextView)findViewById(R.id.next);
// next.setOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
mylist.add(new Survey_vehiclepojo("Pay Slip"));
mylist.add(new Survey_vehiclepojo("Insurance"));
mylist.add(new Survey_vehiclepojo("NA Certificate"));
adapter = new My_document_adapter(DocumentActivity.this, mylist);
recyclerView.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, 100);
tvDocName.setText(mylist.get(pos).getPay_slip());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
selectedFile(data);
}
private void selectedFile(Intent data) {
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));
Toast.makeText(this, "display" + displayName, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "path is" +path, Toast.LENGTH_SHORT).show();
// My_document_adapter.Filename(displayName, position);
// ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_document, null);
// tvDocName = v.findViewById(R.id.tvDocName);
tvDocName.setText(displayName);
adapter.notifyDataSetChanged();
}
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
Toast.makeText(this, "display start " + displayName, Toast.LENGTH_SHORT).show();
// ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_document, null);
// tvDocName = v.findViewById(R.id.tvDocName);
tvDocName.setText(displayName);
adapter.notifyDataSetChanged();
}
}
}
}
in your adapter class change this line
View v = LayoutInflater.from(context).inflate(R.layout.item_document, viewGroup, false);
call this where you update you list trough your adpater
public void refresh(ArrayList<TextviewPojos> textviewPojos){
this.textviewPojo=textviewPojos;
notifyDataSetChanged();
}

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.

Android Gallery Display two item

Hello I made android gallery . I added capture image camera or gallery but I show only one image in display How can show two gallery item in gallery For example that is
here is my gallery code xml
<Gallery
android:id="#+id/main_list_view"
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_alignLeft="#+id/btnAdd"
android:layout_below="#+id/btnAdd"
android:layout_marginTop="28dp"
android:cacheColorHint="#color/deepPurple1"/>
And My MainActivity
#SuppressLint("NewApi")
public class MainActivity extends Activity {
private ArrayList<MyImage> images;
private ImageAdapter imageAdapter;
private Gallery listView;
private Uri mCapturedImageURI;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private Handler handler;
Dialog dialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Alert Dialog View");
// Construct the data source
images = new ArrayList<MyImage>();
// Create the adapter to convert the array to views
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setAdapter(imageAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnChoosePath)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeTakePhoto();
}
});
// show dialog on screen
dialog.show();
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
imageAdapter.remove(images.remove(position));
return false;
}
});
}
public void btnAddOnClick(View view) {
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Alert Dialog View");
Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnChoosePath)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeTakePhoto();
}
});
// show dialog on screen
dialog.show();
}
/**
* take a photo
*/
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
MyImage image = new MyImage();
image.setTitle("Test");
image.setDescription(" add list view");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setSpacing(-20);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
managedQuery(mCapturedImageURI, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
MyImage image = new MyImage();
image.setTitle("Test");
image.setDescription("list view");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setSpacing(-20);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
}
}
And My Adapter
public class ImageAdapter extends ArrayAdapter<MyImage>{
/**
* applying ViewHolder pattern to speed up ListView, smoother and faster
* item loading by caching view in A ViewHolder object
*/
private static class ViewHolder {
ImageView imgIcon;
TextView description;
}
public ImageAdapter(Context context, ArrayList<MyImage> images) {
super(context, 0, images);
}
#Override public View getView(int position, View convertView,
ViewGroup parent) {
// view lookup cache stored in tag
ViewHolder viewHolder;
// Check if an existing view is being reused, otherwise inflate the
// item view
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_image, parent, false);
/*
viewHolder.description =
(TextView) convertView.findViewById(R.id.item_img_infor);
*/
viewHolder.imgIcon =
(ImageView) convertView.findViewById(R.id.item_img_icon);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Get the data item for this position
MyImage image = getItem(position);
// set description text
// viewHolder.description.setText(image.toString());
// set image icon
final int THUMBSIZE = 100;
// viewHolder.imgIcon.setImageURI(Uri.fromFile(new File(image
// .getPath())));
viewHolder.imgIcon.setImageBitmap(ThumbnailUtils
.extractThumbnail(BitmapFactory.decodeFile(image.getPath()),
THUMBSIZE, THUMBSIZE));
viewHolder.imgIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
viewHolder.imgIcon.setBackgroundResource(R.drawable.ios_retina_toggle_frame);
// Return the completed view to render on screen
return convertView;
}
}
And My image Class
public class MyImage {
private String title, description, path;
private Calendar datetime;
private long datetimeLong;
protected SimpleDateFormat df = new SimpleDateFormat("MMMM d, yy h:mm");
public String getTitle() { return title; }
public Calendar getDatetime() { return datetime; }
public void setDatetime(long datetimeLong) {
this.datetimeLong = datetimeLong;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(datetimeLong);
this.datetime = cal;
}
public void setDatetime(Calendar datetime) { this.datetime = datetime; }
public String getDescription() { return description; }
public void setTitle(String title) { this.title = title; }
public long getDatetimeLong() { return datetimeLong; }
public void setDescription(String description) {
this.description = description;
}
public void setPath(String path) { this.path = path; }
public String getPath() { return path; }
#Override public String toString() {
return "Title:" + title + " " + df.format(datetime.getTime()) +
"\nDescription:" + description + "\nPath:" + path;
}
}

Load image From basic gallery To imageview in Custom Listview/

First, I'm sorry for my bad English. please excuse me. :)..
I tried to make a custom listView which has ImageView, TextViews, and Button.
So, I want to change image after I click ImageView in listview and select image from gallery. But.. It's really hard to me.
In my code(customAdapter)Adapter class is not Activity, So it cannot call startActivityForResult directly. So I make new Activity(It is GalleryImage.java). and call startActivity using that class. But it is not working. What should I do...
(Error occur in ImageView.setOnClickListner, getView of PhoneBookAdapter)
CustomAdapter Source Code
//..skip import
public class PhoneBookAdapter extends BaseAdapter implements Filterable {
ArrayList<Contact> m_people = new ArrayList<Contact>();
ArrayList<Contact> m_filteredPeople = new ArrayList<Contact>();
private ItemFilter mFilter = new ItemFilter();
private class CustomHolder {
ImageView m_photo;
TextView m_name, m_phone;
Button m_call, m_reserve;
}
public PhoneBookAdapter(ArrayList<Contact> people) {
m_people = people;
m_filteredPeople = people;
}
#Override
public int getCount() {
return m_filteredPeople.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// final int pos = position;
final Context context = parent.getContext();
final TextView phone;
final ImageView photo;
TextView name;
Button call, reserve;
final int pos = position;
CustomHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.phonebook_list_item, parent,
false);
photo = (ImageView) convertView.findViewById(R.id.iv_photo);
name = (TextView) convertView.findViewById(R.id.tv_name);
phone = (TextView) convertView.findViewById(R.id.tv_phonenumber);
call = (Button) convertView.findViewById(R.id.btn_call);
reserve = (Button) convertView.findViewById(R.id.btn_reserve);
holder = new CustomHolder();
holder.m_photo = photo;
holder.m_name = name;
holder.m_phone = phone;
holder.m_call = call;
holder.m_reserve = reserve;
convertView.setTag(holder);
} else {
holder = (CustomHolder) convertView.getTag();
photo = holder.m_photo;
name = holder.m_name;
phone = holder.m_phone;
call = holder.m_call;
reserve = holder.m_reserve;
}
//photo.setImageResource(m_filteredPeople.get(position).getImage());
name.setText(m_filteredPeople.get(position).getName());
phone.setText(m_filteredPeople.get(position).getNumber());
photo.setOnClickListener(new OnClickListener() {
Activity activity;
int SELECT_IMAGE=90;
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryImage gallery = new GalleryImage(SELECT_IMAGE, photo);
gallery.startActivityForResult(intent, SELECT_IMAGE);
}
});
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO make real phone call
Toast.makeText(context, "call " + phone.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse("tel:" + m_filteredPeople.get(pos).getNumber()));
context.startActivity(intent);
}
});
reserve.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "reserve " + phone.getText(),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString();
FilterResults results = new FilterResults();
final ArrayList<Contact> m_IFpeople = m_people;
int count = m_IFpeople.size();
final ArrayList<Contact> n_people = new ArrayList<Contact>();
String filterableString;
if (filterString != null
&& filterString.trim().equalsIgnoreCase("") != true) {
// Whitespace와 null 제거
// for (int i = 0; i < count; i++) {
// filterableString = m_IFpeople.get(i).getName();
// if (filterableString.indexOf(filterString) >= 0) {
// n_people.add(m_IFpeople.get(i));
// }
// }
for (int i = 0; i < count; i++) {
filterableString = HangulUtils.getHangulInitialSound(
m_IFpeople.get(i).getName(), filterString);
if (filterableString.indexOf(filterString) >= 0) {
n_people.add(m_IFpeople.get(i));
}
}
results.values = n_people;
results.count = n_people.size();
} else {
results.values = m_IFpeople;
results.count = m_IFpeople.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
m_filteredPeople = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
GalleryImage.java(new Activity)
//..skip import
public class GalleryImage extends Activity {
final int REQ_CODE_SELECT_IMAGE;
ImageView photo;
public GalleryImage(int codeImage, ImageView m_photo) {
REQ_CODE_SELECT_IMAGE = codeImage;
photo = m_photo;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Intent intent = new Intent(Intent.ACTION_PICK);
// intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
// intent.setData(
// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK
&& data != null) {
final Uri selectImageUri = data.getData();
final String[] filePathColumn = { MediaStore.Images.Media.DATA };
final Cursor imageCursor = this.getContentResolver()
.query(selectImageUri, filePathColumn, null, null, null);
final int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
final String imagePath = imageCursor.getString(columnIndex);
imageCursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}
}
Thanks for your help. :D.
Solution here is not creating a new instance of Activity but being able to access already existing instance created by Android Framework. Instance of an Activity should never be created by an application programmer.
Best approach would be to add a parameter of type Activity to the constructor of PhoneBookAdapter. Such as:
private Activity activity;
public PhoneBookAdapter(Activity activity, ArrayList<Contact> people) {
this.activity = activity;
m_people = people;
m_filteredPeople = people;
}
You can than then call activity.startActivityForResult on this instance of Activity.
You then pass in the instance of Activity when you create the adapter. In Activity you would simply pass this and in Fragment you can obtain the instance by calling getActivity() method of Fragment class.
As to processing the result of the started Activity you would need to implement this in the Activity or Fragment in which you display the list.

Categories

Resources