Disappearing Android gridview while scrolling - android

The code is working perfect until I scroll the gridview up and down twice. When I start scrolling up and down, the contents of gridview starts to disappear from the top and gradually the screen becomes blank. I know it's a recycle issue but with next to zero programming knowledge in my head I am unable to sort out this problem. I searched here for the answers, but I failed to find out the problem of my code. That's why I decided to ask myself.
I have given codes below, I hope someone come across to sort out my isssue.
Main class
public class NEWS extends AppCompatActivity {
GridView gridView;
static final String[] MOBILE_OS = new String[] { "Mathrubhumi", "Malayala Manorama","Madhyamam","Deshabhimani", "One India","Marunadan Malayali","Janayugom",
"Janmabhumi","Kvartha","Bignews Live"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(new adapter_news(this, MOBILE_OS));
}
adapter class
public class adapter_news extends BaseAdapter {
private ImageView flag;
private Context context;
private final String[] countries;
public adapter_news(Context context, String[] countries) {
this.context = context;
this.countries = countries;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.adapter_news, null);
TextView textView = (TextView) gridView.findViewById(R.id.label);
textView.setText(countries[position]);
flag = (ImageView) gridView.findViewById(R.id.flag);
String mobile = countries[position];
if (mobile.equals("Mathrubhumi")) {
flag.setImageResource(R.drawable.mathrubhumi);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Malayala Manorama")) {
flag.setImageResource(R.drawable.malayala_manorama);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Madhyamam")) {
flag.setImageResource(R.drawable.madhyamam);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Deshabhimani")){
flag.setImageResource(R.drawable.deshabhimani);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("One India")){
flag.setImageResource(R.drawable.oneindia);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Marunadan Malayali")){
flag.setImageResource(R.drawable.marunadan);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Janayugom")){
flag.setImageResource(R.drawable.janayugom);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Janmabhumi")){
flag.setImageResource(R.drawable.janmabhumi);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else if (mobile.equals("Kvartha")){
flag.setImageResource(R.drawable.kvartha);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
} else {
flag.setImageResource(R.drawable.bignews);
flag.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("");
v.getContext().startActivity(intent);
}
}
);
}
} else {
gridView = convertView;
}
return gridView;
}
#Override
public int getCount() {
return countries.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
Main xml
<GridView
android:id="#+id/gridView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:numColumns="auto_fit"
android:columnWidth="140dp"
android:stretchMode="columnWidth"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</GridView>
Adapter xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:gravity="center">
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="#+id/label"
android:textSize="15sp" >
</TextView>

This is the description of the method:
/**
* Get the row id associated with the specified position in the list.
*
* #param position The position of the item within the adapter's data set whose row id we want.
* #return The id of the item at the specified position.
*/
#Override
public long getItemId(int position) {
return position; // return 0 here means All items are the same;
}
Base on that, return 0 from here could cause confusion to the listView. You would probably never do this. the return 0 statement is generated by the IDE and have nothing to do with the logic of the method.

Related

Trying to show thumbnail images on the side of the listview

I currently have a listview that shows all the .cue files in a directory in alphabetical order after selecting it, it uses and external program to handle the .cue file. what i would like to do is to show thumbnails matching the cue file in an imageview at the background. for example if i have a file named "a.cue" and "a.png" in the same directory, when "a.cue" is highlighted in the listview,
"a.png" is shown as a thumbnail in the background at the same time. Here is my current code:
public class openfileactivity7 extends Activity {
File path;
ListView list;
static ArrayList<String> bin_paths=new ArrayList<String>();
static ArrayList<String> bin_names=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (audioplay.isplayingAudio) {
} else {audioplay.playAudio(this, R.raw.boot);
}
list=(ListView)findViewById(R.id.listView1);
bin_paths.clear();
bin_names.clear();
path = new File("/mnt/usb_storage/USB_DISK0/udisk0/cue/pcecd");
searchFolderRecursive1(path);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, bin_names);
Collections.sort(bin_paths);
Collections.sort(bin_names);
adapter.sort(new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
});
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String path = bin_paths.get(arg2);
File file = new File(path);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/cue");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
if (audioplay.isplayingAudio) {
audioplay.stopAudio();
}
startActivity(intent);
}
});
}
private static void searchFolderRecursive1(File folder)
{
if (folder != null)
{
if (folder.listFiles() != null)
{
for (File file : folder.listFiles())
{
if (file.isFile())
{
if(file.getName().contains(".cue"))
{
// Log.e("ooooooooooooo", "path__="+file.getName());
file.getPath();
bin_names.add(file.getName());
bin_paths.add(file.getPath());
// Log.e("bin_paths", ""+bin_names);
}
}
else
{
searchFolderRecursive1(file);
}
}
}
}
}
}
Try the following example (The code below is not tested).
1) MainActivity.class-------------------
public class MainActivity extends AppCompatActivity implements ItemAdapter.Listener {
private ListView lv;
private ItemAdapter itemAdapter;
private List<String> bin_names;
private List<String> bin_paths;
private List<String> bin_images_paths;
private static final String NO_IMAGE = "no_image";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo11);
//Search for .cue files --- populate bin_names --- populate bin_path ---
// check if an image (in the same directory) for the corresponding .cue file exists:
// if yes add image path otherwise add NO_IMAGE.
// done with data population part...
lv = (ListView) findViewById(R.id.lv);
itemAdapter = new ItemAdapter(getApplication() , bin_names , bin_paths , bin_images_paths , MainActivity.this);
lv.setAdapter(itemAdapter);
}
#Override
protected void onResume() {
super.onResume();
if(itemAdapter != null){// refresh data
itemAdapter.notifyDataSetChanged();
}
}
#Override
public void PlayM(int position) {
//open file
// get file path by using bin_paths.get(position).
File file = new File(bin_paths.get(position));
if(file.exists()){
if(file.getName().contains(".cue")){
Toast.makeText(getApplicationContext() , "Play " + bin_paths.get(position) , Toast.LENGTH_LONG).show();
}else{
//refresh data.
if(itemAdapter != null){
itemAdapter.notifyDataSetChanged();
}
}
}else{
//refresh data.
if(itemAdapter != null){
itemAdapter.notifyDataSetChanged();
}
}
}
}
2) ItemAdapter.class---------------------------
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private Listener callback;
private List<String> n = new ArrayList<String>();
private List<String> p = new ArrayList<String>();
private List<String> i = new ArrayList<String>();
public ItemAdapter(Context c , List<String> n , List<String> p , List<String> i , Listener l) {
mContext = c;
callback = l;
this.n = n; //names
this.p = p; //paths
this.i = i; //images;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return p.size();
}
public Object getItem(int position) {
return p.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
TextView tv;
ImageView iv;
View view = convertView;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.demo10, null);
}
}
tv = (TextView) view.findViewById(R.id.tv);
iv = (ImageView) view.findViewById(R.id.iv);
File file = new File(p.get(position));
if(file.exists()){
if(!file.getName().contains(".cue")){// is not a .cue file
n.remove(position);
p.remove(position);
i.remove(position);
this.notifyDataSetChanged();
}else{
//everything is fine.
tv.setText(n.get(position));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback != null) {
callback.PlayM(position);
}
}
});
File image = new File(i.get(position)); // check if image exists
if(image.exists()){
if(image.getName().contains(".jpg") || image.getName().contains(".png")){
Bitmap b = BitmapFactory.decodeFile(i.get(position));
iv.setImageBitmap(b);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback != null){
callback.PlayM(position);
}
}
});
}else{
// hide imageView
iv.setVisibility(View.GONE);
}
}else{
// hide imageView
iv.setVisibility(View.GONE);
}
}
}else{ // doesn't exist
n.remove(position);
p.remove(position);
i.remove(position);
this.notifyDataSetChanged();
}
return view;
}
public interface Listener {
public void PlayM(int position);
}
}
3) demo11.xml--------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv">
</ListView>
</android.support.constraint.ConstraintLayout>
4) demo10.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:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tv"
android:textSize="17sp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_toStartOf="#id/iv"
android:layout_marginStart="20dp"
android:textStyle="bold"
android:text="Name"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_weight="20"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="10dp"
android:id="#+id/iv"/>
</RelativeLayout>

GridView displaying items incorrect

I have a GridView and it is displaying items incorrect.
I am trying to load Images with Retrofit and show them by GridView in 2 columns.
When Phones display screen shows 4 images, if total images are 8, by scrolling down repeats first 4 images. Not showing all 8 images correct.
LinerLayout:
<LinearLayout
android:id="#+id/panelBody"
android:layout_width="270dp"
android:layout_height="470dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:paddingTop="120dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="#+id/photosAddButton"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginBottom="10dp"
android:background="#drawable/drw_button_sign"
android:text="#string/add_photo"
android:textColor="#color/colorWhite"/>
<GridView
android:id="#+id/imagesGalleryGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:paddingBottom="5dp"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:background="#color/colorPrimary"></GridView>
<Button
android:id="#+id/photosUpdateButton"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginTop="-45dp"
android:background="#drawable/drw_button_sign"
android:text="#string/update_profile"
android:textColor="#color/colorWhite"/>
</LinearLayout>
Load Photos function:
public void loadPhotos() {
API_RETROFIT retrofit = this.getRetrofit();
Call<List<PROVIDER_PHOTOS>> call = retrofit.getPhotos(providerID);
call.enqueue(new Callback<List<PROVIDER_PHOTOS>>() {
#Override
public void onResponse(Call<List<PROVIDER_PHOTOS>> call, Response<List<PROVIDER_PHOTOS>> response) {
if(response.isSuccessful() && response.body() != null) {
List<PHOTO_ITEM> photoItemList = new ArrayList<PHOTO_ITEM>();
photoItemList.clear();
photoses = response.body();
for (PROVIDER_PHOTOS items : photoses) {
photoItemList.add(new PHOTO_ITEM(items.getID(), items.getPath()));
}
galleryImageAdapter = new GalleryImageAdapter(PhotosProvider.this, photoItemList);
imagesGalleryGridView.setAdapter(galleryImageAdapter);
loading.dismiss();
}
}
#Override
public void onFailure(Call<List<PROVIDER_PHOTOS>> call, Throwable t) {
call.cancel();
Toast.makeText(getApplicationContext(), R.string.checkConnection, Toast.LENGTH_LONG).show();
loading.dismiss();
}
});
}
GalleryImageAdapter:
public class GalleryImageAdapter extends BaseAdapter {
private Context context;
private List<PHOTO_ITEM> images;
public GalleryImageAdapter(PhotosProvider c, List<PHOTO_ITEM> items) {
context = c;
images = items;
}
// returns the number of images
public int getCount() {
return images.size();
}
// returns the ID of an item
public Object getItem(int position) {
return images.get(position);
}
// returns the ID of an item
public long getItemId(int position) {
return position;
}
// returns an ImageView view
public View getView(final int position, View convertView, ViewGroup parent) {
final PHOTO_ITEM pitem = getItems(position);
ImageView imageView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.provider_photos_item, null);
imageView = (ImageView) convertView.findViewById(R.id.grid_item_image408);
Picasso.with(context).load(REQUEST.UPLOADS_PATH + pitem.URL).resize(110, 110).into(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProviderGalleryView.class);
intent.putExtra("setURL", pitem.URL);
context.startActivity(intent);
}
});
ImageButton deletePhoto = (ImageButton) convertView.findViewById(R.id.deletePhoto);
deletePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // DELETE PHOTO }
});
}
return convertView;
}
PHOTO_ITEM getItems(int position) {
return ((PHOTO_ITEM) getItem(position));
}
}
Move the lines of code after you inflate the view outside the if condition:
View row = convertView;
if (row == null) {
row = inflater.inflate(R.layout.provider_photos_item, null);
}
ImageView imageView = (ImageView) row.findViewById(R.id.grid_item_image408);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProviderGalleryView.class);
intent.putExtra("setURL", pitem.URL);
context.startActivity(intent);
}
});
ImageButton deletePhoto = (ImageButton) row.findViewById(R.id.deletePhoto);
deletePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // DELETE PHOTO }
});
return row;

application not working in API 21

I have an application which has a gridview with images in it. The problem is its showing in all phones except for API 21 i.e. Lollipop version. In Lollipop its shows just background and no gridview. The targetSDK is 21 and minSDK is 8. Any help in this would be much appreciated.
MainActivity
public class MainView extends Activity {
ImageView back, home, site, header;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
setContentView(R.layout.mainview);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent myIntent = null;
if(position == 0){
myIntent = new Intent(v.getContext(), TheShow.class);
}
if(position == 1){
myIntent = new Intent(v.getContext(), Exhibitor.class);
}
if(position ==2){
myIntent = new Intent(v.getContext(), Visitor.class);
}
if(position ==3){
myIntent = new Intent(v.getContext(), Conference.class);
}
if(position ==4){
myIntent = new Intent(v.getContext(), ContactUs.class);
}
if(position == 5){
myIntent = new Intent(v.getContext(), ExhibitorReg.class);
}
if(position == 6){
myIntent = new Intent(v.getContext(), VisitorReg.class);
}
if(position == 7){
myIntent = new Intent(v.getContext(), FlrPlan.class);
}
if(myIntent!=null){
startActivity(myIntent);
}
}
});
back=(ImageView)findViewById(R.id.imageView2);
home=(ImageView)findViewById(R.id.imageView3);
site=(ImageView)findViewById(R.id.imageView4);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainView.this.onBackPressed();
}
});
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Same Page", Toast.LENGTH_LONG).show();
}
});
site.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://india-aviation.in/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
header=(ImageView)findViewById(R.id.imageView1);
header.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(MainView.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("About Us");
dialog.setCancelable(true);
Button button = (Button) dialog.findViewById(R.id.buttonOK);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
private class MyAdapter extends BaseAdapter
{
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context)
{
inflater = LayoutInflater.from(context);
items.add(new Item("The Show", R.drawable.globecopy1));
items.add(new Item("Exhibitor", R.drawable.workcopy1));
items.add(new Item("Visitor", R.drawable.visitor1copy1));
items.add(new Item("Conference", R.drawable.conferencecopy1));
items.add(new Item("Contact Us", R.drawable.contactus1copy1));
items.add(new Item("Exhibitor Registration", R.drawable.exregistercopy1));
items.add(new Item("Visitor Registration", R.drawable.anothercopy1));
items.add(new Item("Layout Plan", R.drawable.registercopy1));
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i)
{
return items.get(i);
}
#Override
public long getItemId(int i)
{
return items.get(i).drawableId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
ImageView picture;
TextView name;
if(v == null)
{
v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private class Item
{
final String name;
final int drawableId;
Item(String name, int drawableId)
{
this.name = name;
this.drawableId = drawableId;
}
}
}
}
If you app has a values-21 folder in res folder, either set the layout there or delete the folder if you want persistent layout for all APIs.

edittext value not save in listview dynamically

in my listview already 20 items and above listview there is one "ADD" button .when i am click on button then open one popup dialog.. in popup dialog there is on edittext and save and close button .. when i am write something edittext and click on save button then its not working.... i'll use custom listview with one image left side and text in center..... help me
Button add = (Button)findViewById(R.id.btn_Add);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Add Category");
Button close = (Button)dialog.findViewById(R.id.btn_cls);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_sv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)dialog.findViewById(R.id.editText1);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout 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=".MainActivity"
android:background="#drawable/black"
android:orientation="vertical">
<EditText
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/bbbb"
android:ems="10"
android:textColor="#color/White"
android:hint="Search"
android:padding="5dp"
android:textSize="20sp">
<requestFocus />
</EditText>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:dividerHeight="5dp"
android:cacheColorHint="#null"
android:listSelector="#null"
android:clipToPadding="false"
android:drawSelectorOnTop="true" />
<Button
android:id="#+id/btn_Add"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/list_selector"
android:text="ADD Category"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
listview_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_border"
android:gravity="center"
android:padding="5dp">
<ImageView
android:id="#+id/flag"
android:background="#drawable/sd"
android:layout_width="60dp"
android:layout_height="60dp"
android:adjustViewBounds="true"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp">
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="21sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/round"
android:layout_marginLeft="5dp"/>
</LinearLayout>
popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<Button
android:id="#+id/btn_cls"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:text="Close" />
<Button
android:id="#+id/btn_sv"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#drawable/list_selector"
android:text="Save" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private ListView list;
private ListViewAdapter adapter;
private EditText editsearch;
private Button add;
private String[] animal = new String[] {"COW","LION","TIGER","ELEPHANT","MONKEY","DONKEY"};
private ArrayList<String> listData;
private Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listview);
add = (Button)findViewById(R.id.btn_Add);
listData = new ArrayList<String>();
for (int i=0;i<animal.length;i++){
listData.add(animal[i]);
}
Collections.sort(listData);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addAnimal();
}
});
adapter = new ListViewAdapter(this,listData);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,listData.get(position),Toast.LENGTH_SHORT).show();
// if(listData.get(position).equals("COW"));
// intent = new Intent(getBaseContext(),COW.class);
//
// else if(listData.get(position).equals("LION"))
// intent = new Intent(getBaseContext(),LION.class);
//
// else if(listData.get(position).equals("TIGER"))
// intent = new Intent(getBaseContext(),TIGER.class);
//
// else if(listData.get(position).equals("MONKEY"))
// intent = new Intent(getBaseContext(),MOKEY.class);
//
// else if(listData.get(position).equals("DONKEY"))
// intent = new Intent(getBaseContext(),DONKEY.class);
}
});
editsearch = (EditText) findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editsearch.getText().toString();
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
}
public void addAnimal(){
dialog = new Dialog(this);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Add Animal");
final EditText edit = (EditText)dialog.findViewById(R.id.editText1);
Button close = (Button)dialog.findViewById(R.id.btn_cls);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_sv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edit.getText().toString().trim().length()>0){
listData.add(edit.getText().toString());
Collections.sort(listData);
adapter = new ListViewAdapter(MainActivity.this,listData);
list.setAdapter(adapter);
dialog.dismiss();
}else{
edit.setError("Value Required");
}
}
});
dialog.show();
}
class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
private ArrayList<String> filterData;
public ListViewAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data = data;
filterData =new ArrayList<String>();
filterData.addAll(this.data);
}
public class ViewHolder {
TextView country;
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.listview_item, null);
holder.country = (TextView) view.findViewById(R.id.country);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.country.setText(filterData.get(position));
return view;
}
public void filter(String charText) {
filterData.clear();
if (charText.length() == 0) {
filterData.addAll(data);
}else{
for (String animal : data){
if (animal.toLowerCase().contains(charText.toLowerCase())){
filterData.add(animal);
}
}
}
notifyDataSetChanged();
}
}
}
i will use like that..
public class list extends Activity {
private ListView list;
private Button add ;
private Dialog dialog;
private ListViewAdapter adapter;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView)findViewById(R.id.listview1);
add = (Button)findViewById(R.id.btn_Addd);
listData = new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AddSMS();
}
});
list.setAdapter(adapter);
}
public void AddSMS(){
dialog = new Dialog(this);
dialog.setContentView(R.layout.popup1);
dialog.setTitle("Add Your SMS");
final EditText et = (EditText)dialog.findViewById(R.id.editText11);
Button close = (Button)dialog.findViewById(R.id.btn_clss);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_svv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (et.getText().toString().trim().length()>0){
listData.add(et.getText().toString());
adapter = new ListViewAdapter(list.this, listData);
list.setAdapter(adapter);
dialog.dismiss();
}else {
et.setError("Value Required");
}
}
});
dialog.show();
}
class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
private ArrayList<String> filterData;
public ListViewAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data = data;
filterData =new ArrayList<String>();
filterData.addAll(this.data);
}
public class ViewHolder {
TextView txttt;
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.list_double, null);
holder.txttt = (TextView) view.findViewById(R.id.txttt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txttt.setText(filterData.get(position));
return view;
}
public void filter(String charText) {
filterData.clear();
if (charText.length() == 0) {
filterData.addAll(data);
}else{
for (String Detail : data){
if (Detail.toLowerCase().contains(charText.toLowerCase())){
filterData.add(Detail);
}
}
}
notifyDataSetChanged();
}
}
}
instead of add to list add the item in adapter and then call notifyDataSetChanged

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