How to update a textview of adapter in an activity - android

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();
}

Related

Listview is setting text only for first position

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

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

Android Horizontal Gridview item overlap each other

Hi everyone I am making capture image display on horizontal gridview But I have got some problem . The gridview item contains image , but items overlap each other How can I do it here is my code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.zzbothtime.MainActivity" >
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="#+id/seatLegendLayout" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/linearLayout_gridtableLayout"
android:layout_width="900dp"
android:layout_height="100dp"
android:orientation="horizontal" >
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_margin="4dp"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="horizontal"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" >
</GridView>
</LinearLayout>
</FrameLayout>
</HorizontalScrollView>
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignLeft="#+id/horizontalScrollView1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="33dp"
android:onClick="btnAddOnClick"
android:text="Ekle" />
MainActivityCode
public class MainActivity extends Activity {
#SuppressWarnings("deprecation")
private ArrayList<MyImage> images;
private ImageAdapter imageAdapter;
private GridView 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.popupchoose);
dialog.setTitle("Alert Dialog View");
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 = (GridView) findViewById(R.id.gridView1);
listView.setAdapter(imageAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, 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.popupchoose);
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();
}
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 = (GridView) findViewById(R.id.gridView1);
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 = (GridView) findViewById(R.id.gridView1);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
}
}
}
myAdapter
public class ImageAdapter extends ArrayAdapter<MyImage>{
private static class ViewHolder {
ImageView imgIcon;
TextView description;
}
public ImageAdapter(Context context, ArrayList<MyImage> images) {
super(context,0, images);
// TODO Auto-generated constructor stub
}
#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.activity_gallery_item, parent, false);
/*
viewHolder.description =
(TextView) convertView.findViewById(R.id.item_img_infor);
*/
viewHolder.imgIcon =(ImageView) convertView.findViewById(R.id.id_index_gallery_item_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Get the data item for this position
MyImage image = getItem(position);
final int THUMBSIZE = 300;
// 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.FIT_XY);
// Return the completed view to render on screen
return convertView;
}
}
MyImageClass
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.

Android on activity result always return 0 and null intent

I tried almost all solutions found from the net and still can't solve my problem. Would anyone please help with the following codes? I really can't make it work. Even if I tried to put the setresult code in onBackPressed event, the parent activity still get result code = 0.
Start activity for result in the parent [CreatePostActivity] on touch event of a spinner:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
appState = ((ApplicationProvider) getApplicationContext());
LayoutInflater inflate = LayoutInflater.from(this);
mContent = inflate.inflate(R.layout.activity_create_post, null);
setContentView(mContent);
spinnerCategory = (Spinner) mContent.findViewById(R.id.spinnerCategory);
spinnerCategory.setOnTouchListener(this);
arrayCategory = new String[] { getResources().getString(R.string.create_post_category) };
adapterCategory = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayCategory);
spinnerCategory.setAdapter(adapterCategory);}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.spinnerCategory) {
Bundle bundle = new Bundle();
bundle.putInt("CategoryId", categoryId);
Intent intent = new Intent(this, CreatePostActivity_Category.class);
intent.putExtras(bundle);
// intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, Variables.CREATEPOST_CATEGORY_ACTIVITY_REQUEST_CODE);
}
return true;
}
Child [CreatePostActivity_Category] contains a listview and initialize with adapter like below:
listitem_select_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:padding="5dp" >
<TextView
android:id="#+id/textViewItem"
style="#style/Heading.h2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBoxItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />
</RelativeLayout>
CreatePostActivity to receive :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Variables.CREATEPOST_CATEGORY_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
System.out.println("OK");
} else
System.out.println("CANCEL");
}
}
CreatePostActivity_Category:
public class CategoryAdapter extends BaseAdapter implements OnCheckedChangeListener {
private LayoutInflater inflater = null;
public CategoryAdapter(CategoryModel[] list) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mListItems.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listitem_select_checkbox, null);
TextView textViewItem = (TextView) vi.findViewById(R.id.textViewItem);
textViewItem.setText(mListItems[position].getDescription((String) appState.getPreference(Variables.PREF_LANG)));
CheckBox checkBoxItem = (CheckBox) vi.findViewById(R.id.checkBoxItem);
if (categoryId == mListItems[position].CategoryId)
checkBoxItem.setChecked(true);
checkBoxItem.setTag(R.id.tag_id, mListItems[position].CategoryId);
checkBoxItem.setTag(R.id.tag_desc, mListItems[position].getDescription((String) appState.getPreference(Variables.PREF_LANG)));
checkBoxItem.setOnCheckedChangeListener(this);
return vi;
}
#Override
public void onCheckedChanged(CompoundButton v, boolean isChecked) {
if (isChecked) {
int id = Integer.parseInt(((CompoundButton) v).getTag(R.id.tag_id).toString());
String desc = ((CompoundButton) v).getTag(R.id.tag_desc).toString();
Bundle bundle = new Bundle();
bundle.putInt("CategoryId", id);
bundle.putString("Category", desc);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
if (getParent() == null) {
setResult(Activity.RESULT_OK, mIntent);
} else {
getParent().setResult(Activity.RESULT_OK, mIntent);
}
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
appState = ((ApplicationProvider) getApplicationContext());
database = DatabaseHelper.instance();
LayoutInflater inflate = LayoutInflater.from(this);
mContent = inflate.inflate(R.layout.activity_create_post_category, null);
setContentView(mContent);
ImageButton ibtnClose = (ImageButton) mContent.findViewById(R.id.ibtnClose);
ibtnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
listViewCategory = (ListView) mContent.findViewById(R.id.listViewCategory);
Cursor cr = database.select("SELECT category_id, edesc, cdesc FROM category");
mListItems = new CategoryModel[cr.getCount()];
if (cr != null) {
if (cr.moveToFirst()) {
int i = 0;
do {
int categoryId = cr.getInt(cr.getColumnIndex("category_id"));
String cdesc = cr.getString(cr.getColumnIndex("cdesc"));
String edesc = cr.getString(cr.getColumnIndex("edesc"));
mListItems[i] = new CategoryModel(categoryId, cdesc, edesc);
i++;
} while (cr.moveToNext());
}
}
cr.close();
CategoryAdapter mCategoryAdapter = new CategoryAdapter(mContext, mListItems);
listViewCategory.setAdapter(mCategoryAdapter);
mData = this.getIntent().getExtras();
categoryId = mData.getInt("CategoryId");
}
Before call the finish() method in your child activity,add the below code:
setResult(RESULT_OK);
Fllowing is new:
1、Add new variable:
Context mContext;
2、Change your adapter constructor:
public CategoryAdapter(Context context,CategoryModel[] list) {
mContext = context;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
3、Change finish() in adapter to:
((Activity)mContext).finish();
4、Replace your adapter's definition in your parent activity with the construction mentioned in Step 2
Finally I figured it out!!!
The original on touch listener I wrote has been fired three times, that's why it was unable to retrieve the actual return result.
Solved it by this --> Setting a spinner onClickListener() in Android
private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.getId() == R.id.spinnerCategory) {
Bundle bundle = new Bundle();
bundle.putInt("CategoryId", categoryId);
Intent intent = new Intent(mContext, CreatePostActivity_Category.class);
intent.putExtras(bundle);
startActivityForResult(intent, Variables.CREATEPOST_CATEGORY_ACTIVITY_REQUEST_CODE);
}
}
return true;
}
};
Everything works.
Thanks all for the suggested and correct answers.

Categories

Resources